Legal Information
Microsoft DirectX 9.0 SDK Update (October 2004)

Legal Information

DirectX 9.0 Programmer's Reference

Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.

© 1995-2004 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, Direct3D, DirectAnimation, DirectDraw, DirectInput, DirectMusic, DirectPlay, DirectShow, DirectSound, DirectX, Visual C++, Visual Studio, Win32, and XNA are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.

BLUETOOTH is a trademark owned by Bluetooth SIG, Inc. and licensed to Microsoft Corporation.

The names of actual companies and products mentioned herein may be the trademarks of their respective owners.

Note Manufacturers of telecommunications devices implementing this application programming interface (API) must ensure compliance with section 255 of the telecommunications act of 1996.

© 2004 Microsoft Corporation. All rights reserved.
Feedback? Please provide us with your comments on this topic.
For more help, visit the DirectX Developer Center.


The DirectX Software Development Kit
Microsoft DirectX 9.0 SDK Update (October 2004)

The DirectX Software Development Kit

The Microsoft DirectX software development kit (SDK) is your backstage pass to multimedia applications that sizzle. DirectX is a set of low-level application programming interfaces (APIs) for creating games and other high-performance multimedia applications. It includes support for high-performance 2-D and 3-D graphics, sound, and input.

Here is some general information about DirectX:

  • DirectX Documentation Conventions
  • DirectX 9.0 Components:
    • DirectX Graphics
    • Microsoft DirectInput
    • Microsoft DirectSound
  • What's New in DirectX 9.0 SDK Update (October 2004)
  • Security Considerations for DirectX
  • DirectX and Windows XP
  • Further Information

Audience

This documentation set is intended for developers using the C/C++ programming language. Separate documentation is available for developers using the Microsoft .NET Framework. DirectX 9.0 can be used in the Microsoft Windows 98, Windows Millennium Edition (Windows Me), Windows 2000, and Windows XP environments.

Scope

The DirectX SDK is broken into the following sections:

  • DirectX Programming Guide
  • DirectX Tools
  • DirectX Samples
  • DirectX Reference

Related Topics

Other related topics include:

  • Microsoft XNA home page The Microsoft XNA World Wide Web link software development platform is designed to integrate tools and technologies from Microsoft and its partners to enable developers to make better games and 3-D applications faster. In line with the XNA initiative, future releases of this SDK will have an increased focus on technologies, tools, and components that are shared across both Microsoft Xbox and Windows.
  • GDI+ World Wide Web link
  • OpenGL World Wide Web link
  • Windows Image Acquisition World Wide Web link


DirectX Documentation Conventions
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectX Documentation Conventions

The following conventions are used in the syntax of methods, functions, and other application programming interface (API) elements, as well as typographic conventions used in explanatory material and sample code.

Convention | Meaning
FULL BOLD CAPITALS | Used for most type and structure names.
FULL CAPITALS | Used for enumeration values, flags, and constants.
Bold text | Denotes a function, procedure, structure, macro, interface, method, data type, or other keyword in the programming interface or language.
Italic text | Denotes a placeholder or variable. You must provide the actual value. For example, the statement SetCursorPos(x,y) requires you to substitute values for the x and y parameters.
monospace
Used for code examples, syntax spacing, and user input.
[] Encloses optional parameters.
... Specifies that the preceding item may be repeated or represents an omitted portion of text or sample.
.

.

. 		Represents an omitted portion of a sample application.

Obtaining Code Syntax and Help in Visual Studio .NET

You can search the help files within Microsoft Visual Studio .NET as follows:

  • Place the cursor over a Microsoft DirectX object in code, and prototype syntax will appear.
  • Place the cursor over a DirectX object in code, then press F1, and a help page will open on that topic.
  • In a line of code, type in a DirectX method or function name, then an open parenthesis, and required parameters and their types will appear to assist completion of the method or function call.

    Code syntax display in Visual Studio .NET

Printing Help Files

To print the software development kit (SDK) Help files, complete the following steps.

  1. Open the Help file.
  2. From the File menu, click Print. The Print Topics dialog box appears.

    Print Topics dialog box

  3. Click either Print the selected topic or Print the selected heading and all subtopics.
  4. Click OK.

To print C++ graphics files, for example, the Help files can be opened from Start, All Programs, Microsoft DirectX 9.0 SDK Update (October 2004), DirectX Documentation for C++, or by double-clicking the SDK Help file at the following location:

(SDK root)\Documentation\DirectX9\

If the pages are being cut off on the right side when printing, decrease the font size so that the text does not exceed the right page margin. You can do this by clicking the Font button one or more times to choose a smaller font size before opening the Print Topics dialog box.

Location of the Font button

Using the Index

The following tips will help you quickly locate DirectX reference topics.

Help File Index

When using the Help file, click the Index tab at the left and then use this typical procedure:

  1. In the index text entry box, type the name of the DirectX method you seek. The index list will display topics that match what you have typed, along with their associated interfaces in parentheses. For example, if you type "lock", then Lock Method (IDirect3DVertexBuffer9) will be one of several Lock methods listed.
  2. Double-click the appropriate entry to open its documentation.

Visual Studio .NET Index

When using the documentation within Visual Studio .NET, select Index... from the Help menu and then use this typical procedure:

  1. In the Look for box, type the name of the DirectX method you seek.
  2. If the method name displays in the index list, double-click the method name. An Index Results pane will appear that lists all interfaces containing the method.
  3. Double-click the appropriate entry to open its documentation.
  4. To find only DirectX topics, click the Location column to sort by technology, then scroll the list until you find the topics marked DirectX 9.0 C++.

Visual Studio .NET with Index and Index Results panes

Searching the Help Files

To begin a search in the Help file, click the Search tab. Type in the word or phrase you are looking for. To do partial word searches, use the * wildcard. For example, a search for "D3DXLoad*" returns all references to functions that begin with D3DXLoad.


DirectX 9.0 Components
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectX 9.0 Components

Microsoft DirectX 9.0 is made up of the following components.

  • DirectX Graphics combines the Microsoft DirectDraw and Microsoft Direct3D components of previous DirectX versions into a single application programming interface (API) that you can use for all graphics programming. The component includes the Direct3D extensions (D3DX) utility library, which simplifies many graphics programming tasks.
  • Microsoft DirectInput provides support for a variety of input devices, including full support for force-feedback technology.
  • Microsoft DirectSound can be used in the development of high-performance audio applications that play and capture waveform audio.


What's New in DirectX 9.0 SDK Update (October 2004)
Microsoft DirectX 9.0 SDK Update (October 2004)

What's New in DirectX 9.0 SDK Update (October 2004)

Follow the links below to see the latest features in each of the components for this Microsoft DirectX release.

  • What's New in DirectX Graphics
  • What's New in DirectInput
  • What's New in DirectSound

In order to provide further advances in developer tools, the status of several DirectX components has been changed.

  • Microsoft DirectPlay is intended to address identified security issues through December 31, 2004. Game developers should use enhanced core Microsoft Windows networking technologies as they become available.
  • Microsoft DirectInput, Microsoft DirectMusic, Microsoft DirectShow, and Microsoft DirectSound will maintain their current status until new technology in these areas is made available.

    Note When the DirectX software development kit (SDK) has been loaded, the DirectMusic, DirectPlay, and DirectShow documentation can be found at the following location:

    (SDK Root)\Documentation\DirectX9

    Documentation for these DirectX components is also available on the MSDN Library:

    • DirectMusic World Wide Web link
    • DirectPlay World Wide Web link
    • DirectShow World Wide Web link
  • Use of Microsoft DirectDraw is no longer recommended. With the release of DirectX 9.0, all two-dimensional (2-D) functionality is contained within Microsoft Direct3D and its associated helper functions in the Direct3D extensions (D3DX). However, the DirectDraw documentation is still available and can be viewed at the MSDN Library Archive at DirectDraw World Wide Web link.


Security Considerations for DirectX
Microsoft DirectX 9.0 SDK Update (October 2004)

Security Considerations for DirectX

This topic provides information about security considerations related to Microsoft DirectX 9.0. This topic does not provide all you need to know about security issues. Instead, use it as a starting point and reference for this technology area.

For general security topics, such as avoiding buffer overruns and running with special privileges, see Security Developer Center World Wide Web link.

For more information about writing secure code, see the following resource:

  • Howard, Michael, and David LeBlanc. Writing Secure Code. Redmond, WA: Microsoft Press, 2002.


Further Information
Microsoft DirectX 9.0 SDK Update (October 2004)

Further Information

For the latest about Microsoft DirectX, see the MSDN DirectX World Wide Web link Web site. This site contains DirectX downloads, the latest DirectX documentation, the "Driving DirectX" column, links to the DirectX newsgroups, and more.

See Further Information on 3-D Graphics for a list of suggested references on three-dimensional computer graphics and Microsoft Direct3D.

You can find more information about sound and music discussed throughout the DirectX documentation, as well as information about Microsoft Windows programming in general, in the following sources.

  • Begault, Durand R. 3-D Sound for Virtual Reality and Multimedia. Academic Press, 1994.
  • Dodge, Charles, and Thomas A. Jerse. Computer Music: Synthesis, Composition, and Performance. Second ed. Schirmer Books, 1997.
  • Kientzle, Tim. A Programmer's Guide to Sound. Addison-Wesley Developers Press, 1998.

Additional sources for the concepts and terms associated with Component Object Model (COM) can be found in the following sources:

  • Brockschmidt, Kraig. Inside OLE 2. Second ed. Microsoft Press, 1995.
  • Rogerson, Dale E. Inside COM. Microsoft Press, 1997.


DirectX and Windows XP
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectX and Windows XP

This topic contains tips for using Microsoft DirectX on Microsoft Windows XP.

  • Handling Multiple Users
  • Fast User Switching
  • File Storage
  • Registry Storage
  • Obtaining DirectX Version

Handling Multiple Users

Windows XP allows multiple users to be logged on to one computer at the same time. If your application cannot run multiple instances simultaneously, you should check to see if another instance is running before starting a new instance. You cannot use FindWindow across desktop sessions. FindWindow only works within the current session.

To see if an instance of the application is already running, use a global mutex. If an instance is running, you can use FindWindow to see if the instance is in the current session and restore the window. Otherwise, notify users that they cannot use the application.

Fast User Switching

Fast User Switching allows users to switch between sessions. Users do not have to terminate their applications or log out for another user to start a session. Instead, they use Fast User Switching, which enables another user to log on and work on the computer.

DirectX applications should be prepared to handle this situation. Windows will send out a WM_WTSSESSION_CHANGE message when a user session changes. In order to receive this message, your application must register its window handle by calling WTSRegisterSessionNotification.

Note Microsoft DirectDraw and Microsoft Direct3D applications that set the window to full screen by default will not allow Fast User Switching.

File Storage

There are two types of users on Windows XP: administrators and limited users. Administrators have read/write access to all of the hard drive. Limited users are restricted to a few areas of the hard drive where they can write data.

The only areas of the hard drive that limited users have write access to, and therefore the only place DirectX applications should store information for limited users, are the following (default) directories:

CSIDL value | Folder
CSIDL_COMMON_DOCUMENTS | C:\Documents and Settings\All Users\Documents
CSIDL_PERSONAL | C:\Documents and Settings\<username>\MyDocuments
CSIDL_COMMON_APPDATA | C:\Documents and Settings\All Users\Application Data
CSIDL_LOCAL_APPDATA | C:\Documents and Settings\<username>\Application Data

Because installation should be to the Program Files directory (CSIDL_PROGRAM_FILES) by default, only an administrator can install an application. If a limited user is trying to install an application, an informational message box should be displayed telling the user that they need administrator privileges to install.

All of these locations should be determined by passing the appropriate CSIDL to the SHGetFolderPath function, rather than being hard-coded.

Data files generated by an application should be stored with limited users in mind. Use the following table to determine where to store the data.

Data available for: | CSIDL value | Can user load, view, and alter data? | Example
All users | CSIDL_COMMON_APPDATA | NO | System configuration
Current user | CSIDL_LOCAL_APPDATA | NO | Keyboard bindings
All users | CSIDL_COMMON_DOCUMENTS | YES | Shared saved files
Current user | CSIDL_PERSONAL | YES | Private saved files

Note If the user is meant to load, view, and alter data, ensure that there is a file association and icon representative to the application.

Registry Storage

To correctly store data in the registry, use the following guidelines.

  • Require administrator privileges for installation.
  • Be sure that each registry key item is less than 64 KB of data.
  • Registry data can exist in HKEY_LOCAL_MACHINE or HKEY_CURRENT_USER.

    HKEY_LOCAL_MACHINE

    • Only administrators have access, so do not store information that limited users will need to access in HKEY_LOCAL_MACHINE.
    • If you have data that few users must access, place it in HKEY_LOCAL_MACHINE.
    • Store computer configuration data in HKEY_LOCAL_MACHINE.

    HKEY_CURRENT_USER

    • Both administrators and limited users have access.
    • Any data that the "limited users" will need to access should be in HKEY_CURRENT_USER.
    • Store user configuration data in HKEY_CURRENT_USER.
    • When the game is first started, check the registry keys in HKEY_CURRENT_USER and make sure the default values exist.

Obtaining DirectX Version

Your application can check the installed DirectX version with D3DXCheckVersion or DirectXSetupGetVersion. The version of DirectX can also be obtained by running the DirectX Diagnostic Tool, or by using the DirectX Version Checking Sample at the following location:

(SDK root)\Samples\C++\Misc\GetDXVer

Alternately, the DirectX version can be obtained from the following registry key:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\DirectX\

Name | Type | Data
Version | REG_SZ | A string value that represents the currently installed DirectX version, in the following format: x.xx.xx.xxxx


DirectX Programming Guide
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectX Programming Guide

This section contains information for using Microsoft DirectX applications.

  • Programming DirectX with C/C++
  • DirectSetup Essentials
  • Using COM


Programming DirectX with C/C++
Microsoft DirectX 9.0 SDK Update (October 2004)

Programming DirectX with C/C++

Most Microsoft DirectX application development with C/C++ involves conventional programming techniques. However, there are several aspects of DirectX programming that may be unfamiliar to some developers. This section provides a brief overview of several specialized topics, along with some guidelines for compiling and debugging DirectX applications.

  • Using Callback Functions
  • Debugging DirectX Applications


Using Callback Functions
Microsoft DirectX 9.0 SDK Update (October 2004)

Using Callback Functions

A callback function is essentially an event handler that is implemented by an application and called by the system. Microsoft Windows applications typically implement multiple callback functions, each one designed for a particular set of events. When an event occurs, the system notifies the application by calling the appropriate callback function. The callback function also usually has a parameter list that the system can use to pass the application more detailed information about the event. The most common example of a callback function is the window procedure. This function is used by the system to pass Windows messages to the applications that owns the window.

Microsoft DirectX uses callback functions for a variety of purposes. For example, your system supports multiple devices. Microsoft DirectInput represents each device by a device object, that contains the details of the device's capabilities. Your application will typically need to enumerate the available devices and to examine the device objects in order to handle user input properly. To do this enumeration, you must implement a DIEnumDeviceObjectsCallback callback function.

You start the enumeration process by calling IDirectInputDevice8::EnumObjects and passing the method a pointer to your DIEnumDeviceObjectsCallback callback function. The system will call this function once for each device, and it will pass in a DIDEVICEOBJECTINSTANCE structure containing information about the device's capabilities. After your callback function has processed the information, it can return DIENUM_CONTINUE to request the next device object, or DIENUM_STOP to stop the enumeration.

DirectX uses a number of other callback functions for a variety of purposes. For details, see the documentation for the particular DirectX component.

Implementing a Callback Function

Because callback functions have different purposes and usage, they are documented in the appropriate reference section in much the same way as a regular function. However, a callback function reference is essentially a template that describes how to implement the function, not a normal application programming interface (API) reference. The callback function reference provides the following information:

  • How the function is used
  • The function's syntax
  • An explanation of the information that will be contained by each parameter
  • An explanation of the possible return values

You should declare the function as a CALLBACK or WINAPI type. Either type is acceptable. You can use any function name. The name used in the documentation is just a convenient label for a particular callback function.

Implement the function according to the description in the reference. The implementation details will depend on the particular function and the requirements of your application. See the sample code for some examples of how to implement various callback functions.

Pass a pointer to the function to the appropriate DirectX component. The DirectX component can then use the function pointer to call the function. The way in which you pass this pointer varies from function to function, so you should see the particular function's reference for details.

The following code fragment is borrowed from the DirectInput Joystick sample. It sketches out the essential elements of a DIEnumDeviceObjectsCallback implementation that is used to enumerate the axes of a joystick.

// The function declaration
BOOL CALLBACK EnumAxesCallback( const DIDEVICEOBJECTINSTANCE* pdidoi,
                                VOID* pContext );
...
// Pass the function pointer to DirectInput by calling the
// IDirectInputDevice9::EnumObjects method

if ( FAILED( hr = g_pJoystick->EnumObjects(EnumAxesCallback,
                                            (VOID*)hDlg,
                                            DIDFT_AXIS )));

...

// The function implementation
BOOL CALLBACK EnumAxesCallback( const DIDEVICEOBJECTINSTANCE* pdidoi,
                                VOID* pContext )
{
// Process the information passed in through the two parameters
// Return DIENUM_CONTINUE to request the next device object
// Return DIENUM_STOP to stop the enumeration
}


Debugging DirectX Applications
Microsoft DirectX 9.0 SDK Update (October 2004)

Debugging DirectX Applications

This section covers the following topics pertaining to debugging C and C++ applications.

  • Debug vs. Retail DLLs
  • Removing or Adding Debug DLLs
  • Other Resources

Debug vs. Retail DLLs

The Microsoft DirectX software development kit (SDK) installation program provides the option of installing either debug or retail builds of the DirectX dynamic-link libraries (DLLs).

When you develop software in C++, it is best to install the debug versions of the DLLs. This option installs both debug and retail DLLs on your system (the retail version installs only the retail DLLs). The debug DLLs have additional code that validates internal data structures and outputs debug error messages, using the OutputDebugString function while your program is executing. When an error occurs, the debug output gives you a more detailed description of the problem. The debug DLLs run more slowly than the retail DLLs but are much more useful for debugging an application. Be sure to ship the retail version with your application.

If you have the debug SDK installed, you can use the DirectX Control Panel utility to switch between the debug and retail builds of most components. To enable this feature, select the Debug option when you install the SDK.

To see the debug messages, configure your system so that debug output appears in a window or on a remote computer. A development environment such as Microsoft Visual Studio .NET enables you to do this. Consult the environment documentation for setup instructions.

To ensure that the debugger can find the relevant symbolic information when using debug builds, locate the symbol files as follows:

Operating system | Debugger | .pdb file location | .dbg file location
Microsoft Windows 98 | Microsoft Visual C++ | Same directory as binary | Same directory as binary
Windows 2000 | Visual Studio .NET | Same directory as binary | %SystemRoot%\Symbols\<binary extension>\
Microsoft Windows NT, Windows 2000 | Visual C++ | Same directory as binary | %SystemRoot%\Symbols\<binary extension>\
Windows NT, Windows 2000 | NTSD/KD | %SystemRoot%\Symbols\<binary extension>\ | %SystemRoot%\Symbols\<binary extension>\
Windows XP | Visual Studio .NET | Same directory as binary | %SystemRoot%\Symbols\<binary extension>\

Note When debugging with the Visual C++ development system on Windows NT or Windows 2000, do not use the Splitsym development tool. Splitsym copies private symbolic information from the <binary>.dbg file into the symbol directory under the binary extension—for example, %SystemRoot%\Symbols\Dll\—and deletes the original file from the binary directory. Visual C++ relies on finding a private symbolic information (<binary>.dbg) file in the same directory as the binary. Therefore, for debug builds, you must copy the private symbolic information and not delete it. This is an issue only when using Visual C++ with Windows NT or Windows 2000. Consult Visual C++ documentation and Windows 2000 Driver Development Kit (DDK) documentation for more debugging information.

Removing or Adding Debug DLLs

If you installed the retail runtime and would like to change to the debug runtime, run Dxsetup.exe, which is located in the (SDK root)\Redist\DirectX9\ folder.

If you have the debug runtime and would like to revert to the retail runtime, run Undxxpdebug.exe, which is located in the Windows System folder. You can also run this by selecting Run from the Start menu and typing undxxpdebug in the box.

Note If you are using Windows 98, Windows Millennium Edition (Windows Me) or Windows 2000, you will need to uninstall the DirectX SDK in order to remove the debug version of the runtime.

Other Resources

To find C++ memory corruption problems, consider using a memory corruption/leak tool like Compuware's BoundsChecker World Wide Web link.

Microsoft maintains a database of "knowledge base" articles on MSDN. Go to msdn.microsoft.com World Wide Web link and search for Knowledge Base Articles. Then search for the topic you need.

The AppVerifier tool monitors an application for things like heap corruption, locks usage, invalid handles, and thread stack size checking. To find the tool, search for Testing Applications with AppVerifier on the MSDN Library World Wide Web link.


DirectSetup
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectSetup

The DirectSetup application programming interface (API) facilitates one-call installation of the Microsoft DirectX components. This is more than a convenience; DirectX is a complex product, and installing it is an involved task.

DirectSetup includes several API functions and structures. It also includes a prototype DirectXSetupCallbackFunction that can be defined by an application to customize the user interface during the installation process. The DirectX software development kit (SDK) includes a sample application that demonstrates the use of this callback function.

If you do not want to create your own custom installation, you can use the DXSetup.exe standard installation provided with the SDK.

Note Follow the instructions for Redistributable Code contained in the license agreements within the following folder:

(SDK root)\Documentation\License Agreements

For further information, see the following topics:

  • Setup Overview for DirectSetup
  • Preparing the Setup Folder
  • Customizing Setup
  • Creating a DirectSetup Callback Function
  • Testing the Setup Program
  • Enabling AutoPlay
  • DirectX Redistribution
  • DXSetup.exe


Setup Overview for DirectSetup
Microsoft DirectX 9.0 SDK Update (October 2004)

Setup Overview for DirectSetup

Applications and games that depend on Microsoft DirectX use the DirectXSetup function to install the necessary system components into an existing Microsoft Windows installation. The function optionally updates the display and audio drivers for optimal support of DirectX. Typically, you would call DirectXSetup from the program that you are using to install your own application files.

Warning The DirectXSetup function overwrites system components from previous versions of DirectX. For example, if you install DirectX 8.0 on a system that already has DirectX 7.0 components, all DirectX 7.0 components are overwritten. Because all DirectX components comply with Component Object Model (COM) backward-compatibility rules, software written for DirectX 7.0 continues to function properly.

The DirectXSetup function can tell when DirectX components, display drivers, and audio drivers need to be upgraded. It can also distinguish whether these components can be upgraded without adversely affecting the Windows operating system. This is said to be a safe upgrade. The upgrade is safe for the operating system, not necessarily for the applications running on the computer. Some hardware-dependent applications can be negatively affected by an upgrade that is safe for Windows.

By default, the DirectXSetup function performs only safe upgrades. If the upgrade of a device driver might adversely affect the operation of Windows, the upgrade is not performed.

During the setup process, DirectSetup creates a backup copy of the system components and drivers that are replaced. These can be restored if problems occur.

When display or audio drivers are upgraded, the DirectXSetup function uses a database created by the system to manage the process. The database contains information about existing drivers that are provided by Microsoft, the manufacturers of the hardware, or the vendors of the hardware. This database describes the upgrade status of each driver, based on testing done at Microsoft and other sites.

Check the value returned by DirectXSetup. If it is DSETUPERR_SUCCESS_RESTART, notify the user that changes do not take effect without a restart, and offer the choice of restarting immediately. For an example of how to do this, see Dinstall.c in the Dinstall Sample.


Preparing the Setup Folder
Microsoft DirectX 9.0 SDK Update (October 2004)

Preparing the Setup Folder

The DirectXSetup function takes a parameter, lpszRootPath, that points to the root directory of the installation. It can be NULL to indicate that the root path is the current directory—that is, the directory where your setup program resides.

The root directory must contain Dsetup.dll and Dsetup32.dll. It must also have a folder named "DirectX" (this name is not case sensitive), containing all the redistributable files and drivers. To create the proper structure on your application setup disk, copy the redistributable code from one of the following locations into the root path of your setup program.

  • Installed by the software development kit (SDK) at (SDK root)\Redist\DirectX9
  • On the Microsoft DirectX 9.0 CD at (CD root)\Redist\DirectX9
  • SDK download at (Extracted location)\Redist\DirectX9
  • A separate download at http://msdn.microsoft.com/downloads World Wide Web link

These files must be included in any distribution of DirectX 9.0 as explained by the "DirectX Redist.txt" file found at:

(CD root)\Documentation\License Agreements\DirectX Redist.txt


Customizing Setup
Microsoft DirectX 9.0 SDK Update (October 2004)

Customizing Setup

Microsoft DirectSetup enables you to define a callback function for customizing the Microsoft DirectX setup process. In the DirectSetup documentation, this callback function is referred to as DirectXSetupCallbackFunction, but you can give it any name.

If a callback function is not provided by the setup program, the DirectXSetup function displays status and error information in a dialog box and obtains user input by calling the Microsoft Win32 MessageBox function. If a callback is provided, the information that would have been used to create the status dialog or message box is instead passed to the callback. The callback function is called once for each DirectX component and device driver that can be installed or upgraded.

You can use the callback function to do the following:

  • Employ a custom interface. Your setup program might display messages in ways other than by using MessageBox or standard Microsoft Windows dialog boxes. The callback function enables you to integrate messages for the DirectX component of your installation into your own interface.
  • Update a progress indicator.
  • Suppress the display of status and error messages. Designers of programs for novice users might want to suppress error messages and let the setup program handle errors and make upgrade choices silently. This approach requires a greater development effort for the setup program, but it might be appropriate for the target audience.

For help customizing your setup, see Creating a DirectSetup Callback Function.


Creating a DirectSetup Callback Function
Microsoft DirectX 9.0 SDK Update (October 2004)

Creating a DirectSetup Callback Function

To customize the setup process, first create a callback function that conforms to the DirectXSetupCallbackFunction prototype, as in the following declaration.

DWORD WINAPI DirectXSetupCallbackFunction(
        DWORD dwReason,
        DWORD dwMsgType,
        LPSTR szMessage,
        LPSTR szName,
        void *pInfo);

In this example, adapted from the Dinstall Sample sample application, the name of the function is the same as that of the prototype, but this is optional. The parameter names differ slightly from those in the prototype declared in the Dsetup.h header file and are used throughout the following discussion.

  • Parameters
  • Return Value
  • Setting the Callback Function

Parameters

The dwReason parameter indicates why the callback function has been called. The possible values are listed and explained in the reference for DirectXSetupCallbackFunction.

The dwMsgType parameter receives flags equivalent to those that DirectSetup would, by default, pass to MessageBox, such as those controlling which buttons and icons are displayed. Of special interest are the button flags, which you use to determine what return values are expected. If this value is 0, the event never requires user input, and DirectSetup normally displays a status message.

The szMessage parameter receives the same text that DirectSetup would otherwise pass to the status dialog box or to MessageBox.

When a driver is a candidate for upgrading, its name is passed in the szName parameter, and pInfo points to information about how the upgrade is to be handled—for example, whether DirectSetup recommends that the old driver be kept or upgraded.

The way your callback function interprets the parameters is entirely up to you. Typically, you would choose which messages to display (based on dwReason) and when to present the user with alternatives, and you would modify the interface accordingly.

Return Value

The value returned by your callback function must conform to the following rules.

  • When dwMsgType is 0, the return value must be IDOK. In this case, there are no choices to be made by the user. Your application, of course, can display a status message, even though no input is required.
  • If dwMsgType is nonzero, the return value must be the same as would have been returned by MessageBox, given the equivalent choice by the user.

To determine the appropriate return value in the second case, test dwMsgType for the buttons that would normally have been put in a message box. The following example, from the GetReply function in Dinstall, shows how this is done.

/* The global g_wReply identifies the custom dialog button
   that has been selected by the user. */

switch (dwMsgType & 0x0000000F)
{
   / * There would normally have been an OK and a Cancel button.
       IDBUT1 is equivalent to the OK button. If the user did not
       choose that, it was a Cancel. */
    case MB_OKCANCEL:
        wDefaultButton = (g_wReply == IDBUT1) ? IDOK : IDCANCEL;
        break;
    / * And so on with the other button combinations. */
    case MB_OK:
        wDefaultButton = IDOK;
        break;
    case MB_RETRYCANCEL:
        wDefaultButton = (g_wReply == IDBUT1) ? IDRETRY : IDCANCEL;
        break;
    case MB_ABORTRETRYIGNORE:
        if (g_wReply == IDBUT1)
            wDefaultButton = IDABORT;
        else if (g_wReply == IDBUT2)
            wDefaultButton = IDRETRY;
        else
            wDefaultButton = IDIGNORE;
        break;
    case MB_YESNOCANCEL:
        if (g_wReply == IDBUT1)
            wDefaultButton = IDYES;
        else if (g_wReply == IDBUT2)
            wDefaultButton = IDNO;
        else
            wDefaultButton = IDCANCEL;
        break;
    case MB_YESNO:
        wDefaultButton = (g_wReply == IDBUT1) ? IDYES : IDNO;
        break;
    default:
        wDefaultButton = IDOK;
}

This routine translates button clicks from the custom interface into the equivalent button identifiers in the standard dialog box that DirectSetup would otherwise create. The wDefaultButton variable is set to the identifier of the equivalent standard dialog box button, and this value is ultimately returned from the callback function.

Setting the Callback Function

Before calling DirectXSetup, notify DirectSetup that you want to use a callback by calling the DirectXSetupSetCallback function, passing a pointer to the callback as a parameter. The following example shows how this is done.

DirectXSetupSetCallback(
        (DSETUP_CALLBACK) DirectXSetupCallbackFunction);


Testing the Setup Program
Microsoft DirectX 9.0 SDK Update (October 2004)

Testing the Setup Program

To test the DirectSetup component of your setup program, compile a version in which the DSETUP_TESTINSTALL flag is passed to the DirectXSetup function. Set up the installation directory, as described in Preparing the Setup Folder.

When you run your setup program, DirectSetup goes through the motions of installing Microsoft DirectX, including calls to your callback function if you have provided one, without actually installing any components.


Enabling AutoPlay
Microsoft DirectX 9.0 SDK Update (October 2004)

Enabling AutoPlay

If you are building an AutoPlay compact disc title, copy the Autorun.inf file in the root directory of the Microsoft DirectX software development kit (SDK) compact disc to the root of your application directory. This text file contains the following information.

[autorun]
OPEN=SETUP.EXE

If your application's setup program is called Setup.exe, you do not have to make any changes to this file; otherwise, edit this file to contain the name of your setup program.


DirectX Redistribution
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectX Redistribution

Stand-alone developer runtime installers only install the Microsoft DirectX developer and debug runtime for redistribution purposes. These installers are available for all supported platforms and are located at the following location:

(SDK root)\Developer Runtime\

Applications can use the supplied standard installer, DXSetup.exe, to redistribute DirectX.

Note Follow the instructions for Redistributable Code contained in the license agreements within the following folder:

(SDK root)\Documentation\License Agreements


DXSetup.exe
Microsoft DirectX 9.0 SDK Update (October 2004)

DXSetup.exe

DXSetup.exe is a standard installer that independent software vendors (ISVs) can use to install the Microsoft DirectX 9.0 redistributable runtime. It provides an easy way for developers to install the DirectX 9.0 runtime without having to write a custom installer. The standard installer is included in the following folder:

(SDK root)\Redist\DirectX9

DXSetup.exe uses the DirectSetup application programming interface (API) for version checking, setting up install type, displaying the end-user license agreement (EULA), installing DirectX, progress reporting, and message handling. DXSetup.exe displays all user interface (UI) components during the DirectX 9.0 installation. These include the click-through-EULA, progress meter, and message handling.

Developers who need to install the Managed DirectX component and are using the standard installer must perform the following steps.

  1. Before calling DXSetup.exe, verify the Microsoft .NET Framework is installed.
  2. Call DXSetup.exe with the /InstallManagedDX command line attribute.

The following is an example of how to use the standard installer for Managed DirectX.

DXSetup.exe /InstallManagedDX

DXSetup.exe Supports the Microsoft Windows 98, Windows 98 Second Edition, Windows Millennium Edition (Windows Me), Windows 2000, and Windows XP operating systems.

DXSetup.exe supports the following languages:

  • Chinese (Simplified)
  • Chinese (Traditional)
  • Czech
  • Dutch
  • English (American)
  • French
  • German
  • Italian
  • Japanese
  • Korean
  • Polish
  • Portuguese (Brazil)
  • Russian
  • Spanish
  • Swedish


Using COM
Microsoft DirectX 9.0 SDK Update (October 2004)

Using COM

The Component Object Model (COM) is an object-oriented programming model used by numerous applications. Because the bulk of the Microsoft DirectX run time is in the form of COM-compliant objects, all DirectX developers need to have at least a basic understanding of COM principles and programming techniques. Although COM has a reputation for being difficult and complex, the COM programming required by most DirectX applications is straightforward.

There are two distinct types of COM programming:

  • Using existing COM objects. This is not much more difficult than using C++ objects.
  • Implementing your own COM objects. This can be a complicated and demanding task. Much of COM's reputation for complexity comes from this type of COM programming.

Most DirectX applications need to use only the COM objects provided by DirectX. They do not need to implement their own COM objects. In other words, most DirectX developers will need to concern themselves only with the first, and easiest, type of COM programming.

This section provides a brief introduction to using the COM objects provided by DirectX. It is primarily intended for novice COM programmers. For a more detailed discussion of how to use COM objects, or for information about how to implement your own COM objects, see Further Information.

  • COM Object Overview
  • Creating a COM Object
  • Using COM Interfaces
  • Managing a COM Object's Lifetime
  • Using C to Access COM Objects
  • Using Macros to Call DirectX COM Methods
  • DirectX COM Documentation Conventions
  • Using ATL with DirectX 9.0 COM Interfaces
  • IUnknown


COM Object Overview
Microsoft DirectX 9.0 SDK Update (October 2004)

COM Object Overview

Component Object Model (COM) objects are basically black boxes that can be used by applications to perform one or more tasks. They are most commonly implemented as a dynamic-link library (DLL). Like a conventional DLL, COM objects expose methods that your application can call to perform any of the supported tasks. Applications interact with COM objects in somewhat the same way they do with C++ objects. However, there are some distinct differences:

  • COM objects enforce stricter encapsulation than C++ objects. You cannot just create the object and call any public method. A COM object's public methods are grouped into one or more interfaces. To use a method, you must create the object and obtain the appropriate interface from the object. An interface typically contains a related set of methods that provide access to a particular feature of the object. For example, the IDirect3DCubeTexture9 interface contains methods that enable you to manipulate cube texture resources. Any methods that are not part of an interface are not accessible.
  • COM objects are not created in the same way as C++ objects. There are several ways to create a COM object, but all involve COM-specific techniques. The Microsoft DirectX application programming interface (API) includes a variety of helper functions and methods that simplify creating most of the DirectX objects.
  • You must use COM-specific techniques to control the lifetime of the object.
  • COM objects do not need to be explicitly loaded. COM objects are typically contained in a DLL. However, you do not need to explicitly load the DLL or link to a static library in order to use a COM object. Each COM object has a unique registered identifier that is used to create the object. COM automatically loads the correct DLL.
  • COM is a binary specification. COM objects can be written in and accessed from a variety of languages. You don't need to know anything about the object's source code. For example, Microsoft Visual Basic applications routinely use COM objects that were written in C++.

This document contains the following sections.

  • Objects and Interfaces
  • GUIDs
  • HRESULT Values
  • The Address of a Pointer

Objects and Interfaces

It is important to understand the distinction between objects and interfaces. In casual usage, an object may sometimes be referred to by the name of its principle interface. However, strictly speaking, the two terms are not interchangeable.

  • An object may expose any number of interfaces. For example, while all objects must expose the IUnknown interface, they normally expose at least one additional interface, and they might expose many. In order to use a particular method, you must not only create the object, you must also obtain the correct interface.
  • More than one object might expose the same interface. An interface is a group of methods that perform a specified set of operations. The interface definition specifies only the syntax of the methods and their general functionality. Any COM object that needs to support a particular set of operations can do so by exposing a suitable interface. Some interfaces are highly specialized and are exposed only by a single object. Others are useful in a variety of circumstances and are exposed by many objects. The extreme case is the IUnknown interface, which must be exposed by all COM objects.
Note If an object exposes an interface, it must support every method in the interface definition. In other words, you can call any method and be confident that it exists. However, the details of how a particular method is implemented may vary from object to object. For example, different objects may use different algorithms to arrive at the final result. There is also no guarantee that a method will be supported in a nontrivial way. Sometimes an object exposes a commonly-used interface, but needs to support only a subset of the methods. You will still be able to call the remaining methods successfully, but they will return E_NOTIMPL. You should refer to the documentation to see how an interface is implemented by any particular object.

The COM standard requires that an interface definition must not change once it has been published. You cannot, for example, add a new method to an existing interface. You must instead create a new interface. While there are no restrictions on what methods must be in that interface, a common practice is to have the next-generation interface include all the of the old interface's methods, plus any new methods.

It is not unusual for an interface to have several generations. Typically, all generations perform essentially the same overall task, but they will be different in detail. Often, an object will expose every generation of interface. Doing so allows older applications to continue using the object's older interfaces, while newer applications can take advantage of the features of the newer interfaces. Typically, a family of interfaces will all have the same name, plus an integer indicating the generation. For example, if the original interface were named IMyInterface, the next two generations would be called IMyInterface2 and IMyInterface3. DirectX typically labels successive generations of interfaces with the DirectX version number.

GUIDs

Globally unique identifiers (GUIDs) are a key part of the COM programming model. At its most basic, a GUID is a 128-bit structure. However, GUIDs are created in such as way as to guarantee that no two GUIDs are the same. COM uses GUIDs extensively for two primary purposes:

  1. To uniquely identify a particular COM object. A GUID that is assigned to a COM object is called a class identifier (CLSID). You use a CLSID when you want to create an instance of the associated COM object.
  2. To uniquely identify a particular COM interface. The GUID that is associated with a particular COM interface is called an interface identifier (IID). You use an IID when you request a particular interface from an object. An interface's IID will be the same, regardless of which object exposes the interface.
Note For convenience, documentation normally refers to objects and interfaces by a descriptive name such as IDirect3D9. In the context of the documentation, there is rarely any danger of confusion. However, strictly speaking, there is no guarantee that another object or interface does not have the same descriptive name. The only unambiguous way to refer to a particular object or interface is by its GUID.

Although GUIDs are structures, they are often expressed as an equivalent string. The general format of the string form of a GUID is 32 hexadecimal digits in the format 8-4-4-4-12. That is, "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}," where each x corresponds to a hexadecimal digit. For example, the string form of the IID for the IDirect3D9 interface is:

{1DD9E8DA-1C77-4D40-B0CF-98FEFDFF9512}

Because the actual GUID is somewhat clumsy to use and easy to mistype, an equivalent name is usually provided as well. You can use this name instead of the actual structure when you call functions such as CoCreateInstance. The customary naming convention is to prepend either IID_ or CLSID_ to the descriptive name of the interface or object, respectively. For example, the name of the IDirect3D9 interface's IID is IID_IDirect3D9.

HRESULT Values

All COM methods return a 32-bit integer called an HRESULT. With most methods, the HRESULT is essentially a structure that contains two primary pieces of information:

  • Whether the method succeeded or failed.
  • More detailed information about the outcome of the operation supported by the method.

Some methods return HRESULT values only from the standard set defined in Winerror.h. However, methods are free to return custom HRESULT values with more specialized information. These values are normally documented on the method's reference page.

Note The list of HRESULT values that you find on a method's reference page is often only a subset of the possible values that may be returned. The list typically covers only those values that are specific to the method and those standard values that have some method-specific meaning. You should assume that a method may return a variety of standard HRESULT values, even if they are not explicitly documented.

While HRESULT values are often used to return error information, you should not think of them as error codes. The fact that the bit that indicates success or failure is stored separately from the bits that contain the detailed information allows HRESULT values to have any number of success and failure codes. By convention, success codes are given names with an S_ prefix, and failure codes with an E_ prefix. For example, the two most commonly used codes are S_OK and E_FAIL, which indicate simple success or failure, respectively.

The fact that COM methods may return a variety of success or failure codes means that you have to be careful how you test the HRESULT value. For example, consider a hypothetical method with documented return values of S_OK if successful and E_FAIL if not. However, remember that the method may also return other failure or success codes. The following code fragment illustrates the danger of using a simple test, where hr contains the HRESULT value returned by the method:

if(hr == E_FAIL)
{
    //Handle the failure
}

else
{
    //Handle the success
}

As long as the method returns only E_FAIL to indicate failure, this test will work properly. However, the method might also return an error value such as E_NOTIMPL or E_INVALIDARG. That value would be interpreted as a success, perhaps causing your application to fail.

If you need detailed information about the outcome of the method call, you will need to test each relevant HRESULT value. However, you may be interested only in whether the method succeeded or failed. A robust way to test whether an HRESULT value indicates success or failure is to pass the value to the one of the following macros, defined in Winerror.h:

  • The SUCCEEDED macro returns TRUE for a success code and FALSE for a failure code.
  • The FAILED macro returns TRUE for a failure code and FALSE for a success code.

You can fix the preceding code fragment by using the FAILED macro.

if(FAILED(hr))
{
   //Handle the failure
}

else
{
   //Handle the success
}

This code fragment properly treats E_NOTIMPL and E_INVALIDARG as failures.

Although most COM methods return structured HRESULT values, a small number use the HRESULT to return a simple integer. Implicitly, these methods are always successful. If you pass an HRESULT of this sort to the SUCCEEDED macro, the macro will always return TRUE. A commonly used example is the IUnknown::Release method. This method decrements an object's reference count by one and returns the current reference count. See Managing a COM Object's Lifetime for a discussion of reference counting.

The Address of a Pointer

If you view a few COM method reference pages, you will probably run across something like the following:

HRESULT CreateDevice(..., IDirect3DDevice9 **ppReturnedDeviceInterface);

While a normal pointer is quite familiar to any C/C++ developer, COM often uses an additional level of indirection. This second level of indirection is indicated by a "**" following the type declaration, and the variable name typically has a "pp" prefix. For the example given above, the ppReturnedDeviceInterface parameter is typically referred to as the address of a pointer to an IDirect3DDevice9 interface.

Unlike C++, you do not access a COM object's methods directly. Instead, you must obtain a pointer to an interface that exposes the method. To invoke the method, you use essentially the same syntax that you would to invoke a pointer to a C++ method. For example, to invoke the IMyInterface::DoSomething method, you would use the following syntax.

IMyInterface *pMyIface;
...
pMyIface->DoSomething(...);

The need for a second level of indirection comes from the fact that you do not create interface pointers directly. You must call one of a variety of methods, such as the CreateDevice method shown above. To use such a method to obtain an interface pointer, you declare a variable as a pointer to the desired interface then pass the address of that variable to the method. In other words, you pass the address of a pointer to the method. When the method returns, the variable will point to the requested interface, and you can use that pointer to call any of the interface's methods. For more information about how to use interface pointers, see Using COM Interfaces.


Creating a COM Object
Microsoft DirectX 9.0 SDK Update (October 2004)

Creating a COM Object

There are several ways to create Component Object Model (COM) objects. The two most common ones used in Microsoft DirectX programming are:

  • Directly, by passing the object's class identifier (CLSID) to the CoCreateInstance function. The function will create an instance of the object, and it will return a pointer to an interface that you specify.
  • Indirectly, by calling a DirectX method or function that creates the object for you. The method creates the object and returns an interface on the object. When you create an object this way, you usually cannot specify which interface should be returned.

Before you create any objects, COM must be initialized by calling the CoInitialize function. If you are creating objects indirectly, the object creation method will handle this task. If you need to create an object with CoCreateInstance, you must call CoInitialize explicitly. When you are finished, COM must be uninitialized by calling CoUninitialize If you make a call to CoInitialize you must match it with a call to CoUninitialize. Typically, applications that need to explicitly initialize COM do so in their startup routine, and they uninitialize COM in their cleanup routine.

To create a new instance of a COM object with CoCreateInstance, you must have the object's CLSID. If this CLSID is publicly available, you will find it in the reference documentation or the appropriate header file. If the CLSID is not publicly available, you cannot create the object directly.

The CoCreateInstance function has five parameters. For the COM objects you will be using with DirectX, you can normally set the parameters as follows

  • rclsid. Set this parameter to the CLSID of the object you want to create.
  • pUnkOuter. Set this parameter to NULL. It is used only if you are aggregating objects. See Further Information for a discussion of aggregation.
  • dwClsContext. Set this parameter to CLSCTX_INPROC_SERVER. This setting indicates that the object is implemented as a dynamic-link library (DLL) and will run as part of your application's process.
  • riid. Set this parameter to the interface identifier (IID) of the interface that you would like to have returned. The function will create the object, and it will return the requested interface pointer in the ppv parameter.
  • ppv. Set this parameter to the address of a pointer that will be set to the interface specified by riid when the function returns. This variable should be declared as a pointer to the requested interface, and the reference to the pointer in the parameter list should be cast as (LPVOID *).

Creating an object indirectly is usually much simpler. You pass the object creation method the address of an interface pointer. The method then creates the object and returns an interface pointer. When you create an object indirectly, you typically cannot choose which interface the method will return. However, you can often specify a variety of things about how the object should be created. For example, the following code fragment calls the IDirect3D9::CreateDevice method discussed earlier to create a device object to represent a display adapter. It returns a pointer to the object's IDirect3DDevice9 interface. The first four parameters provide a variety of information needed to create the object, and the fifth parameter receives the interface pointer. See the reference documentation for details.

IDirect3DDevice9 *g_pd3dDevice = NULL;
...
if( FAILED( g_pD3D->CreateDevice(D3DADAPTER_DEFAULT,
                                 3DDEVTYPE_HAL,
                                 hWnd,
                                 D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                 &d3dpp,
                                 &g_pd3dDevice )))

  return E_FAIL;


Using COM Interfaces
Microsoft DirectX 9.0 SDK Update (October 2004)

Using COM Interfaces

When a Component Object Model (COM) object is created, the creation method returns an interface pointer. You can then use that pointer to access any of the interface's methods. The syntax is identical to that used with a pointer to a C++ method.

Requesting Additional Interfaces

In many cases, the interface pointer that you receive from the creation method may be the only one that you need. In fact, it is relatively common for an object to export only one interface other than IUnknown. However, many objects export multiple interfaces, and you may need pointers to several of them. If you need more interfaces than the one returned by the creation method, there is no need to create a new object. Instead, request another interface pointer by using the object's IUnknown::QueryInterface method.

If you create your object with CoCreateInstance, you can request an IUnknown interface pointer and then call IUnknown::QueryInterface to request every interface you need. However, this approach is inconvenient if you need only a single interface, and it doesn't work at all if you use an object creation method that does not allow you to specify which interface pointer should be returned. In practice, you usually don't need to obtain an explicit IUnknown pointer because all COM interfaces extend the IUnknown interface.

Extending an interface is similar to inheriting from a C++ class. The child interface exposes all of the parent interface's methods plus one or more of its own. In fact, you will often see "inherits from" used instead of "extends." What you need to remember is that the inheritance is internal to the object. Your application cannot inherit from or extend an object's interface. However, you can use the child interface to call any of the child's or the parent's methods.

Because all interfaces are children of IUnknown you can use any of the interface pointers you already have for the object to call QueryInterface. When you do so, you must provide the interface identifier (IID) of the interface you are requesting and the address of a pointer that will contain the interface pointer when the method returns. For example, the following code fragment calls IDirectSound9::CreateSoundBuffer to create a primary buffer object. This object exposes several interfaces. The CreateSoundBuffer method returns an IDirectSoundBuffer9 interface. The subsequent code then uses the IDirectSoundBuffer9 interface to call QueryInterface to request an IDirectSound3DListener9 interface.

IDirectSoundBuffer9* pDSBPrimary = NULL;
IDirectSound3DListener9* pDSListener;
...
if(FAILED(hr = g_pDS->CreateSoundBuffer( &dsbd, &pDSBPrimary, NULL )))
  return hr;

if(FAILED(hr = pDSBPrimary->QueryInterface(IID_IDirectSound3DListener9,
                                           (LPVOID *)&pDSListener)))
  return hr;


Managing a COM Object's Lifetime
Microsoft DirectX 9.0 SDK Update (October 2004)

Managing a COM Object's Lifetime

When an object is created, the system allocates the necessary memory resources. When an object is no longer needed, it should be destroyed. The system can use that memory for other purposes. With C++ objects, you can control the object's lifetime directly with the new and delete operators. Component Object Model (COM) does not enable you to create or destroy objects directly. The reason for this practice is that the same object may be used by more than one application. If one of those applications were to destroy the object, the other applications would probably fail. Instead COM uses a system of reference counting to control an object's lifetime.

An object's reference count is the number of times one of its interfaces has been requested. Each time an interface is requested, the reference count is incremented. An application releasesan interface when that interface is no longer needed, decrementing the reference count. As long as the reference count is greater than zero, the object remains in memory. When the reference count reaches zero, the object destroys itself. You don't need to know anything about the reference count of an object. As long as you obtain and release an object's interfaces properly, the object will have the appropriate lifetime.

Important Properly handling reference counting is a crucial part of COM programming. Failure to do so can easily create a memory leak. One of the most common mistakes that COM programmers make is failing to release an interface. When this happens, the reference count will never reach zero, and the object will remain in memory indefinitely.

Incrementing and Decrementing the Reference Count

Whenever you obtain a new interface pointer, the reference count must be incremented by a call to IUnknown::AddRef. However, your application does not usually need to call this method. If you obtain an interface pointer by calling an object creation method or by calling IUnknown::QueryInterface, the object will automatically increment the reference count. However, if you create an interface pointer in some other way, such as copying an existing pointer, you must explicitly call IUnknown::AddRef. Otherwise, when you release the original interface pointer, the object may be destroyed even though you may still need to use the copy of the pointer.

You must release all interface pointers, regardless of whether you or the object incremented the reference count. When you no longer need an interface pointer, call IUnknown::Release to decrement the reference count. A common practice is to initialize all interface pointers to NULL then set them back to NULL when they are released. That convention allows you to test all interface pointers in your cleanup code. Those that are non-NULL are still active and must be released before you terminate the application.

The following code fragment extends the sample discussed in Using COM Interfaces to illustrate how to handle reference counting.

IDirectSoundBuffer9* pDSBPrimary = NULL;
IDirectSound3DListener9* pDSListener = NULL;
IDirectSound3DListener9* pDSListener2 = NULL;
...
//Create the object and obtain an additional interface.
//The object increments the reference count.

if(FAILED(hr = g_pDS->CreateSoundBuffer( &dsbd, &pDSBPrimary, NULL )))
  return hr;

if(FAILED(hr=pDSBPrimary->QueryInterface(IID_IDirectSound3DListener9,
                                        (LPVOID *)&pDSListener)))
  return hr;

//Make a copy of the IDirectSound3DListener9 interface pointer.
//Call AddRef to increment the reference count and to ensure that
//the object is not destroyed prematurely

pDSListener2 = pDSListener;
pDSListener2->AddRef();
...
//Cleanup code. Check to see if the pointers are still active.
//If they are, call Release to release the interface.

if(pDSBPrimary != NULL)
{
  pDSBPrimary->Release();
  pDSBPrimary = NULL;
}

if(pDSListener != NULL)
{
  pDSListener->Release();
  pDSListener = NULL;
}

if(pDSListener2 != NULL)
{
  pDSListener2->Release();
  pDSListener2 = NULL;
}


Using C to Access COM Objects
Microsoft DirectX 9.0 SDK Update (October 2004)

Using C to Access COM Objects

Although C++ is the most commonly used language for Component Object Model (COM) programming, you can also access COM objects using C. Doing so is relatively straightforward, but requires a somewhat more complex syntax:

  • All methods have an additional parameter added to the beginning of the parameter list. This parameter must be set to the interface pointer.
  • You must explicitly reference the object's vtable.

Every COM object has a vtable that contains a list of pointers to the methods that the object exposes. An interface pointer points to the appropriate location in the vtable, which in turn contains a pointer to the particular method you are calling. The vtable is not mentioned elsewhere in this documentation because the vtable is essentially invisible with C++. However, if you want to call COM methods with C, you must include an additional level of indirection that explicitly references the vtable.

Some components have macros defined in their header files that resolve to the correct calling convention. See Using Macros to Call DirectX COM Methods for details.


Using Macros to Call DirectX COM Methods
Microsoft DirectX 9.0 SDK Update (October 2004)

Using Macros to Call DirectX COM Methods

For many of the Microsoft DirectX Component Object Model (COM) interfaces, macros are defined for each method. The macros simplify the use of the methods in your application. You can find definitions of these macros in the same header file as the interface declaration. The macros are designed to be used by both C and C++ applications. To use the C++ macros, you must define _cplusplus. Otherwise, the C macros will be used. The macro syntax is the same for both languages, but the header files include separate sets of macro definitions that expand to the appropriate calling convention.

For example, the following code fragment from the d3d.h header file shows the definitions of the C and C++ macros for the IDirect3D9::GetAdapterIdentifier method:

...
#define IDirect3D9_GetAdapterIdentifier(p,a,b,c) (p)->lpVtbl->GetAdapterIdentifier(p,a,b,c)
...
#else
...
#define IDirect3D9_GetAdapterIdentifier(p,a,b,c) (p)->GetAdapterIdentifier(a,b,c)
...
#endif

To use one of these macros, you must first obtain a pointer to the associated interface. The first parameter of the macro must be set to that pointer. The remaining parameters map to the method's parameters. The macro's return value is the HRESULT value that is returned by the method. The following code fragment uses a macro to call the IDirect3D9::GetAdapterIdentifier method. Note that pD3D is a pointer to an IDirect3D9 interface.

hr = IDirect3D9_GetAdapterIdentifier(pD3D,
                                     Adapter,
                                     dwFlags,
                                     pIdentifier);


DirectX COM Documentation Conventions
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectX COM Documentation Conventions

By convention, Component Object Model (COM) methods and interfaces are referred to in the documentation by their equivalent C++ class names. The CreateDevice method of the IDirect3D9 interface is thus referred to as IDirect3D9::CreateDevice. The primary reason for this convention is that different interfaces may export a method with the same name but with entirely different functionality and syntax. For example, many interfaces have an Create or CreateDevice method, but the functionality and parameters may be quite different. Using the C++ class name is a convenient way to uniquely identify the method.

The text and sample code generally uses C++ conventions for calling COM methods. See Using C to Access COM Objects, for a discussion of how to convert a C++ method call to its C equivalent.


Using ATL with DirectX 9.0 COM Interfaces
Microsoft DirectX 9.0 SDK Update (October 2004)

Using ATL with DirectX 9.0 COM Interfaces

To use the Active Template Library (ATL) with Microsoft DirectX 9.0, you must redefine the interfaces for ATL compatibility. This will allow you to properly use the CComQIPtr class to obtain a pointer to an interface.

If you do not redefine the interfaces for ATL, you will get the following error message.

C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\atlmfc\include\atlbase.h(4704) :
  error C2787: 'IDirectXFileData' : no GUID has been associated with this object

The following code sample shows how to define the IDirectXFileData interface.

// Explicit declaration
struct __declspec(uuid("{3D82AB44-62DA-11CF-AB39-0020AF71E433}")) IDirectXFileData;

// Macro method
#define RT_IID(iid_, name_) struct __declspec(uuid(iid_)) name_
RT_IID("{1DD9E8DA-1C77-4D40-B0CF-98FEFDFF9512}", IDirectXFileData);

After redefining the interface, you must use the Attach method to attach the interface to the interface pointer returned by ::Direct3DCreate9. If you do not, the IDirect3D9 interface will not be properly released by the smart pointer class.

The CComPtr class internally calls IUnknown::AddRef on the interface pointer when the object is created and when an interface is assigned to the CComPtr class. To avoid leaking the interface pointer, do not call IUnknown::AddRef on the interface returned from ::Direct3DCreate9.

The following code properly releases the interface without doing IUnknown::AddRef.

CComPtr<IDirect3D9> d3d;
d3d.Attach(::Direct3DCreate9(D3D_SDK_VERSION));

Use the previous code. Do not use the following code, which calls IUnknown::AddRef followed by IUnknown::Release and does not release the reference added by ::Direct3DCreate9.

CComPtr<IDirect3D9> d3d = ::Direct3DCreate9(D3D_SDK_VERSION);

Note that this is the only place in Microsoft Direct3D where you will have to use the Attach method in this manner.

For more information about the CComPTR and CComQIPtr classes, see their definitions in the Atlbase.h header file.


Games for Windows
Microsoft DirectX 9.0 SDK Update (October 2004)

Games for Windows

This section contains information that addresses issues when designing games to run on Microsoft Windows.

  • Games and Firewalls


Games and Firewalls
Microsoft DirectX 9.0 SDK Update (October 2004)

Games and Firewalls

The improved security brought by Microsoft Windows XP Service Pack 2 (SP2) also brings a new complication for multiplayer games: the Windows Firewall. This article describes the new Windows Firewall, why it exists, what it accomplishes, and how it does so. Most importantly, it describes how to configure your application to work well with the Windows Firewall.

The Need for a Firewall

A firewall provides a barrier against network-based intrusions. It blocks unsolicited incoming traffic, and makes the system mostly invisible on the internet by rejecting Internet Control Message Protocol (ICMP) requests. This means that ping and tracert will not work. The firewall also looks out for invalid packets and rejects those it finds.

This barrier prevents opportunistic attacks. Attacks spread by finding many systems with the same vulnerability. The firewall can thwart many attacks by putting up a "do not disturb" sign for those features not currently in use; the attack is ignored and does not strike home. The essential benefit of the new Windows Firewall is that features and applications that are not in use cannot be avenues for attack.

The user configures the system to identify what applications and features are needed and should be open to the network. This happens either when an application is installed or when it tries to open itself to the network.

With the arrival of Windows XP SP2, firewalls are going to be widely deployed and an open connection between endpoints will be the exception. Asking users to choose between being secure and having fun is bad business.

Determining if Your Game Is Affected

All multiplayer games are affected to some degree. While clients are generally in good shape, servers, hosts, and peers in peer-to-peer all need the Windows Firewall configured to continue working. Specifically, incoming unsolicited traffic is dropped. The Windows Firewall intercepts network traffic filter packets based on the packet contents and recent network activity. The Windows Firewall uses the contents and activity to decide if a packet is forwarded or dropped.

Once the Windows Firewall is properly configured, a game will be able to accept inbound unsolicited traffic as before.

Who has inbound unsolicited traffic?

  • Client/Server: All participants connect to a central server. The central server is the one with incoming unsolicited traffic. The clients connecting to the server are soliciting return traffic, which is expected and is allowed to pass through the Windows Firewall if the rules for clients are followed. The central server must be configured to accept the unsolicited traffic to allow the client traffic to pass through the Windows Firewall.
  • Massively Multiplayer (MMP): All participants are connected to a data center. This amounts to a complex client/server relationship, as the data center has the inbound unsolicited traffic. The participants are clients, and in general do not need to accept unsolicited traffic.
  • Peer-to-Peer, where all participants are connected to each other directly: All participants must be ready to accept unsolicited traffic from any new player joining the group. In a sense, each of the participants must function as a host, so they must all be configured as if they were hosts.

Clients are generally in good shape. Their outgoing Transmission Control Protocol/Internet Protocol (TCP/IP) connections will work fine, as will outgoing User Datagram Protocol (UDP) messages along with timely responses to those messages - the Windows Firewall keeps the port open for 90 seconds after each outgoing message in anticipation of a reply.

The Firewall Before Windows XP SP2

The Internet Connection Firewall (ICF) in Windows XP and Windows Server 2003 is a stateful packet filter, and handles both Internet Protocol, version 4 (IPv4) and Internet Protocol, version 6 (IPv6). However, it is not on by default and does not support non-Microsoft network stacks, of which there are a significant number in the world, such as large internet providers including national telephone companies.

For those not on Windows XP SP2, turning ICF on is highly recommended. "Use a Firewall" is listed on http://www.microsoft.com/security/protect as the first step to securing your PC. The ICF provides port mapping to override the packet filter. Essentially, you specify the port to open and it remains opened until you close it. If the user reboots before it is closed, it will remain open until specifically closed. The control of the ICF and the management of the port mappings is done via the INetSharingManager (IPv4) and the INetFwV6Mgr (IPv6).

The Windows Firewall for Windows XP SP2 is a more comprehensive solution that does support non-Microsoft network stacks, and does much more intelligent port handling: ports are kept open only so long as the application that needs them is still active.

The New Windows XP SP2 Firewall Is a Cleaner Solution

The new firewall is available on both Windows XP SP2 and Windows Server 2003 Service Pack 1 (SP1). Like the Windows Firewall, it is a software firewall that supports both IPv4 and IPv6, but unlike Windows Firewall it:

  • Has boot-time protection of the system, eliminating a small window of vulnerability during boot.
  • Supports non-Microsoft network stacks.
  • Has an "on with no exceptions" mode that blocks all unsolicited incoming packets. (This is great when you're using a public network, such as in an airport or your favorite coffee shop.)

In the "on with no exceptions" mode, all static holes are closed. application programming interface (API) calls to open a static hole are allowed but deferred; that is, they are not applied until the Windows Firewall switches back to normal operation. All listen requests by applications will also be ignored. Outbound connections will still succeed. For new applications, add your application to the "Exceptions List" during installation. After getting the user's agreement, add the application using the INetFwAuthorizedApplications interface, supplying the full path. We'll cover the details in the sample.

Your old applications, including applications installed before the user upgraded to Windows XP SP2, are handled with the Exceptions List popup (see Figure 1). This dialog shows when an application tries to open a port for incoming traffic - either when calling bind() with a non-zero port for UDP, or accept() for TCP/IP protocol. You must be running as an Administrator to "Unblock" applications, while "Ask Me Later" disallows this time around but asks again next time.

This is a non-blocking, system modal dialog unless the Windows Firewall detects a fullscreen Microsoft Direct3D application. When we tested with a blocking version of the dialog, many fullscreen applications crashed when the dialog popped up. To avoid these crashes, the dialog comes in underneath; the user can then handle it when the application exits fullscreen mode.

Figure 1. Exceptions List Popup dialog

The popup displays the name and publisher of the application which it extracts from the executable's version information. This information is an important system administration tool; it is even used for ongoing application compatibility work. Some applications neglect to keep this version information up-to-date.

Users can also add their applications through the user interface (UI) (see Figure 2), but for your new applications it's best to handle it during setup, add the application on install, and remove the application on uninstall. We'll show you how in Managing the Windows Firewall below.

Figure 2. Configuring the Windows Firewall

Figure 3. Application Exceptions List

Windows XP SP2 puts the security choices and settings out front. The goal is to protect by default, and allow the users to make informed choices about what applications are allowed to run on their machine.

Managing the Windows Firewall

The sample hits the two big scenarios: Installation (including the uninstall) and multiplayer launch. The Windows Firewall is configured during install, and the state of the Windows Firewall is detected when multiplayer is launched. The sample deals with these two scenarios in OnInstallApplication and in OnLaunchMultiplayer. The complete sample includes error checking left out of these snippets in the interest of brevity.

The install case is crucial (see Figure 4). Once the Windows Firewall is properly configured, the Windows Firewall takes care of the rest and is invisible to the application.

hr = OnInstallApplication(
        L"%ProgramFiles%\\Combat Flight Simulator\\COMBATFS.EXE ",
        L" Combat Flight Simulator"
        );
if( FAILED(hr) )
    printf( "OnInstallApplication failed: 0x%08lx\n", hr );

Figure 4. The first basic scenario: Install

We invoke OnInstallApplication passing the complete path to the executable and a "friendly name" that will appear in the Windows Firewall exception list (see Figure 4 and Figure 5). OnInstallApplication creates an instance of our FirewallWrapper class, and adds the executable to the Windows Firewall's exception list using the AddAuthorizedApp method.

BOOL OnInstallApplication(
            IN const wchar_t* szFwProcessImageFileName,
            IN const wchar_t* szFwFriendlyName
            )
{
    FirewallWrapper* pfw = FirewallWrapper::Create();
    if( !pfw )
        return FALSE;

    HRESULT hr = pfw->AddAuthorizedApp(
        szFwProcessImageFileName,
        szFwFriendlyName
        );
    return SUCCEEDED(hr);
}

Figure 5. OnInstallApplication

class FirewallWrapper
{
        INetFwProfile*  m_pFwProfile;
        HRESULT InitFirewallProfile();
        FirewallWrapper();

  public:
        static FirewallWrapper* Create();
        ~FirewallWrapper();

        BOOL    FirewallPresent()             { return m_pFwProfile != NULL; }
        HRESULT AddAuthorizedApp(
            IN const wchar_t* szFwProcessImageFileName,
            IN const wchar_t* szFwFriendlyName  );
        HRESULT RemoveAuthorizedApp(
            IN const wchar_t* szFwProcessImageFileName  );
        BOOL IsAppEnabled(
            IN const wchar_t* szFwProcessImageFileName
            );
        BOOL AreExceptionsAllowed();
};

Figure 6. The FirewallWrapper class

FirewallWrapper::FirewallWrapper()
    : m_pFwProfile(NULL)
    , m_hrComInit(E_FAIL)
{}

FirewallWrapper* FirewallWrapper::Create()
{
    FirewallWrapper* pfw = new FirewallWrapper;
    if( pfw )
    {
        pfw->InitFirewallProfile();
        if( !pfw->FirewallPresent() )
        {
            // Failed to initialize firewall profile
            delete pfw;
            pfw = NULL;
        }
    }
    return pfw;
}

Figure 7. Initialize FirewallWrapper

Digging inside the FirewallWrapper class initialization, the first order of business is to initialize a profile (Figure 7). We create an instance of the Firewall Settings Manager (Figure 8), use it to retrieve the local Windows Firewall policy, then use the policy to fetch the intended profile. Because all interactions go through the profile, it is stored in a member variable for future use. From now on, the FirewallWrapper will use the profile to check and modify Windows Firewall settings.

On older systems that lack the new Windows Firewall, no profile will be created and the FirewallWrapper::Create method will return NULL.

HRESULT FirewallWrapper::InitFirewallProfile()
{
    HRESULT         hr = S_OK;
    INetFwMgr*      pFwMgr = NULL;
    INetFwPolicy*   pFwPolicy = NULL;
    m_pFwProfile = NULL;

    // Create an instance of the firewall settings manager.
    hr = CoCreateInstance(  __uuidof(NetFwMgr), NULL,
            CLSCTX_INPROC_SERVER, __uuidof(INetFwMgr),
            (void**)&pFwMgr );
    _ASSERT( hr != CO_E_NOTINITIALIZED &&
             "COM has not been initialized" );
    if( FAILED(hr) )
        goto cleanup;
    // Retrieve the local firewall policy.
    hr = pFwMgr->get_LocalPolicy( &pFwPolicy );
    if( FAILED(hr) )
        goto cleanup;
    // Retrieve the firewall profile currently in effect.
    hr = pFwPolicy->get_CurrentProfile( &m_pFwProfile );
    if( FAILED(hr) )
        printf( "get_CurrentProfile failed: 0x%08lx\n", hr );

cleanup:
    if( pFwPolicy != NULL )
        pFwPolicy->Release();
    if( pFwMgr != NULL )
        pFwMgr->Release();
    return hr;
}

Figure 8. InitFirewallProfile

Adding the authorized application (Figure 9) works through the Authorized Applications list. An instance of an authorized application is created to add to the list, BSTRs are used to pass in both the fully-qualified file name and the friendly name, and the application is added to the list. Manipulating the Windows Firewall is limited to Administrators on the system, so this call will fail when running as a limited user. This does not pose a problem because installs already require Administrator privilege.

HRESULT FirewallWrapper::AddAuthorizedApp(
            IN const wchar_t* szFwProcessImageFileName,
            IN const wchar_t* szFwFriendlyName
            )
{
    HRESULT             hr = S_OK;
    BSTR                fwBstrName = NULL;
    BSTR                fwBstrProcessImageFileName = NULL;
    INetFwAuthorizedApplication*    pFwApp = NULL;  .
    INetFwAuthorizedApplications*   pFwApps = NULL;

    hr = m_pFwProfile->get_AuthorizedApplications( &pFwApps );

    // Create an instance of an authorized application.
    hr = CoCreateInstance( __uuidof(NetFwAuthorizedApplication),
            NULL, CLSCTX_INPROC_SERVER,
            __uuidof(INetFwAuthorizedApplication),
            (void**)&pFwApp );
    // Set the process image file name.
    fwBstrProcessImageFileName = SysAllocString(
    szFwProcessImageFileName );
    hr = pFwApp->put_ProcessImageFileName(
    fwBstrProcessImageFileName );
    // Set the application friendly name.
    fwBstrName = SysAllocString( szFwFriendlyName );
    hr = pFwApp->put_Name( fwBstrName );

    // Add the application to the collection.
    hr = pFwApps->Add( pFwApp );

cleanup:
    // Free the BSTRs.
    SysFreeString( fwBstrName );
    SysFreeString( fwBstrProcessImageFileName );

    // Release the authorized application instance.
    if( pFwApp != NULL )
        pFwApp->Release();
    if( pFwApps != NULL )
        pFwApps->Release();
    return hr;
}

Figure 9. AddAuthorizedApp

Because removing an authorized application is so similar to adding one, the details are omitted here. The wrapper handles it in the RemoveAuthorizedApp method (see Figure 10 and the sample application).

BOOL OnUninstallApplication(
            IN const wchar_t* szFwProcessImageFileName
            )
{
    FirewallWrapper* pfw = FirewallWrapper::Create();
    if( !pfw )
        return FALSE;

    HRESULT hr = pfw->RemoveAuthorizedApp(
        szFwProcessImageFileName
        );
    return SUCCEEDED(hr);
}

Figure 10. OnUninstallApplication

Now to launch, the second basic scenario (see Figure 11). The launch case is interesting because connectivity problems are a real headache for gamers. The Windows Firewall state needs to be checked on launch to proactively detect connection problems and give better guidance through better error messages.

if( CanHostMultiplayer(
       L"%ProgramFiles%\\Combat Flight Simulator\\COMBATFS.EXE")   )
    printf( "Okay to launch multiplayer.\n" );

Figure 11. The second basic scenario: Launch

First, check for changes since installation. The application may have been disabled or removed from the exceptions list. This checks to ensure the work from OnInstallApplication still holds. The second check is even more interesting in its own way, because users can request the special "on with no exceptions" mode at any time. Hosting will not work if either of these checks fails, including the peer-to-peer scenario as discussed earlier.

BOOL CanHostMultiplayer(
            IN const wchar_t* szFwProcessImageFileName
            )
{
    FirewallWrapper* pfw = FirewallWrapper::Create();
    if( !pfw )
        return TRUE;

    if( !pfw->IsAppEnabled(szFwProcessImageFileName) )
    {
        // Application is not enabled in the firewall.
        // You will not be able host games or join a peer-to-peer game.
        // Depending on the game, you may be able to join.
        return FALSE;
    }
    if( !pfw->AreExceptionsAllowed() )
    {
        // Firewall is on with no exceptions.
        // You will not be able host games or join a peer-to-peer game.
        // Depending on the game, you may be able to join.
        return FALSE;
    }
    return TRUE;
}

Figure 12. CanHostMultiplayer

With the wrapper, it's simple to check if exceptions are allowed as seen in Figure 13. The wrapper uses the profile to call get_ExceptionsNotAllowed, fixes up the negative logic, and returns the result.

BOOL FirewallWrapper::AreExceptionsAllowed()
{
    VARIANT_BOOL        vbNotAllowed = VARIANT_FALSE;
    HRESULT             hr = S_OK;

    hr = m_pFwProfile->get_ExceptionsNotAllowed( &vbNotAllowed );
    if( SUCCEEDED(hr) && vbNotAllowed != VARIANT_FALSE )
        return FALSE;

    return TRUE;
}

Figure 13. AreExceptionsAllowed

Discovering if an application is on the enabled list is more involved (see Figure 14). Get the set of authorized applications, and check for the executable image's file name using a BSTR; if present, check to see if it is enabled. Finally, complete the process by cleaning up.

BOOL FirewallWrapper::IsAppEnabled(
            IN const wchar_t* szFwProcessImageFileName
            )
{
    HRESULT        hr = S_OK;
    BSTR                fwBstrProcessImageFileName = NULL;
    VARIANT_BOOL        vbFwEnabled;
    INetFwAuthorizedApplication*    pFwApp = NULL;
    INetFwAuthorizedApplications*   pFwApps = NULL;
    BOOL bFwAppEnabled = FALSE;

    // Retrieve the collection of authorized applications.
    hr = m_pFwProfile->get_AuthorizedApplications( &pFwApps );
    if( FAILED(hr) )
        goto cleanup;
    fwBstrProcessImageFileName = SysAllocString(
               szFwProcessImageFileName );
    if( SysStringLen( fwBstrProcessImageFileName ) == 0 )
        goto cleanup;
    // Retrieve the authorized application, find if it is enabled
    hr = pFwApps->Item( fwBstrProcessImageFileName, &pFwApp );
    if( SUCCEEDED(hr ) )
    {
        hr = pFwApp->get_Enabled( &vbFwEnabled );
        if( SUCCEEDED(hr) && vbFwEnabled != VARIANT_FALSE )
            bFwAppEnabled = TRUE;
    }

cleanup:
    SysFreeString( fwBstrProcessImageFileName );
    if( pFwApp != NULL )
        pFwApp->Release();
    if( pFwApps != NULL )
        pFwApps->Release();
    return bFwAppEnabled;
}

Figure 14. IsAppEnabled

If you run afoul of the Windows Firewall, the log can come in handy. We made extensive use of it during our development cycle; you can see the Windows Firewall activity in this text log including what packets are dropped and what connections succeed. At the top of the log is a header describing the columns. Turn it on from the Control Panel by double-clicking Windows Firewall, then selecting the Advanced tab, and clicking the Settings button in the Security Logging area. By default, the log file goes to the following location and may be found there:

C:\windows\pfirewall.log

You may be wondering if it is a security risk that applications can add and remove applications from the exceptions list without a popup, or perhaps you think that the bigger risk is that applications can disable the Windows Firewall altogether. To perform these feats, the application must be running in administrator mode. If you have malicious code running in administrator mode on your system, the game is already over. The hacker has already won. Your system is compromised. The hacker's ability to disable the Windows Firewall would merit little more than a footnote.

The Recommendations

The Windows Firewall is here to stay as long as the Internet is under attack. With our customers under attack, don't tell them to disable the Windows Firewall. They need an active firewall. Easy is good. Make the firewall seamless for your users by adding your application to the exceptions list during installation. Make the user aware you are doing so; remember, the system belongs to the user. Put the user in the driver's seat. When you uninstall, remove your application from the exceptions list. Give good feedback if your multiplayer code is blocked by the Windows Firewall state. Disable networking features if they won't work either because the application is disallowed or because the system is in the "no exceptions" mode.

Existing applications will be handled through the popup mechanism; you can also patch or supply instructions on your Web site to guide them through the Control Panel dialog. That's what they'll need to do if they want to change their mind after allowing or disallowing a given application.


DirectX Tools
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectX Tools

This section contains tools to help you develop Microsoft DirectX 9.0 applications.

  • DirectX Caps Viewer
  • DirectX Control Panel
  • DirectX Diagnostic Tool
  • DirectX Version Checking

Related Topics

  • 3-D Graphics Tools


DirectX Caps Viewer
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectX Caps Viewer

The Microsoft DirectX Caps Viewer shows information for the following components of DirectX:

  • Microsoft Direct3D devices and capabilities
  • Microsoft DirectSound capture devices and capabilities
  • Microsoft DirectPlay connections (server provider information)
  • Microsoft DirectInput devices and their capabilities
  • Microsoft DirectMusic capabilities (for DirectMusic ports)

The DirectX Caps Viewer screen shot below shows the general Microsoft DirectDraw capabilities of the primary display adapter.

Screen shot of DirectX Caps Viewer

Developers should use this tool to verify the capabilities of their development and test computers, making sure that DirectX applications correctly test for current computer capabilities and react accordingly. It is suggested that applications be designed with fallback strategies if the required features are not available.

Path

Executable: (SDK root)\Bin\DXUtils\DXCapsViewer.exe

User's Guide

Select items in the tree view on the left. Information about the selected item appears in the pane on the right.


DirectX Control Panel
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectX Control Panel

You can use the Microsoft DirectX Control Panel, which is installed with the software development kit (SDK), to examine and modify the properties of DirectX components. This utility contains tabs for each DirectX component. Using this utility you can:

  • Obtain version information for DirectX components.
  • Change the debug output level and debug settings to aid in troubleshooting during the development process.
  • View specific driver and hardware support information for DirectX components.
  • Toggle between debug and retail versions of the runtime files for Microsoft Direct3D, Microsoft DirectMusic, and Microsoft DirectInput.


DirectX Diagnostic Tool
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectX Diagnostic Tool

The Microsoft DirectX Diagnostic tool gathers information about the system and the DirectX installed components. It also provides a number of tests to ensure that components are working properly. Use the DirectX Diagnostic Viewer (Dxdiag.exe) to create a DirectX-relevant data dump of your computer by running Dxdiag.exe after your computer has crashed. Then send the data dump to Microsoft using the Report button on the More Help tab.

Additional debug information can be found in Debugging DirectX Applications.

Launch Procedure

CPU Procedure
32-bit
  1. From the Start menu, select Run.
  2. Enter Dxdiag.exe, then click OK.

The executable is located at %windir%\system32\Dxdiag.exe.
64-bit
  1. From the Start menu, select Run.
  2. Enter Dxdiag.exe, then click OK.
  3. In the dialog box (this will only appear on a 64-bit computer), click Run 64-bit DxDiag. The 64-bit version of Dxdiag will launch.


DirectX Version Checking
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectX Version Checking

Applications sometimes need to know which version of Microsoft DirectX is currently available on the system. If an older version of DirectX is on the system, your application may need to scale itself to the capabilities of that version or install the most recent version.

The table lists the version of DirectX that shipped with each operating system:

Operating System | DirectX Version
Microsoft Windows 98 Gold | DirectX 5.2
Windows 98 SE | DirectX 6.1a
Windows 2000 | DirectX 7.0
Windows Millennium Edition (Windows Me) | DirectX 7.1
Windows XP | DirectX 8.1

DirectX 9.0 is supported on Windows XP.

The GetDXVer SDK sample has a function in it called GetDXVersion that returns the version of DirectX that is installed. As long as this integer is greater than or equal to your desired version number, your application will run normally.

Path

Source: | (SDK root)\Samples\C++\Misc\GetDXVer
Executable: | (SDK root)\Samples\C++\Misc\Bin\GetDXVer

Checking the Operating System Version

Use the Windows function GetVersionEx World Wide Web link to check the operating system installed. This function returns an OSVERSIONINFOEX World Wide Web link structure that contains a variety of information about the operating system.

Related Topics

  • Obtaining DirectX Version


DirectX Samples
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectX Samples

The sample in this section demonstrates Microsoft DirectX tools.

Note Follow the instructions for Sample Code contained in the license agreements within the following folder:

(SDK root)\Documentation\License Agreements

  • Dinstall Sample


Dinstall Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

Dinstall Sample

This sample uses DirectSetup functions to install the Microsoft DirectX subsystem. It shows how to use a callback function to present messages and get user input through a custom interface (a modeless dialog box).

Path

Source: (SDK root)\Samples\C++\Misc\DXInstall

User's Guide

  1. Copy the entire contents of the \Redist\DirectX9 folder from the DirectX software development kit (SDK) CD into the same folder as Dinstall.exe.
  2. In your development environment, set the working directory to this folder as well. (In Microsoft Visual C++, this setting is on the Debug page of the Project Settings dialog box.)
  3. Run the program and, on the File menu, click Start Install. DirectSetup performs a simulated installation of DirectX (see Programming Notes below) and advises you of its progress in a modeless dialog box. You can use the Options menu to change the level of messages shown. However, if you are performing only a simulated installation, you will never see problem or update messages.
  4. On the File menu, click GET Version. The program shows the version and revision number of DirectX currently installed on the system.

Programming Notes

By default, the program passes DSETUP_TESTINSTALL to the DirectXSetup function. This means that no files are copied and the registry is not modified. To perform a real installation, delete this flag from the call.

Dinstall.exe employs a callback function to monitor the progress of installation and intercept messages. Depending on the user's preferred warning level, as tracked in g_fStatus, messages may be ignored or presented to the user in a modeless dialog box. If user input is required, the appropriate buttons are displayed and the application monitors the message queue until one of the buttons is pressed.

Although DirectX samples include Visual C++ project workspace files, you might need to verify other settings in your development environment to ensure that the samples compile properly.

Related Topics

  • DirectSetup Essentials


DirectX Reference
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectX Reference

This section contains reference information for the tools provided for working with Microsoft DirectX. Material is divided into the following sections:

  • The DirectX 9.0 Error Handling Utility Library
  • DirectX Diagnostic Tool Reference
  • DirectSetup
  • IUnknown


The DirectX 9.0 Error Handling Utility Library
Microsoft DirectX 9.0 SDK Update (October 2004)

The DirectX 9.0 Error Handling Utility Library

The Microsoft DirectX 9.0 software development kit (SDK) includes a pair of utility functions and several macros designed to simplify the task of debugging your application. These functions are contained in the Dxerr9.lib library. The function and macro declarations are in Dxerr9.h.

  • DirectX 9.0 Error Handling Functions
  • DirectX 9.0 Error Handling Macros


DirectX 9.0 Error Handling Functions
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectX 9.0 Error Handling Functions

The following functions are included in the Microsoft DirectX error handling utility library, Dxerr9.lib.

Functions

  • DXGetErrorDescription9
  • DXGetErrorString9
  • DXTrace


DXGetErrorDescription9 Function

Returns a string that describes a Microsoft DirectX HRESULT value.

Syntax

TCHAR *DXGetErrorDescription9(

    HRESULT hr
);

Parameters

hr
[in] Any HRESULT return code from Microsoft Direct3D, Microsoft DirectPlay, Microsoft DirectMusic, Microsoft DirectSound, Microsoft DirectInput, and Microsoft DirectShow.

Return Value

Returns a pointer to a character string that describes the HRESULT code.

Remarks

This function supports Microsoft Win32 Winerror.h error codes.

Function Information

Header | dxerr9.h
Import library | dxerr9.lib
Minimum operating systems | Windows 98


DXGetErrorString9 Function

Returns the name associated with an error code. This method is designed to handle error codes from all the Microsoft DirectX components and Microsoft Win32 functions.

Syntax

TCHAR *DXGetErrorString9(

    HRESULT hr
);

Parameters

hr
[in] Any HRESULT return code from Microsoft Direct3D, Microsoft DirectPlay, Microsoft DirectMusic, Microsoft DirectSound, Microsoft DirectInput, and Microsoft DirectShow.

Return Value

If successful, this function returns a pointer to a string that contains the name of the error code. If Unicode is set, DXGetErrorString9 will return a Unicode string. Otherwise, it will return an ANSI string.

Remarks

This function is designed to retrieve the text equivalent of a DirectX error message from a Direct3D, D3DX, DirectPlay, DirectInput, DirectMusic, or DirectSound method. For example, if you set hr to 0x88760686, DXGetErrorString9 returns D3DERR_DEVICELOST.

If an error code maps to more than one text string, DXGetErrorString9 returns a generic string. For example, there are several DirectX error codes, such as D3DERR_OUTOFVIDEOMEMORY, that indicate that you are out of memory, and all map to the same value. If you set hr to any of these codes, DXGetErrorString9 will return E_OUTOFMEMORY.

This method handles all DirectX components including: Direct3D, DirectInput, DirectSound, DirectMusic, DirectShow, DirectPlay, and standard Win32 errors.

This function supports Unicode and ANSI strings.

This function supports Win32 Winerror.h error codes.

Function Information

Header | dxerr9.h
Import library | dxerr9.lib
Minimum operating systems | Windows 98


DXTrace Function

Displays a message box, and passes the error code to DXGetErrorString9.

Syntax

HRESULT DXTrace(

    CHAR *strFile,
    DWORD dwline,
    HRESULT hr,
    CHAR *strMsg,
    BOOL bPopMsgBox
);

Parameters

strFile
[in] Pointer to the name of the current file. You can set this parameter easily with the __FILE__ macro.
dwline
[in] Line number. You can set this parameter easily with the __LINE__ macro.
hr
[in] HRESULT containing an error code. This value will be passed to DXGetErrorString9 and converted to the equivalent name.
strMsg
[in] Pointer to an optional message that will be displayed along with the file name, line number, and HRESULT.
bPopMsgBox
[in] Specifies whether a message box should be displayed. If bPopMsgBox is set to TRUE, a message box will be displayed containing the values of the first four parameters. If bPopMsgBox is set to FALSE, the message box is not displayed.

Return Value

Returns the HRESULT that was assigned to hr.

Function Information

Header | dxerr9.h
Import library | dxerr9.lib
Minimum operating systems | Windows 98


DirectX 9.0 Error Handling Macros
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectX 9.0 Error Handling Macros

The following macros simplify using the DXTrace function.

Functions

  • DXTRACE_ERR
  • DXTRACE_ERR_MSGBOX
  • DXTRACE_MSG


DXTRACE_ERR Macro

Output a debug message and the failed return value for a failed function call.

Syntax

HRESULT DXTRACE_ERR(

    char *str,
    HRESULT hr
);

Parameters

str
[in] Pointer to a string to be passed to the debugger.
hr
[in] HRESULT containing an error code. This value will be passed to DXGetErrorString9 and converted to the equivalent name.

Return Value

Returns the HRESULT that was assigned to hr.

Remarks

For example, if you call DXTRACE_ERR with:

    DXTRACE_ERR( "Call failed", D3DERR_INVALIDCALL )

A function call that fails will output a debug message in the output window of the compiler similar to this one:

    c:\basichlsl\basichlsl.cpp(242): Call failed hr=D3DERR_INVALIDCALL (0x8876086c)

This identifies the file and line number of the function call that fails. You must be running a debug build to see the message. If you are using the Microsoft Visual Studio .NET debugger, you can jump to the line of source code where the error occurred by double-clicking on this message in the debug output window.

If you are not interested in returning the error code, see DXTRACE_MSG.

Macro Information

Header | dxerr9.h
Minimum operating systems | Windows 98


DXTRACE_ERR_MSGBOX Macro

Displays a message box with error information.

Syntax

HRESULT DXTRACE_ERR_MSGBOX(

    char *str,
    HRESULT hr
);

Parameters

str
[in] Pointer to a string to be displayed in the message box.
hr
[in] HRESULT containing an error code. This value will be passed to DXGetErrorString9 and converted to the equivalent name.

Return Value

Returns the HRESULT that was assigned to hr.

Remarks

For debug builds, the macro will display an error message that looks similar to the following:

c:\basichlsl\basichlsl.cpp(242):
    D3DXCreateFont( pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
    OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Arial",
    NULL ) hr=D3DERR_INVALIDCALL (0x8876086c)

If you are using the Microsoft Visual Studio .NET debugger, you can jump to the line of source code where the error occurred by double-clicking this message in the debug output window.

If you don't want to use a message box to debug, you can send error messages to the debug output window in Visual Studio .NET using DXTRACE_ERR or DXTRACE_MSG.

Macro Information

Header | dxerr9.h
Minimum operating systems | Windows 98


DXTRACE_MSG Macro

Output a debug message for a failed function call.

Syntax

HRESULT DXTRACE_MSG(

    CHAR *str
);

Parameters

str
[in] Pointer to a user-supplied debug message that will be passed to the debugger.

Return Value

Returns zero if successful, or a nonzero value if not.

Remarks

For example, if you call DXTRACE_MSG with:

    DXTRACE_MSG( "Call failed" )

A function call that fails will output a debug message in the output window of the compiler similar to this one:

    c:\basichlsl\basichlsl.cpp(242): Call failed

This identifies the file and line number of the function call that fails. You must be running a debug build to see the message. If you are using the Microsoft Visual Studio .NET debugger, you can jump to the line of source code where the error occurred by double-clicking this message in the debug output window.

If you are interested in returning the error code also, see DXTRACE_ERR.

Macro Information

Header | dxerr9.h
Minimum operating systems | Windows 98


DirectX Diagnostic Tool Reference
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectX Diagnostic Tool Reference

The Microsoft DirectX Diagnostic Tool exposes a Component Object Model (COM) interface to allow developers to programmatically query the information gathered by the tool.

  • Interfaces
  • Structures

Examples using the diagnostic tool can be found in:

  • (SDK root)\Samples\C++\Misc\DXDiagReport\
  • (SDK root)\Samples\C++\Misc\DXDiagOutput\


Interfaces
Microsoft DirectX 9.0 SDK Update (October 2004)

Interfaces

This section contains reference material for the interfaces exposed by the Microsoft DirectX Diagnostic Tool.

  • IDxDiagContainer
  • IDxDiagProvider


IDxDiagContainer Interface

Applications use the methods of the IDxDiagContainer interface to query objects and properties exposed by the Microsoft DirectX Diagnostic tool.

IDxDiagContainer Members

EnumChildContainerNames | Enumerates the name of the IDxDiagContainer object at the specified index.
EnumPropNames | Enumerates the name of the property at the specified index.
GetChildContainer | Retrieves a pointer to the specified child container.
GetNumberOfChildContainers | Returns the number of IDxDiagContainer objects in this container.
GetNumberOfProps | Retrieves the number of properties in this container.
GetProp | Retrieves an instance of the specified property.

Interface Information

Stock Implementation | dxdiagn.dll
Custom Implementation | No
Inherits from | IUnknown
Header | dxdiag.h
Minimum operating systems | Windows 98


IDxDiagContainer::EnumChildContainerNames Method

Enumerates the name of the IDxDiagContainer object at the specified index.

Syntax

HRESULT EnumChildContainerNames(

    DWORD dwIndex,
    LPWSTR pwszContainer,
    DWORD cchContainer
);

Parameters

dwIndex
[in] Zero-based index of the container object that specifies which child container name to retrieve. If this is outside of the allowable range, E_INVALIDARG is returned.
pwszContainer
[out] Address of a string buffer that receives the unique name of the child container. This should be at least 256 elements. If the buffer is too small, it will return DXDIAG_E_INSUFFICIENT_BUFFER.
cchContainer
[in] Specifies the size of the pwszContainer buffer in characters.

Return Value

Returns S_OK if successful. Otherwise, returns one of the following values:

E_INVALIDARG | An invalid argument was passed to the returning function.
DXDIAG_E_INSUFFICIENT_BUFFER | The buffer is too small.

Example

To enumerate the names of all the child containers, use this method in a loop. This example shows how to get the number of child containers, enumerate the names of all the child containers, and retrieve instances of the child containers.

IDxDiagContainer*   pDxDiagContainer;
IDxDiagContainer*   pChildContainer;
DWORD   dwChildCount;
DWORD   dwChildIndex;
WCHAR   wszChildName[256];

hr = pDxDiagContainer->GetNumberOfChildContainers( &dwChildCount );
assert( SUCCEEDED(hr) );

for( dwChildIndex = 0; dwChildIndex < dwChildCount; dwChildIndex++ )
{
        hr = pDxDiagContainer->EnumChildContainerNames( dwChildIndex, wszChildName, 256 );
        assert( SUCCEEDED(hr) );

        hr = pDxDiagContainer->GetChildContainer( wszChildName, &pChildContainer );
        assert( SUCCEEDED(hr) );

        // Do something with pChildContainer.

        SAFE_RELEASE( pChildContainer );
}


IDxDiagContainer::EnumPropNames Method

Enumerates the name of the property at the specified index.

Syntax

HRESULT EnumPropNames(

    DWORD dwIndex,
    LPWSTR pwszPropName,
    DWORD cchPropName
);

Parameters

dwIndex
[in] Zero-based index of the container object that specifies which property name to retrieve. If this is outside the allowable range, then E_INVALIDARG is returned.
pwszPropName
[out] Receives the unique name of the property. It should be at least 256 elements. If the buffer is too small it will return DXDIAG_E_INSUFFICIENT_BUFFER.
cchPropName
[in] Specifies the size of the pwszPropName buffer in characters.

Return Value

If unsuccessful, returns one of the following values:

E_INVALIDARG | An invalid argument was passed to the returning function.
DXDIAG_E_INSUFFICIENT_BUFFER | The buffer is too small.


IDxDiagContainer::GetChildContainer Method

Retrieves a pointer to the specified child container.

Syntax

HRESULT GetChildContainer(

    LPCWSTR pwszContainer,
    IDxDiagContainer **ppInstance
);

Parameters

pwszContainer
[in] Specifies the NULL-terminated name of the container.
ppInstance
[out] Receives an instance of the child IDxDiagContainer specified by pwszContainer.

Return Value

If unsuccessful, returns one of the following values:

E_INVALIDARG | An invalid argument was passed to the returning function.
E_OUTOFMEMORY | Could not allocate sufficient memory to complete the call.

Example

To enumerate the names of all the child containers, use this method in a loop. This example shows how to get the number of child containers, enumerate the names of all the child containers, and retrieve instances of the child containers.

IDxDiagContainer*	pDxDiagContainer;
IDxDiagContainer*	pChildContainer;
DWORD 	dwChildCount;
DWORD	dwChildIndex;
WCHAR	wszChildName[256];

hr = pDxDiagContainer->GetNumberOfChildContainers( &dwChildCount );
assert( SUCCEEDED(hr) );

for( dwChildIndex = 0; dwChildIndex < dwChildCount; dwChildIndex++ )
{
        hr = pDxDiagContainer->EnumChildContainerNames( dwChildIndex, wszChildName, 256 );
        assert( SUCCEEDED(hr) );

        hr = pDxDiagContainer->GetChildContainer( wszChildName, &pChildContainer );
        assert( SUCCEEDED(hr) );

        // Do something with pChildContainer.

        SAFE_RELEASE( pChildContainer );
}


IDxDiagContainer::GetNumberOfChildContainers Method

Returns the number of IDxDiagContainer objects in this container.

Syntax

HRESULT GetNumberOfChildContainers(

    DWORD *pdwCount
);

Parameters

pdwCount
[out] Receives the number of IDxDiagContainer objects in the container.

Return Value

Returns S_OK if successful. Otherwise, returns the following value:

E_INVALIDARG An invalid argument was passed to the returning function.

Example

To enumerate the names of all the child containers, use this method in a loop. This example shows how to get the number of child containers, enumerate the names of all the child containers, and retrieve instances of the child containers.

IDxDiagContainer*	pDxDiagContainer;
IDxDiagContainer*	pChildContainer;
DWORD 	dwChildCount;
DWORD	dwChildIndex;
WCHAR	wszChildName[256];

hr = pDxDiagContainer->GetNumberOfChildContainers( &dwChildCount );
assert( SUCCEEDED(hr) );

for( dwChildIndex = 0; dwChildIndex < dwChildCount; dwChildIndex++ )
{
        hr = pDxDiagContainer->EnumChildContainerNames( dwChildIndex, wszChildName, 256 );
        assert( SUCCEEDED(hr) );

        hr = pDxDiagContainer->GetChildContainer( wszChildName, &pChildContainer );
        assert( SUCCEEDED(hr) );

        // Do something with pChildContainer.

        SAFE_RELEASE( pChildContainer );
}


IDxDiagContainer::GetNumberOfProps Method

Retrieves the number of properties in this container.

Syntax

HRESULT GetNumberOfProps(

    DWORD *pdwCount
);

Parameters

pdwCount
[out] Receives the number of properties in this container.

Return Value

Returns S_OK if successful. Otherwise, returns the following value:

E_INVALIDARG An invalid argument was passed to the returning function.


IDxDiagContainer::GetProp Method

Retrieves an instance of the specified property.

Syntax

HRESULT GetProp(

    LPCWSTR pwszPropName,
    VARIANT *pvarProp
);

Parameters

pwszPropName
[in] Specifies the NULL-terminated name of the property.
pvarProp
Receives an instance of the property specified in pwszPropName. Check the method's return value and call VariantClear only if the method succeeds.

Return Value

Returns S_OK if successful. Otherwise, returns one of the error codes for VariantCopy or the following value:

E_INVALIDARG An invalid argument was passed to the returning function.


IDxDiagProvider Interface

Applications use the methods of the IDxDiagProvider interface to create the root IDxDiagContainer object.

IDxDiagProvider Members

GetRootContainer | Creates and initializes an IDxDiagContainer object to be the root container.
Initialize | Initializes an IDxDiagProvider object.

Interface Information

Stock Implementation | dxdiagn.dll
Custom Implementation | No
Inherits from | IUnknown
Header | dxdiag.h
Minimum operating systems | Windows 98


IDxDiagProvider::GetRootContainer Method

Creates and initializes an IDxDiagContainer object to be the root container.

Syntax

HRESULT GetRootContainer(

    IDxDiagContainer **ppInstance
);

Parameters

ppInstance
[in, out] Receives an instance of IDxDiagContainer.

Return Value

If unsuccessful, returns one of the following values:

E_CO_UNINITIALIZED | The requested object has not been initialized.
E_OUTOFMEMORY | Could not allocate sufficient memory to complete the call.
E_INVALIDARG | An invalid argument was passed to the returning function.
E_NOINTERFACE | No object interface is available.


IDxDiagProvider::Initialize Method

Initializes an IDxDiagProvider object.

Syntax

HRESULT Initialize(

    DXDIAG_INIT_PARAMS *pParams
);

Parameters

pParams
[in] DXDIAG_INIT_PARAMS that specifies the initialization parameters.

Return Value

Returns S_OK if successful. Otherwise, returns one of the following values:

E_POINTER | An invalid pointer, usually NULL, was passed as a parameter.
E_INVALIDARG | An invalid argument was passed to the returning function.
E_OUTOFMEMORY | Could not allocate enough memory to complete the operation.


Structures
Microsoft DirectX 9.0 SDK Update (October 2004)

Structures

This section contains the structure exposed by the Microsoft DirectX Diagnostic tool.

Structures

  • DXDIAG_INIT_PARAMS


DXDIAG_INIT_PARAMS Structure

Used by IDxDiagProvider::Initialize to initialize the IDxDiagProvider object.

Syntax

typedef struct _DXDIAG_INIT_PARAMS {
    DWORD dwSize;
    DWORD dwDxDiagHeaderVersion;
    BOOL bAllowWHQLChecks;
    VOID *pReserved;
} DXDIAG_INIT_PARAMS;

Members

dwSize
Specifies the size of the structure.
dwDxDiagHeaderVersion
Identifies whether the header is built against the correct version. This value must be DXDIAG_DX9_SDK_VERSION.
bAllowWHQLChecks
Specifies whether the Microsoft DirectX Diagnostic tool is allowed to verify that the drivers are digitally signed by Microsoft Windows Hardware Quality Labs (WHQL). When doing this, the DirectX Diagnostic tool can connect to the Internet to download new WHQL certificates. The valid values are:
TRUE
Allow verification.
FALSE
Do not allow verification.
pReserved
Reserved. Must be NULL.

Structure Information

Header | dxdiag.h
Minimum operating systems | Windows 98


DirectSetup Reference
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectSetup Reference

This section contains reference information for the application programming interface (API) elements provided by DirectSetup. Reference material is divided into the following categories:

  • Functions
  • Structures
  • Enumerations
  • Return Values


Functions
Microsoft DirectX 9.0 SDK Update (October 2004)

Functions

This section contains information about the following global functions used with Microsoft DirectSetup.

  • DirectXRegisterApplication
  • DirectXSetup
  • DirectXSetupCallbackFunction
  • DirectXSetupGetEULA
  • DirectXSetupGetVersion
  • DirectXSetupSetCallback
  • DirectXSetupShowEULA
  • DirectXUnRegisterApplication


DirectXRegisterApplication Function

Deprecated. Registers an application as one designed to work with IDirectPlayLobby3.

Syntax

int DirectXRegisterApplication(

    HWND hWnd,
    LPDIRECTXREGISTERAPP lpDXRegApp
);

Parameters

hWnd
Handle of the parent window. If this parameter is set to NULL, the desktop is the parent window.
lpDXRegApp
Address of the DIRECTXREGISTERAPP structure that contains the registry entries that are required for the application to function properly with DirectPlayLobby.

Return Value

If this function succeeds, it returns TRUE.

If it fails, it returns FALSE. Call the GetLastError function to get extended error information.

Remarks

The DirectXRegisterApplication function has to have both Dsetup.dll and Dsetup32.dll. These files are not installed on the system but they are included in the software development kit (SDK).

DirectXRegisterApplication corresponds to the old IDirectPlayLobby3::RegisterApplication method. It is recommended that you use the IDirectPlay8LobbiedApplication::RegisterProgram method instead.

Function Information

Header | dsetup.h
Import library | dsetup.lib
Minimum operating systems | Windows 98

See Also

DirectXUnRegisterApplication


DirectXSetup Function

Installs one or more Microsoft DirectX components.

Syntax

int DirectXSetup(

    HWND hWnd,
    LPSTR lpszRootPath,
    DWORD dwFlags
);

Parameters

hWnd
Handle of the parent window for the setup dialog boxes.
lpszRootPath
Address of a string that contains the root path of the DirectX component files. This string must specify a full path to the directory that contains the files Dsetup.dll and Dsetup32.dll, as well as the DirectX redistributable files. If this value is NULL, the current working directory is used.
dwFlags
One or more flags indicating which control the DirectSetup configuration.
DSETUP_DIRECTX
Installs DirectX run-time components, as well as DirectX-compatible display and audio drivers.
DSETUP_MANAGEDDX
Installs the DirectX 9.0 for Managed Code component. This requires that the Microsoft .NET Framework is installed.
DSETUP_TESTINSTALL
Performs a test installation. Does not install new components.

Return Value

If it fails, it returns an error value. For a list of possible return values, see Return Values. If this function succeeds, it returns one of the following success codes:

DSETUPERR_SUCCESS | Success.
DSETUPERR_SUCCESS_RESTART | Success, but the user must restart the system for the changes to take effect.

Remarks

Before using the DirectXSetup function in your setup program, you should first ensure that the system has enough available disk space. The maximum space that you need to set up DirectX 9.0 is 20 MB for Microsoft Windows 98 and Windows Millennium Edition (Windows Me) systems, and 25 MB for Windows 2000 and Windows XP.

The following flags can be specified for the dwFlags parameter but are ignored by DirectX 9.0.
DSETUP_D3D | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DDRAW | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DDRAWDRV | Not used in DirectX 8.1.
DSETUP_DINPUT | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DIRECTXSETUP | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DPLAY | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DPLAYSP | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DSOUND | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DSOUNDDRV | Not used in DirectX 8.1.
DSETUP_DXCORE | Installs DirectX run-time components. Does not install DirectX-compatible display and audio drivers.

Function Information

Header | dsetup.h
Import library | dsetup.lib
Minimum operating systems | Windows 98


DirectXSetupCallbackFunction Function

A placeholder name for an optional callback function supplied by the setup program. If present, it is called once for each step in the setup process.

Syntax

DWORD DirectXSetupCallbackFunction(

    DWORD Reason,
    DWORD MsgType,
    char *szMessage,
    char *szName,
    void *pInfo
);

Parameters

Reason
Reason for the callback. It can be one of the following values:
DSETUP_CB_MSG_BEGIN_INSTALL
DirectXSetup is about to begin installing Microsoft DirectX components. The system will be checked for the DirectX version, operating system, system language, and disk space requirements.
DSETUP_CB_MSG_BEGIN_INSTALL_RUNTIME
DirectXSetup is about to begin installing DirectX components.
DSETUP_CB_MSG_INTERNAL_ERROR
An internal error has occurred. Setup of the DirectX component or device driver has failed.
DSETUP_CB_MSG_NOMESSAGE
No message to be displayed. The callback function should return.
DSETUP_CB_MSG_PROGRESS
Reporting the progress of the runtime installation, which includes initializing, extracting, copying, and finalizing DirectSetup files.
DSETUP_CB_MSG_WARNING_DISABLED_COMPONENT
DirectSetup has detected that one or more DirectX components are disabled.
MsgType
Flags that control the display of a message box. These flags can be passed as the uType parameter to the MessageBox function. An exception is when MsgType is 0. In that case, the setup program can display status information but should not wait for input from the user.
szMessage
Pointer to a localized character string containing error or status messages that can be displayed in a dialog box created with the MessageBox function.
szName
NULL and can be ignored.
pInfo
Pointer to the address of a structure containing upgrade information. When Reason is DSETUP_CB_MSG_PROGRESS, the setup program supplies the current state of installation. In this case, pInfo points to a DSETUP_CB_PROGRESS structure containing information about the phase of the installation.

Return Value

The return value should be the same as the value that would be returned by the MessageBox function, with one exception. If this function returns 0, the DirectXSetup function performs the default action for upgrade of the DirectX component or driver.

Remarks

The name of DirectXSetupCallbackFunction is supplied by the setup program. The DirectXSetupSetCallback function is used to pass the address of the callback function to DirectSetup.

If MsgType is 0, the setup program can display status information but it should not wait for user input. In this case, the function returns IDOK.

If Reason is DSETUP_CB_MSG_WARNING_DISABLED_COMPONENT, direct the user to the DirectX Diagnostic Tool for more information about enabling DirectX components. It is typical for components such as Microsoft Direct3D to be disabled on Microsoft Windows servers.

Function Information

Header | dsetup.h
Import library | None
Minimum operating systems | Windows 98

See Also

DirectXSetupSetCallback, Customizing Setup


DirectXSetupGetEULA Function

Gets the Microsoft DirectX end-user license agreement (EULA) text for a specific language.

Syntax

int WINAPI DirectXSetupGetEULA(

    LPTSTR lpszEULA,
    UINT cchEULA,
    WORD LangID
);

Parameters

lpszEULA
[in] Points to a buffer that receives the EULA string. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
cchEULA
[out] Specifies the size of the buffer pointed to by the lpszEULA parameter. If this value is zero, the function returns the required buffer size and makes no use of the lpszEULA buffer. If the compiler settings specify Unicode, the size is in Unicode characters, otherwise the size will be in ANSI characters.
LangID
[in] Determines in which language the DirectX EULA is returned. Specify 0 for the system default language. Or specify one of the following values.
MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED)
MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_TRADITIONAL)
MAKELANGID(LANG_CZECH, SUBLANG_NEUTRAL)
MAKELANGID(LANG_DUTCH, SUBLANG_NEUTRAL)
MAKELANGID(LANG_ENGLISH, SUBLANG_NEUTRAL)
MAKELANGID(LANG_FRENCH, SUBLANG_NEUTRAL)
MAKELANGID(LANG_GERMAN, SUBLANG_NEUTRAL)
MAKELANGID(LANG_ITALIAN, SUBLANG_NEUTRAL)
MAKELANGID(LANG_JAPANESE, SUBLANG_NEUTRAL)
MAKELANGID(LANG_KOREAN, SUBLANG_NEUTRAL)
MAKELANGID(LANG_POLISH, SUBLANG_NEUTRAL)
MAKELANGID(LANG_PORTUGUESE, SUBLANG_NEUTRAL)
MAKELANGID(LANG_RUSSIAN, SUBLANG_NEUTRAL)
MAKELANGID(LANG_SPANISH, SUBLANG_NEUTRAL)
MAKELANGID(LANG_SWEDISH, SUBLANG_NEUTRAL)

Return Value

If the function succeeds, and cchEULA is nonzero, the return value is the number of EULA characters (Unicode or ANSI) written to the buffer pointed to by lpszEULA. If the function succeeds, and cchEULA is zero, the return value is the required size, in ANSI or Unicode characters, for a buffer that can receive the EULA string.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to DirectXSetupGetEULAW. Otherwise, the function call resolves to DirectXSetupGetEULAA because ANSI strings are being used.

If a LangID is passed that is not supported, the function will fail and return 0. In this case, the GetLastError return value will be ERROR_INVALID_PARAMETER. ERROR_INVALID_PARAMETER is also returned for the following reasons.

  • cchEULA is not large enough to receive the EULA.
  • cchEULA is nonzero and lpszEULA is NULL.
  • lpszEULA is an invalid pointer.

The setup application must display the EULA with in accordance with the DirectX software development kit (SDK) EULA.

The EULA must be displayed and accepted before continuing with DirectSetup.

Function Information

Header | dsetup.h
Import library | dsetup.lib
Minimum operating systems | Windows 98


DirectXSetupGetVersion Function

Retrieves the version number of the Microsoft DirectX components that are currently installed.

Syntax

INT DirectXSetupGetVersion(

    DWORD *pdwVersion,
    DWORD *pdwRevision
);

Parameters

pdwVersion
Pointer to the address of a variable to receive the version number. This parameter can be NULL if the version number is not wanted.
pdwRevision
Pointer to the address of a variable to receive the revision number. This parameter can be NULL if the revision number is not wanted.

Return Value

If the function succeeds, it returns nonzero.

If it fails, it returns 0.

Remarks

The DirectXSetupGetVersion function can be used to retrieve the version and revision numbers before or after the DirectXSetup function is called. If it is called before DirectXSetup is invoked, it gives the version and revision numbers of the DirectX components that are currently installed. If it is called after DirectXSetup is called, but before the computer is restarted, it gives the version and revision numbers of the DirectX components that take effect after the computer is restarted.

The version number in the pdwVersion parameter is composed of the major version number and the minor version number. The major version number is in the 16 most significant bits of the DWORD when this function returns. The minor version number is in the 16 least significant bits of the DWORD when this function returns. The version numbers can be interpreted as follows:

DirectX version | Value pointed to by pdwVersion
DirectX 5.0 | 0x00040005
DirectX 6.0 | 0x00040006
DirectX 7.0 | 0x00040007
DirectX 8.x | 0x00040008
DirectX 9.0 | 0x00040009

DirectX 9.0 supports only operating systems and DirectX versions later than Microsoft Windows 98 and DirectX 5.0. This method will not return a value less than 0x00040005 for pdwVersion.

The version number in the pdwRevision parameter is composed of the release number and the build number. The release number is in the 16 most significant bits of the DWORD when this function returns. The build number is in the 16 least significant bits of the DWORD when this function returns.

All DirectX 8.x releases have the same pdwVersion value. The pdwRevision parameter differentiates them. DirectX 8.x versions do not install on Windows XP. Windows XP shipped with DirectX 8.1 and the DirectX 8.1a and DirectX 8.1b updates were included in Windows XP Service Pack 1 (SP1). The following table lists the pdwRevision values for DirectX 8.x.

DirectX release | pdwRevision | Notes
DirectX 8.0
DirectX 8.1 | 0x0001032A | 4.08.01.0810. Windows XP version.
DirectX 8.1 | 0x00010371 | 4.08.01.0881. This is the DirectX 8.1 version for the down level operating systems. 0371 is the hex version for 0881 decimal revision value.
DirectX 8.1a | 0x00010385 | 4.08.01.0901. This release includes an update to Microsoft Direct3D (D3d8.dll).
DirectX 8.1b | 0x00010385 | 4.08.01.0901. This update includes a fix to Microsoft DirectShow on Windows 2000 (Quartz.dll).
DirectX 8.2 | 0x00020386 | 4.08.02.0134. This version includes Microsoft DirectPlay updates for both Windows XP and downlevel operating systems.

All DirectX 9.0 releases have the same pdwVersion value. The pdwRevision parameter differentiates them. The following table lists the pdwRevision values for DirectX 9.0 releases.

DirectX release | pdwRevision | Notes
DirectX 9.0 | 0x00000384 | 4.09.00.0900. This release includes many updates across all DirectX components.
DirectX 9.0a | 0x00000385 | 4.09.00.0901. This is an incremental update to DirectX 9.0, which include updates to DirectX for managed code, DirectPlay, Graphics, and DirectSetup components.
DirectX 9.0b | 0x00000386 | 4.09.00.0902. This is an incremental update, which includes DirectX 9.0a updates, plus additional updates to the DirectShow and Direct3D components.

Note There is no way to tell the difference between DirectX 8.1a and DirectX 8.1b with the pdwVersion and pdwRevision values. DirectX 8.1a updates only D3d8.dll. DirectX 8.1b includes the changes in DirectX 8.1a as well as updates to other files. Use GetFileVersionInfo to get version information for the following files.

On Windows 2000:

Quartz.dll | 6.03.01.0885
Stream.sys | 5.01.2600.0885
Mpg2splt.ax | 6.03.01.0885
D3d8.dll | 5.01.2600.0901
D3d8d.dll | 5.01.2600.0901

On Windows 95 or later:

Mpg2splt.ax | 6.03.01.0885
D3d8.dll | 4.08.01.0901
D3d8d.dll | 4.08.01.0901

The following sample code fragment demonstrates how the information returned by DirectXSetupGetVersion can be extracted and used.

DWORD dwVersion;
DWORD dwRevision;
if (DirectXSetupGetVersion(&dwVersion, &dwRevision))
{
    printf("DirectX version is %d.%d.%d.%d\n",
           HIWORD(dwVersion), LOWORD(dwVersion),
           HIWORD(dwRevision), LOWORD(dwRevision));
}

Version and revision numbers can be concatenated into a 64-bit quantity for comparison. The version number is in the 32 most significant bits and the revision number is in the 32 least significant bits.

Function Information

Header | dsetup.h
Import library | dsetup.lib
Minimum operating systems | Windows 98

See Also

DirectXSetup


DirectXSetupSetCallback Function

Sets a pointer to a callback function that is periodically called by DirectXSetup. The callback function can be used for setup progress notification and to implement a custom user interface for an application's setup program. For more information, see DirectXSetupCallbackFunction. If a setup program does not provide a callback function, DirectXSetupSetCallback is not invoked.

Syntax

INT DirectXSetupSetCallback(

    DSETUP_CALLBACK Callback
);

Parameters

Callback
Address of a callback function.

Return Value

Currently returns 0.

Remarks

To set a callback function, DirectXSetupSetCallback must be called before DirectXSetup is called.

The name of the callback function passed to DirectXSetupSetCallback is supplied by the setup program. However, it must match the prototype given in DirectXSetupCallbackFunction.

Function Information

Header | dsetup.h
Import library | dsetup.lib
Minimum operating systems | Windows 98

See Also

DirectXSetupCallbackFunction, DirectXSetup


DirectXSetupShowEULA Function

Displays the Microsoft DirectX end-user license agreement (EULA) in the system's localized language.

Syntax

int WINAPI DirectXSetupShowEULA(

    HWND hWndParent
);

Parameters

hWndParent
Handle of the parent window for the EULA dialog boxes.

Return Value

IDYES is returned if the user accepts the EULA and the application can continue with DirectSetup. Otherwise, IDNO is returned and the application must cancel DirectSetup.

Remarks

Both the EULA and dialog box displaying the EULA are localized to the system language.

If hWndParent equals NULL then DirectSetup uses the desktop as the parent window.

DirectXSetupShowEULA should be called before proceeding with DirectSetup.

Even if the local language for the system is changed to another language, using, for example, a multilingual user interface package, this application programming interface (API) displays the DirectX user interface (UI) in the system language. To display the EULA for local languages other than the system language, use DirectXSetupGetEULA.

IDNO is returned if the user rejects the EULA or an internal setup error occurs.

Function Information

Header | dsetup.h
Import library | dsetup.lib
Minimum operating systems | Windows 98


DirectXUnRegisterApplication Function

Deletes the registration of an application designed to work with IDirectPlayLobby3.

Syntax

int DirectXUnRegisterApplication(

    HWND hWnd,
    LPGUID lpGUID
);

Parameters

hWnd
Handle of the parent window. Set this to NULL if the desktop is the parent window.
lpGUID
Address of a globally unique identifier (GUID) that represents the Microsoft DirectPlay application to be unregistered.

Return Value

If the function succeeds, the return value is TRUE. This means that the registration is successfully deleted.

If the function fails, the return value is FALSE.

Remarks

The DirectXUnRegisterApplication function has to have both Dsetup.dll and Dsetup32.dll. These two files are not installed on the system but they are included in the software development kit (SDK).

DirectXUnRegisterApplication corresponds to the old IDirectPlayLobby3::UnregisterApplication method. It is recommended that you use theIDirectPlay8LobbiedApplication::UnregisterProgram method instead.

Function Information

Header | dsetup.h
Import library | dsetup.lib
Minimum operating systems | Windows 98

See Also

DirectXRegisterApplication


Structures
Microsoft DirectX 9.0 SDK Update (October 2004)

Structures

This section contains information about the following structures used with Microsoft DirectSetup.

  • DIRECTXREGISTERAPP
  • DIRECTXREGISTERAPP2
  • DSETUP_CB_PROGRESS
Note The memory for all Microsoft DirectX structures must be initialized to 0 before use. In addition, all structures that contain a dwSize member must set the member to the size of the structure, in bytes, before use.


DIRECTXREGISTERAPP Structure

Contains the registry entries needed for applications designed to work with IDirectPlayLobby3.

Syntax

typedef struct {
    DWORD dwSize;
    DWORD dwFlags;
    LPSTR lpszApplicationName;
    LPGUID lpGUID;
    LPSTR lpszFilename;
    LPSTR lpszCommandLine;
    LPSTR lpszPath;
    LPSTR lpszCurrentDirectory;
} DIRECTXREGISTERAPP, *PDIRECTXREGISTERAPP, *LPDIRECTXREGISTERAPP;

Members

dwSize
Size of the structure. This member must be initialized to the size of the DIRECTXREGISTERAPP structure.
dwFlags
Reserved.
lpszApplicationName
Name of the application.
lpGUID
globally unique identifier (GUID) of the application.
lpszFilename
Name of the executable file to be called.
lpszCommandLine
Command-line arguments for the executable file.
lpszPath
Path of the executable file.
lpszCurrentDirectory
Current directory. This is typically the same as lpszPath.

Structure Information

Header | dsetup.h
Minimum operating systems | Windows 98


DIRECTXREGISTERAPP2 Structure

Contains the registry entries needed for applications designed to work with IDirectPlayLobby3.

Syntax

typedef struct {
    DWORD dwSize;
    DWORD dwFlags;
    LPSTR lpszApplicationName;
    LPGUID lpGUID;
    LPSTR lpszFilename;
    LPSTR lpszCommandLine;
    LPSTR lpszPath;
    LPSTR lpszCurrentDirectory;
    LPSTR lpszLauncherName;
} DIRECTXREGISTERAPP2, *PDIRECTXREGISTERAPP2, *LPDIRECTXREGISTERAPP2;

Members

dwSize
Size of the structure. This member must be initialized to the size of the DIRECTXREGISTERAPP structure.
dwFlags
Reserved.
lpszApplicationName
Name of the application.
lpGUID
The globally unique identifier (GUID) of the application.
lpszFilename
Name of the executable file to be called.
lpszCommandLine
Command-line arguments for the executable file.
lpszPath
Path of the executable file.
lpszCurrentDirectory
Current directory. This is typically the same as lpszPath.
lpszLauncherName
Name of the executable to be launched from the lobby.

Structure Information

Header | dsetup.h
Minimum operating systems | Windows 98


DSETUP_CB_PROGRESS Structure

Passed as a parameter to the application-defined DirectXSetupCallbackFunction. It contains valid information only when the Reason parameter is DSETUP_CB_MSG_PROGRESS. Callback functions can use it to get status information on the upgrade that is about to be done.

Syntax

typedef struct _DSETUP_CB_PROGRESS {
    DWORD dwPhase;
    DWORD dwInPhaseMaximum;
    DWORD dwInPhaseProgress;
    DWORD dwOverallMaximum;
    DWORD dwOverallProgress;
} DSETUP_CB_PROGRESS;

Members

dwPhase
Flag indicating the phase of the install progress. Can be any of the DSETUP_CB_PROGRESS_PHASE flags.
dwInPhaseMaximum
This is the maximum number of files that will need to be extracted or copied during the DSETUP_EXTRACTING or DSETUP_COPYING phase. This is parameter is only used for the DSETUP_EXTRACTING and DSETUP_COPYING phases; otherwise it is zero and can be ignored.
dwInPhaseProgress
This is the current number of files that have been extracted or copied during the DSETUP_EXTRACTING or DSETUP_COPYING phase. This is parameter is only used for the DSETUP_EXTRACTING and DSETUP_COPYING phases; otherwise it is zero and can be ignored.
dwOverallMaximum
This is the total number of files for both the DSETUP_EXTRACTING and DSETUP_COPYING phase that need to be performed. This is parameter is only used for the DSETUP_EXTRACTING and DSETUP_COPYING phases; otherwise it is zero and can be ignored.
dwOverallProgress
This is the current number of files that have been extract or copied in relation to the dwOverallMaximum value. This is parameter is only used for the DSETUP_EXTRACTING and DSETUP_COPYING phases; otherwise it is zero and can be ignored.

Structure Information

Header | dsetup.h
Minimum operating systems | Windows 98

See Also

DirectXSetupCallbackFunction


Enumerations
Microsoft DirectX 9.0 SDK Update (October 2004)

Enumerations

This section contains information on the following enumerations used with Microsoft DirectSetup:

Enumerations

  • DSETUP_CB_PROGRESS_PHASE


DSETUP_CB_PROGRESS_PHASE Enumerated Type

Specifies the progress phase of a DirectSetup install.

Syntax

typedef enum _DSETUP_CB_PROGRESS_PHASE {
    DSETUP_INITIALIZING,
    DSETUP_EXTRACTING,
    DSETUP_COPYING,
    DSETUP_FINALIZING
} DSETUP_CB_PROGRESS_PHASE;

Constants

DSETUP_INITIALIZING

Initializing DirectSetup. Initialization includes version checking, an operating system check, and locale and disk space calculations.

DSETUP_EXTRACTING

Extracting files from the cabinet (.cab) files.

DSETUP_COPYING

Copying files onto the user's computer.

DSETUP_FINALIZING

Finalizing DirectSetup. This includes updating the registry and removing temporary files.

Enumerated Type Information

Header | dsetup.h
Minimum operating systems | Windows 98


Return Values Enumerated Type

The DirectXSetup function can return the following values. It can also return a standard Component Object Model (COM) error.

Syntax

typedef enum {
    DSETUPERR_SUCCESS,
    DSETUPERR_SUCCESS_RESTART,
    DSETUPERR_BADWINDOWSVERSION,
    DSETUPERR_CANTFINDDIR,
    DSETUPERR_CANTFINDINF,
    DSETUPERR_INTERNAL,
    DSETUPERR_NOTADMIN,
    DSETUPERR_NOCOPY,
    DSETUPERR_OUTOFDISKSPACE,
    DSETUPERR_SOURCEFILENOTFOUND,
    DSETUPERR_UNSUPPORTEDPROCESSOR,
    DSETUPERR_MISSINGCAB_MANAGEDDX,
    DSETUPERR_NODOTNETFRAMEWORKINSTALLED
} Return Values;

Constants

DSETUPERR_SUCCESS

Setup was successful, and no restart is required.

DSETUPERR_SUCCESS_RESTART

Setup was successful, and a restart is required.

DSETUPERR_BADWINDOWSVERSION

Microsoft DirectX does not support the Microsoft Windows version on the system.

DSETUPERR_CANTFINDDIR

The setup program could not find the working directory.

DSETUPERR_CANTFINDINF

A required .inf file could not be found.

DSETUPERR_INTERNAL

An internal error occurred.

DSETUPERR_NOTADMIN

The current user does not have administrative privileges. On Windows 2000 systems, the user may need administrative privileges for some setup operations.

DSETUPERR_NOCOPY

A file's version could not be verified or was incorrect.

DSETUPERR_OUTOFDISKSPACE

The setup program ran out of disk space during installation.

DSETUPERR_SOURCEFILENOTFOUND

One of the required source files could not be found.

DSETUPERR_UNSUPPORTEDPROCESSOR

The processor type is unsupported. DirectX 9.0 supports only Pentium or K6-compatible or higher processors.

DSETUPERR_MISSINGCAB_MANAGEDDX

ManagedDX.CAB is missing from the DirectX package.

DSETUPERR_NODOTNETFRAMEWORKINSTALLED

The Microsoft .NET Framework is not installed and is required for Managed DirectX.

Enumerated Type Information

Minimum operating systems Windows 98


IUnknown Interface

All Component Object Model (COM) objects support an interface called IUnknown. This interface provides Microsoft DirectX with control of the object's lifetime and the ability to retrieve other interfaces implemented by the object. IUnknown has three methods.

IUnknown Members

AddRef

Increases the interface's reference count by 1.

QueryInterface

Determines whether the object supports a particular COM interface. If it does, the system increases the object's reference count, and the application can use that interface immediately.

Release Decreases the reference count of the interface by 1.

Remarks

The IUnknown::AddRef and IUnknown::Release methods maintain an object's reference count. For example, if you create a Microsoft Direct3D object, the object's reference count is set to 1. Every time a function returns a pointer to an interface for that object, the function must call IUnknown::AddRef through that pointer to increment the reference count. Match each IUnknown::AddRef call with a call to IUnknown::Release. Before the pointer can be destroyed, you must call IUnknown::Release through that pointer. After an object's reference count reaches 0, the object is destroyed, and all interfaces to it become invalid.

The IUnknown::QueryInterface method determines whether an object supports a specific interface. If an object supports an interface, IUnknown::QueryInterface returns a pointer to that interface. You then can use the methods of that interface to communicate with the object. If IUnknown::QueryInterface successfully returns a pointer to an interface, it implicitly calls IUnknown::AddRef to increment the reference count, so your application must call IUnknown::Release to decrement the reference count before destroying the pointer to the interface.

Note The reference pages for IUnknown are included with this documentation as a convenience for users of the stand-alone DirectX Help file. Refer to the Microsoft Platform Software Development Kit (SDK) documentation for the most complete and up-to-date information about this interface.

Interface Information

Inherits from | None
Header | unknwn.h
Minimum operating systems | Windows 98


IUnknown::AddRef Method

Increases the interface's reference count by 1.

Syntax

ULONG AddRef(VOID);

Return Value

Returns the new reference count. This value is for diagnostic and testing purposes only.

Remarks

When the interface is created, its reference count is set to 1. Every time an application obtains an interface to the object or calls the IUnknown::AddRef method, the interface's reference count is increased by 1. Use the IUnknown::Release method to decrease the interface's reference count by 1.


IUnknown::QueryInterface Method

Determines whether the object supports a particular Component Object Model (COM) interface. If it does, the system increases the object's reference count, and the application can use that interface immediately.

Syntax

HRESULT QueryInterface(

    REFIID riid,
    LPVOID *ppvObj
);

Parameters

riid
Reference identifier of the interface being requested.
ppvObj
Address of a pointer to fill with the interface pointer if the query succeeds.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value may be E_NOINTERFACE. Some components also have their own definitions of these error values in their header files.

Remarks

If the application does not need to use the interface retrieved by a call to this method, it must call the IUnknown::Release method for that interface to free it. The IUnknown::QueryInterface method makes it possible to extend objects without interfering with functionality.


IUnknown::Release Method

Decreases the reference count of the interface by 1.

Syntax

ULONG Release(VOID);

Return Value

Returns the new reference count. This value is for diagnostic and testing purposes only.

Remarks

The object that exports the interface deallocates itself when its total reference count reaches 0. Use the IUnknown::AddRef method to increase the interface's reference count by 1.

Applications must call this method to release only those interfaces that were explicitly created in a previous call to IUnknown::AddRef, IUnknown::QueryInterface, or a creation function such as Direct3DCreate9.


DirectX Graphics
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectX Graphics

This section provides information about programming Microsoft DirectX graphics using C and C++.

Roadmap

Discover the features of DirectX 9.0 in one of these sections:

  • What's New in DirectX Graphics - This section highlights new 3-D graphics features and functionality.
  • Converting to DirectX 9.0 - This section introduces new features and will help you port an application to DirectX 9.0.
  • Programming Guide - This section contains architecture descriptions, functional block diagrams, descriptions of the building blocks in the pipeline, code snippets, and sample applications.
  • Tools - This section contains tools such as the DirectX Extensions for Visual Studio .NET for debugging DirectX applications.
  • Tutorials and Samples - This section contains tutorials and sample applications for using DirectX graphics.
  • Reference - This section contains the reference pages for the Microsoft Direct3D and D3DX application programming interface (API). This includes the syntax for the API methods, functions, instructions, and data structures. It includes an explanation of how each API method works and often includes code snippets.


What's New in DirectX Graphics
Microsoft DirectX 9.0 SDK Update (October 2004)

What's New in DirectX Graphics

This section describes Microsoft DirectX graphics features that are new or changed since the DirectX 9.0 SDK Update (Summer 2004).

  • PIX
  • New Samples
  • Debug Output Control
  • HLSL Struct Type Syntax
  • Texture Filtering
  • Maya Preview Pipeline

To convert applications from DirectX 8, see Converting to DirectX 9.0.

PIX

More documentation is provided for the PIX for Windows tool:

  • PIX
  • PIX Tutorials

New Samples

The following new samples are provided with the DirectX 9.0 SDK Update (October 2004):

  • AntiAlias
  • ConfigSystem
  • Firewall
  • Instancing

Preliminary documentation for the first three samples can be found at:

(SDK root)\Samples\C++\Direct3D\AntiAlias

(SDK root)\Samples\C++\Direct3D\ConfigSystem

(SDK root)\Samples\C++\Misc\Firewall

Debug Output Control

A new function has been provided to turn on or off all D3DX debug output. See D3DXDebugMute.

HLSL Struct Type Syntax

User-customizable struct data types are documented in the high-level shader language (HLSL) language reference section. See Struct Type Syntax.

Texture Filtering

A new topic on texture sampling is provided. See Bilinear Texture Filtering.

Maya Preview Pipeline

The preview pipeline for Alias' Maya application now functions with Maya Version 6.0. The installation procedure for the tool is also simplified. See Effect File Exporter (Maya Preview Pipeline).


Converting to DirectX 9.0
Microsoft DirectX 9.0 SDK Update (October 2004)

Converting to DirectX 9.0

The following features were changed in Microsoft DirectX 9.0. If you are using these features, see the changes listed below to help you port your application to DirectX 9.0.

  • BaseVertexIndex Changes
  • CreateImageSurface Changes
  • D3DENUM_NO_WHQL_LEVEL Changes
  • EnumAdapterModes Changes
  • Get/SetStreamSource Changes
  • Handles
  • Multisampling Quality Changes
  • ResourceManagerDiscardBytes Changes
  • SetSoftwareVertexProcessing Changes
  • Texture Sampler Changes
  • Vertex Declaration Changes
  • Intervals, and SwapEffects Changes

BaseVertexIndex Changes

In DirectX 8.x, IDirect3DDevice8::SetIndices World Wide Web link required a pointer to the index buffer and a BaseVertexIndex for the starting position in the vertex buffer. An application batching different objects into the vertex buffer had to switch the index buffer (or make a call to IDirect3DDevice9::SetIndices) before calling IDirect3DDevice9::DrawIndexedPrimitive.

In DirectX 9.0, the starting position in the vertex buffer, BaseVertexIndex, has been moved to IDirect3DDevice9::DrawIndexedPrimitive, and its data type changed from a DWORD to an INT.

HRESULT IDirect3DDevice9::DrawIndexedPrimitive(
    D3DPRIMITIVETYPE PrimType,
    INT BaseVertexIndex,
    UINT minIndex,
    UINT NumVertices,
    UINT startIndex,
    UINT primCount);

HRESULT SetIndices(IDirect3DIndexBuffer9* pIndexData);

CreateImageSurface Changes

IDirect3DDevice8::CreateImageSurface World Wide Web link was renamed IDirect3DDevice9::CreateOffscreenPlainSurface. An additional parameter that takes a D3DPOOL type was added. D3DPOOL_SCRATCH will return a surface that has identical characteristics to a surface created by the former IDirect3DDevice8::CreateImageSurface. D3DPOOL_DEFAULT is the appropriate pool for use with IDirect3DDevice9::StretchRect and IDirect3DDevice9::ColorFill.

D3DENUM_NO_WHQL_LEVEL Changes

Applications now have to explicitly ask for the Microsoft Windows Hardware Quality Labs (WHQL) because the response takes relatively long (a few seconds). D3DENUM_NO_WHQL_LEVEL has been removed and D3DENUM_WHQL_LEVEL has been added.

EnumAdapterModes Changes

The IDirect3D9::EnumAdapterModes now takes a D3DFORMAT.

HRESULT IDirect3D9::EnumAdapterModes(
       UINT Adapter,
       D3DFORMAT Format,
       UINT Mode,
       D3DDISPLAYMODE *pMode);

The format supports an expanding set of display modes. To protect applications from enumerating formats that were not invented when the application shipped, the application must tell Microsoft Direct3D the format for the display modes that should be enumerated. The resulting array of display modes will differ only by width, height, and refresh rate.

The application specifies a pixel format and the enumeration is restricted to those display modes that exactly match the format. The following is a list of the allowed formats:

  • D3DFMT_A1R5G5B5
  • D3DFMT_A2B10G10R10
  • D3DFMT_A8R8G8B8
  • D3DFMT_R5G6B5
  • D3DFMT_X1R5G5B5
  • D3DFMT_X8R8G8B8

Enumeration is equivalent for alpha and nonalpha versions of the same format. The returned Format will always be filled with the same format supplied by the application.

This method treats 565 and 555 as equivalent, and returns the correct version in the Format. The difference comes into play only when the application locks the back buffer, and there is an explicit flag that the application must set in order to accomplish this.

Get/SetStreamSource Changes

One parameter has been added to the IDirect3DDevice9::GetStreamSource and IDirect3DDevice9::SetStreamSource methods. The offset is the number of bytes between the beginning of the stream and the beginning of the vertex data. It is measured in bytes. This enables the pipeline to support stream offsets. To find out if the device supports stream offsets, see D3DDEVCAPS2_STREAMOFFSET.

HRESULT GetStreamSource(
    UINT StreamNumber,
    IDirect3DVertexBuffer9 **ppStreamData,
    UINT *pOffsetInBytes,
    UINT *pStride);

Handles

A handle has been added to several methods and should be set to NULL. The methods affected include:

  • IDirect3DDevice9::CreateTexture
  • IDirect3DDevice9::CreateVolumeTexture
  • IDirect3DDevice9::CreateCubeTexture
  • IDirect3DDevice9::CreateVertexBuffer
  • IDirect3DDevice9::CreateIndexBuffer
  • IDirect3DDevice9::CreateRenderTarget
  • IDirect3DDevice9::CreateDepthStencilSurface
  • IDirect3DDevice9::CreateOffscreenPlainSurface

Multisampling Quality Changes

Previously, there was only the D3DMULTISAMPLE_TYPE enumeration. DirectX 9.0 retains this enumeration and adds the idea of a quality level for each element of the enumeration. The quality level indicates a trade-off between visual quality and performance by indicating the number of maskable samples (in the sense of D3DRS_MULTISAMPLEMASK).

An application should choose how many maskable samples it requires, and then consult pQualityLevels. If nonzero, this value indicates the number of quality levels the application can pass to the various creation functions through MultiSampleQuality. Because drivers expose all their multisample schemes as quality levels at D3DMULTISAMPLE_NONMASKABLE, you can enumerate all available multisampling schemes through this one type if your application does not need to mask samples.

The D3DPRASTERCAPS_STRETCHBLTMULTISAMPLE caps bit has been retired. This bit used to mean that the multisampling method did not support write masks, and could not be toggled on and off between IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene. Such nonmaskable methods are now exposed through D3DMULTISAMPLE_NONMASKABLE.

HRESULT CheckDeviceMultiSampleType(
       UINT Adapter,
       D3DDEVTYPE DeviceType,
       D3DFORMAT SurfaceFormat,
       BOOL Windowed,
       D3DMULTISAMPLE_TYPE MultiSampleType,
       DWORD * pQualityLevels);

There is a different maximum for each number of maskable samples. For example, D3DMULTISAMPLE_4_SAMPLES might have three levels of quality, while D3DMULTISAMPLE_2_SAMPLES might have only one. There are at most eight levels of quality for each number of maskable samples (the driver is not allowed to express more). The quality ranges from zero to (*pQualityLevels - 1).

ResourceManagerDiscardBytes Changes

ResourceManagerDiscardBytes has been replaced by IDirect3DDevice9::EvictManagedResources. It can evict all resources, both Direct3D and driver resources.

The resource manager is now consulted when a resource (whether managed or nonmanaged) fails creation because there is insufficient video memory. The manager will automatically be asked to free enough resources for the creation to succeed. In DirectX 8.0, this was not an automated process.

SetSoftwareVertexProcessing Changes

An application can create a mixed-mode device to use software and hardware vertex processing.

To switch between the two vertex processing modes in DirectX 8.x, call IDirect3DDevice8::SetRenderState World Wide Web link. This has been replaced with IDirect3DDevice9::SetSoftwareVertexProcessing to ease problems caused by state blocks. This new method is not recorded by state blocks.

Texture Sampler Changes

DirectX 9.0 supports up to sixteen texture surfaces in one pass using the pixel shader 2_0 model; however, the number of texture coordinates remains limited to eight. Texture stage state is associated with surfaces, coordinate sets, vertex processing, and pixel processing. To manage these differences at compile time, IDirect3DDevice9::SetTextureStageState has been broken into two methods:

  • IDirect3DDevice9::SetTextureStageState will still be used for texture coordinate state, such as wrap modes and texture coordinate generation.
  • IDirect3DDevice9::SetSamplerState has been added and will now be used for filtering, tiling, clamping, MIPLOD, and so forth. This will work for up to sixteen samplers.

SetTextureStageState Changes

IDirect3DDevice9::SetTextureStageState now sets the following states:

  • Fixed function vertex processing state. This state controls the manipulation of texture coordinates D3DTSS_TEXTURETRANSFORMFLAGS and D3DTSS_TEXCOORDINDEX. Up to eight of each can be set (because eight texture coordinates are always supported). D3DTSS_TEXCOORDINDEX is a fixed function vertex processing state. If a programmable vertex shader is used, this state is ignored.
  • Fixed function pixel shader state (the legacy TextureStageState).
    — D3DTSS_ALPHAARG0
    — D3DTSS_ALPHAARG1
    — D3DTSS_ALPHAARG2
    — D3DTSS_ALPHAOP
    — D3DTSS_BUMPENVLOFFSET
    — D3DTSS_BUMPENVLSCALE
    — D3DTSS_BUMPENVMAT00
    — D3DTSS_BUMPENVMAT01
    — D3DTSS_BUMPENVMAT10
    — D3DTSS_BUMPENVMAT11
    — D3DTSS_COLORARG0
    — D3DTSS_COLORARG1
    — D3DTSS_COLORARG2
    — D3DTSS_COLOROP
    — D3DTSS_RESULTARG

    The number of fixed function pixel shader states that can be set is less than or equal to the number represented by MaxTextureBlendStages.

The number of texture samplers available to the application is determined by the pixel shader version, as indicated in the following table.

Name | Number
ps_1_1 to ps_1_3 | 4 texture samplers
ps_1_4 | 6 texture samplers
ps_2_0 | 16 texture samplers
fixed function pipeline | MaxTextureBlendStages/MaxSimultaneousTextures texture samplers

Devices that support displacement mapping in DirectX 9.0 will support an additional sampler (D3DDMAPSAMPLER), which samples the displacement maps in the tessellator unit.

SetSamplerState Changes

IDirect3DDevice9::SetSamplerState sets the sampler state (including the one used in the tessellator unit to sample displacement maps). These have been renamed with a D3DSAMP_ prefix to enable compile-time error detection when porting from DirectX 8.x. The states include:

  • D3DSAMP_ADDRESSU
  • D3DSAMP_ADDRESSV
  • D3DSAMP_ADDRESSW
  • D3DSAMP_BORDERCOLOR
  • D3DSAMP_MAGFILTER
  • D3DSAMP_MAXANISOTROPY
  • D3DSAMP_MAXMIPLEVEL
  • D3DSAMP_MINFILTER
  • D3DSAMP_MIPFILTER
  • D3DSAMP_MIPMAPLODBIAS

Vertex Declaration Changes

Vertex declarations are now decoupled from vertex shader creation. Vertex declarations now use a Component Object Model (COM) interface.

For DirectX 8.x, vertex declarations are tied to vertex shaders.

  • For the fixed function pipeline, call IDirect3DDevice9::SetVertexShader with the flexible vertex format (FVF) code of the vertex buffer.
  • For vertex shaders, call IDirect3DDevice9::SetVertexShader with a handle to a previously create vertex shader. The shader includes a vertex declaration.

For DirectX 9.0, vertex declarations are decoupled from vertex shaders and they can be used with either the fixed function pipeline or with shaders.

  • For the fixed function pipeline, there is no need to call IDirect3DDevice9::SetVertexShader. If, however, you want to switch to the fixed function pipeline and have previously used a vertex shader, call IDirect3DDevice9::SetVertexShader(NULL). When this is done, you will still need to call IDirect3DDevice9::SetFVF to declare the FVF code.
  • When using vertex shaders, call IDirect3DDevice9::SetVertexShader with the vertex shader object. Additionally, call IDirect3DDevice9::SetFVF to set up a vertex declaration. This uses the information implicit in the FVF. IDirect3DDevice9::SetVertexDeclaration can be called in place of IDirect3DDevice9::SetFVF because it supports vertex declarations that cannot be expressed with an FVF.

Intervals, and SwapEffects Changes

Several changes were made to give the user more control over monitor refresh rate, presentation rate, and front-buffer versus back-buffer drawing. They are as follows:

  • Removed one swap effect, D3DSWAPEFFECT_COPY_VSYNC, and one presentation rate, D3DPRESENT_RATE_UNLIMITED.
  • Renamed D3DPRESENT_PARAMETERS.FullScreen_PresentationInterval to PresentationIntervals.
  • Added D3DPRESENT_INTERVAL_IMMEDIATE, which means that the presentation is not synchronized with the vertical sync. As in DirectX 8.x, D3DPRESENT_INTERVAL_DEFAULT is defined as zero and is equivalent to D3DPRESENT_INTERVAL_ONE. D3DPRESENT_INTERVAL_DEFAULT is a convenience for initializing D3DPRESENT_PARAMETERS to zero.

For a detailed explanation of the modes and the intervals that are supported, see D3DPRESENT.


Further Information on 3-D Graphics
Microsoft DirectX 9.0 SDK Update (October 2004)

Further Information on 3-D Graphics

To see the latest news about Microsoft DirectX technology, including new features, announcements of upcoming conferences, frequently asked questions, featured game titles, and links to user communities, see the DirectX World Wide Web link Web site.

For the latest in-depth developer information, see the MSDN DirectX World Wide Web link Web site. This site contains DirectX downloads, the latest DirectX documentation, the "Driving DirectX" column, links to DirectX developer newsgroups, and more.

Also check out the DirectXDev technical discussion forum for DirectX developers that covers the areas of graphics, networking, and input. Forum archives are at DirectX Dev World Wide Web link.

You can find more information about the graphics and multimedia concepts and terms discussed throughout the DirectX documentation in the following sources.

  • Blinn, Jim. Jim Blinn's Corner: A Trip Down the Graphics Pipeline. San Francisco, CA: Morgan Kaufmann Publishers, 1996.
  • Eberly, David H. 3D Game Engine Design: A Practical Approach to Real-Time Computer Graphics. San Francisco, CA: Morgan Kaufmann Publishers, 2000.
  • Engel, Wolfgang F. Direct3D ShaderX: Vertex and Pixel Tips and Tricks. Plano, TX: Wordware Publishing, 2002.
  • Engel, Wolfgang F. Direct3D ShaderX2: Introductions & Tutorials with DirectX 9. Plano, TX: Wordware Publishing, 2003.
  • Engel, Wolfgang F. Direct3D ShaderX2: Shader Programming Tips & Tricks With Directx 9. Plano, TX: Wordware Publishing, 2003.
  • Engel, Wolfgang F., and Amir Geva. Beginning Direct3D Game Programming. Roseville, CA: Prima Tech, 2001.
  • Foley, James D., et al. Computer Graphics: Principles and Practice. Second ed. in C. Reading, MA: Addison-Wesley, 1995.
  • Haines, Eric, et al. RealTime Rendering. Second ed. Reading, MA: Addison-Wesley, 1991.
  • Gray, Kris. DirectX9 Programmable Graphics Pipeline. Redmond, WA: Microsoft Press, 2003.
  • Hearn, Donald, and M. Pauline Baker. Computer Graphics. Second ed. Englewood Cliffs, NJ: Prentice-Hall, 1994.
  • Shirley, Peter. Fundamentals of Computer Graphics. Natick, MA: AK Peters, 2002.
  • Walsh, Peter. The Zen of Direct3D Game Programming. Roseville, CA: Prima Publishing, 2001.
  • Watt, Alan. 3D Computer Graphics. Third ed. Harlow, England; Reading, MA: Addison-Wesley, 2000.
  • Watt, Alan, and Fabio Policarpo. 3D Games: Real-Time Rendering and Software Technology. Volumes 1 and 2. Reading, MA: Addison-Wesley, 2003.
  • Watt, Alan, and Mark Watt. Advanced Animation and Rendering Techniques: Theory and Practice. New York, NY: ACM Press; Wokingham, England; Reading, MA: Addison-Wesley, 1992.


Programming Guide
Microsoft DirectX 9.0 SDK Update (October 2004)

Programming Guide

This guide contains a description of the graphics pipeline implemented by Microsoft Direct3D. It is a guide for developers who implement 3-D graphics functionality into their applications. The guide contains architecture descriptions, functional block diagrams, and descriptions of the building blocks in the pipeline, as well as code snippets and sample applications. The information is divided into the following sections:

  • Getting Started - This section contains both an overview of the pipeline and tutorials that can help you get a simple graphics application running in a few minutes.
  • The Sample Framework - This section describes how to use the new toolkit functions of the sample framework to create simple to moderately complex Direct3D applications.
  • HLSL Shaders - This section covers programmable high-level shader language (HLSL) shaders. Included here are details about using vertex shaders for manipulating object geometry and pixel shaders for controlling pixel shading.
  • Effects - This section covers effects and effect files for building applications that can run on a variety of hardware platforms.
  • Advanced Topics - This section contains examples of different types of special effects you can implement. Topics such as environment and bump mapping, antialiasing, vertex blending, tweening, high dynamic range (HDR) lighting, and precomputed radiance transfer (PRT) show how to apply leading-edge special effects to your application.
  • Programming Tips - This section contains information to help you develop Direct3D graphics applications efficiently.

For more information about specific application programming interface (API) methods, see the Reference pages.


Getting Started
Microsoft DirectX 9.0 SDK Update (October 2004)

Getting Started

This section provides a brief introduction to the 3-D graphics functionality in the Microsoft Direct3D application programming interface (API). Here you will find an overview of the graphics pipeline and tutorials to help you get basic Direct3D functionality up and running quickly.

  • Direct3D Architecture
  • Direct3D Devices
  • Direct3D Resources
  • 3-D Coordinate Systems and Geometry
  • Transforms
  • Viewports and Clipping
  • Lights and Materials
  • Direct3D Rendering
  • Direct3D Surfaces
  • Direct3D Textures
  • D3DX Support
  • X Files (Legacy)

These books provide a thorough introduction to 3-D graphics in general:

  • Foley, James D., et al. Computer Graphics: Principles and Practice. Second ed. in C. Reading, MA: Addison-Wesley, 1995.
  • Haines, Eric, et al. RealTime Rendering. Second ed. Reading, MA: Addison-Wesley, 1991.

Additional references can be found in Further Information on 3-D Graphics.


Direct3D Architecture
Microsoft DirectX 9.0 SDK Update (October 2004)

Direct3D Architecture

This topic provides two high-level views of the architecture of Microsoft Direct3D:

  • Direct3D Graphics Pipeline—A view of the internal processing architecture of the Direct3D rendering system.
  • Direct3D System Integration—A view of how Direct3D mediates between an application and the graphics hardware.

Direct3D Graphics Pipeline

The graphics pipeline provides the horsepower to efficiently process and render 3-D scenes to a display, taking advantage of available hardware. This figure conceptually illustrates the building blocks of the pipeline:

Direct3D graphics pipeline diagram

Pipeline Component | Description | Related Topics
Vertex Data | Untransformed model vertices are stored in vertex memory buffers. | Vertex Buffers, IDirect3DVertexBuffer9
Primitive Data | Geometric primitives, including points, lines, triangles, and polygons, are referenced in the vertex data with index buffers. | Index Buffers, IDirect3DIndexBuffer9, 3-D Primitives, Higher-Order Primitives
Tessellation | The tesselator unit converts higher-order primitives, displacement maps, and mesh patches to vertex locations and stores those locations in vertex buffers. | Tessellation
Vertex Processing | 3-D transformations are applied to vertices stored in the vertex buffer. | Vertex Pipeline, Vertex Shader Basics
Geometry Processing | Clipping, back face culling, attribute evaluation, and rasterization are applied to the transformed vertices. | Pixel Pipeline
Textured Surface | Texture coordinates for 3-D surfaces are supplied to Direct3D through the IDirect3DTexture9 interface. | Direct3D Textures, IDirect3DTexture9
Texture Sampler | Texture level of detail (LOD) filtering is applied to input texture values. | Direct3D Textures
Pixel Processing | Pixel shader operations use geometry data to modify input vertex and texture data, yielding output pixel color values. | Pixel Shader Basics
Pixel Rendering | Final rendering processes modify pixel color values with alpha, depth, or stencil testing, or by applying alpha blending or fog. All resulting pixel values are presented to the output display. | Pixel Pipeline

Direct3D System Integration

This figure shows the relationships between a Microsoft Windows application, Direct3D, Windows Graphics Device Interface (GDI), and the hardware:

Direct3D system relationship diagram

Direct3D exposes a device-independent interface to an application. Direct3D applications can exist alongside GDI applications, and both have access to the computer's graphics hardware through the device driver for the graphics card. Unlike GDI, Direct3D can take advantage of hardware features by creating a hardware abstraction layer (HAL) device.

A HAL device provides hardware acceleration to graphics pipeline functions, based upon the feature set supported by the graphics card. Direct3D methods are provided to retrieve device display capabilities at run time. (See IDirect3D9::GetDeviceCaps and IDirect3DDevice9::GetDeviceCaps.) If a capability is not provided by the hardware, the HAL does not report it as a hardware capability.

For more information about HAL and reference devices supported by Direct3D, see Device Types.


Direct3D Devices
Microsoft DirectX 9.0 SDK Update (October 2004)

Direct3D Devices

A Microsoft Direct3D device is the rendering component of Direct3D. It encapsulates and stores the rendering state. In addition, a Direct3D device performs transformations and lighting operations and rasterizes an image to a surface.

  • Device Types
  • Creating a Device
  • Windowed vs Full-Screen Mode
  • Selecting a Device
  • Lost Devices
  • Determining Hardware Support
  • Processing Vertex Data
  • Primitives

Architecturally, Direct3D devices contain a transformation module, a lighting module, and a rasterizing module, as the following illustration shows.

Direct3D device architecture

Direct3D currently supports two main types of Direct3D devices:

  • A hardware abstraction layer (HAL) device with hardware-accelerated rasterization and shading with both hardware and software vertex processing
  • A reference device

You can think of these devices as two separate drivers. Software and reference devices are represented by software drivers, and the HAL device is represented by a hardware driver. The most common way to take advantage of these devices is to use the HAL device for shipping applications, and the reference device for feature testing. These are provided by third parties to emulate particular devices—for example, developmental hardware that has not yet been released.

The Direct3D device that an application creates must correspond to the capabilities of the hardware on which the application is running. Direct3D provides rendering capabilities, either by accessing 3-D hardware that is installed in the computer or by emulating the capabilities of 3-D hardware in software. Therefore, Direct3D provides devices for both hardware access and software emulation.

Hardware-accelerated devices give much better performance than software devices. The HAL device type is available on all Direct3D supported graphic adapters. In most cases, applications target computers that have hardware acceleration and rely on software emulation to accommodate lower-end computers.

With the exception of the reference device, software devices do not always support the same features as a hardware device. Applications should always query for device capabilities to determine which features are supported.

Because the behavior of the software and reference devices provided with Microsoft DirectX 9.0 is identical to that of the HAL device, application code authored to work with the HAL device will work with the software or reference devices without modifications. Note that while the provided software or reference device behavior is identical to that of the HAL device, the device capabilities do vary, and a particular software device may implement a much smaller set of capabilities.

Behaviors

Direct3D enables you to specify the behavior of a device, as well the device's type. The IDirect3D9::CreateDevice method enables a combination of one or more of the behavior flags to control the global behaviors of the Direct3D device. These behaviors specify what is and is not maintained in the run-time portion of Direct3D, and the device types specify which driver to use. Although some combinations of device behaviors are not valid, it is possible to use all device behaviors with all device types. For example, it is valid to specify D3DDEVTYPE_SW on a device created with D3DCREATE_PUREDEVICE.


Device Types
Microsoft DirectX 9.0 SDK Update (October 2004)

Device Types

HAL Device

The primary device type is the hardware abstraction layer (HAL) device, which supports hardware accelerated rasterization and both hardware and software vertex processing. If the computer on which your application is running is equipped with a display adapter that supports Microsoft Direct3D, your application should use it for 3-D operations. Direct3D HAL devices implement all or part of the transformation, lighting, and rasterizing modules in hardware.

Applications do not access graphics adapters directly. They call Direct3D functions and methods. Direct3D accesses the hardware through the HAL. If the computer that your application is running on supports the HAL, it will gain the best performance by using a HAL device.

To create a HAL device, call IDirect3D9::CreateDevice using D3DDEVTYPE_HAL as the device type.

Reference Device

Direct3D supports an additional device type called a reference device or reference rasterizer. Unlike a software device, the reference rasterizer supports every Direct3D feature. Because these features are implemented for accuracy rather than speed and are implemented in software, the results are not very fast. The reference rasterizer does make use of special CPU instructions whenever it can, but it is not intended for retail applications. Use the reference rasterizer only for feature testing or demonstration purposes. To create a reference device, call IDirect3D9::CreateDevice method using D3DDEVTYPE_REF as the device type.


Creating a Device
Microsoft DirectX 9.0 SDK Update (October 2004)

Creating a Device

To create a Microsoft Direct3D device, first create a Direct3D object (see Direct3DCreate9). All rendering devices created by a Direct3D object share the same physical resources. If you create multiple rendering devices from a single Direct3D object, extreme performance penalties will be incurred because they share the same hardware.

First, initialize values for the D3DPRESENT_PARAMETERS structure that is used to create the Direct3D device. The following code example specifies a windowed application where the back buffer is flipped to the front buffer during a vertical sync operation only.

LPDIRECT3DDEVICE9 pDevice = NULL;

D3DPRESENT_PARAMETERS d3dpp;

ZeroMemory( &d3dpp, sizeof(d3dpp) );
d3dpp.Windowed   = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_COPY;

Next, create the Direct3D device. The following IDirect3D9::CreateDevice call specifies the default adapter, a hardware abstraction layer (HAL) device, and software vertex processing.

if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                                  D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                      &d3dpp, &d3dDevice ) ) )
    return E_FAIL;

Note that a call to create, release, or reset the device should happen only on the same thread as the window procedure of the focus window.

After creating the device, set its state.


Windowed vs Full-Screen Mode
Microsoft DirectX 9.0 SDK Update (October 2004)

Windowed vs Full-Screen Mode

Microsoft Direct3D applications can run in either of two modes: full-screen or windowed.

Full-screen mode means the window that the application runs in covers the entire desktop, hiding all running applications (including your development environment). Games typically default to full-screen mode to fully immerse the user in the game by hiding all running applications. An application running in windowed-mode shares the desktop with all running applications. Code differences between full-screen mode and windowed mode are very small.

Because an application running in full-screen mode takes over the screen, debugging the application requires either a separate monitor or the use of a remote debugger. Use the DirectX Control Panel to enable multiple-monitor debugging. One advantage of a windowed-mode application is that you can step through the code in a debugger without multiple monitors or a remote debugger.


Selecting a Device
Microsoft DirectX 9.0 SDK Update (October 2004)

Selecting a Device

Applications can query hardware to detect the supported Microsoft Direct3D device types. This section contains information about the primary tasks involved in enumerating display adapters and selecting Direct3D devices.

An application must perform a series of tasks to select an appropriate Direct3D device. Note that the following steps are intended for a full-screen application. In most cases, a windowed application can skip most of these steps.

  1. Initially, the application must enumerate the display adapters on the system. An adapter is a physical piece of hardware. Note that the graphics card might contain more than a single adapter, as is the case with a dual-head display. Applications that are not concerned with multimonitor support can disregard this step, and pass D3DADAPTER_DEFAULT to the IDirect3D9::EnumAdapterModes method in step 2.
  2. For each adapter, the application enumerates the supported display modes by calling IDirect3D9::EnumAdapterModes.
  3. If required, the application checks for the presence of hardware acceleration in each enumerated display mode by calling IDirect3D9::CheckDeviceType, as shown in the following code example. Note that this is only one of the possible uses for IDirect3D9::CheckDeviceType; for details, see Determining Hardware Support.
    D3DPRESENT_PARAMETERS Params;
// Initialize values for D3DPRESENT_PARAMETERS members.

Params.BackBufferFormat = D3DFMT_X1R5G5B5;

if(FAILED(m_pD3D->CheckDeviceType(Device.m_uAdapter,
                                  Device.m_DevType,
                                  Params.BackBufferFormat, Params.BackBufferFormat,
                                  FALSE)))
        return E_FAIL;
  4. The application checks for the desired level of functionality for the device on this adapter by calling the IDirect3D9::GetDeviceCaps method. This method filters out those devices that do not support the required functionality. The device capability returned by IDirect3D9::GetDeviceCaps is guaranteed to be constant for a device across all display modes verified by IDirect3D9::CheckDeviceType.
  5. Devices can always render to surfaces of the format of an enumerated display mode that is supported by the device. If the application is required to render to a surface of a different format, it can call IDirect3D9::CheckDeviceFormat. If the device can render to the format, then it is guaranteed that all capabilities returned by IDirect3D9::GetDeviceCaps are applicable.
  6. Lastly, the application can determine if multisampling techniques, such as full-scene antialiasing, are supported for a render format by using the IDirect3D9::CheckDeviceMultiSampleType method.

After completing the above steps, the application should have a list of display modes in which it can operate. The final step is to verify that enough device-accessible memory is available to accommodate the required number of buffers and antialiasing. This test is necessary because the memory consumption for the mode and multisample combination is impossible to predict without verifying it. Moreover, some display adapter architectures might not have a constant amount of device-accessible memory. This means that an application should be able to report out-of-video-memory failures when going into full-screen mode. Typically, an application should remove full-screen mode from the list of modes it offers to a user, or it should attempt to consume less memory by reducing the number of back buffers or using a less complex multisampling technique.

A windowed application performs a similar set of tasks.

  1. It determines the desktop rectangle covered by the client area of the window.
  2. It enumerates adapters, looking for the adapter whose monitor covers the client area. If the client area is owned by more than one adapter, then the application can choose to drive each adapter independently, or to drive a single adapter and have Direct3D transfer pixels from one device to another at presentation. The application can also disregard the above two steps and use the D3DADAPTER_DEFAULT adapter. Note that this might result in slower operation when the window is placed on a secondary monitor.
  3. The application should call IDirect3D9::CheckDeviceType to determine if the device can support rendering to a back buffer of the specified format while in desktop mode. IDirect3D9::GetAdapterDisplayMode can be used to determine the desktop display format, as shown in the following code example.
    D3DPRESENT_PARAMETERS Params;
// Initialize values for D3DPRESENT_PARAMETERS members.

// Use the current display mode.
D3DDISPLAYMODE mode;

if(FAILED(m_pD3D->GetAdapterDisplayMode(Device.m_uAdapter , &mode)))
        return E_FAIL;

Params.BackBufferFormat = mode.Format;

if(FAILED(m_pD3D->CheckDeviceType(Device.m_uAdapter, Device.m_DevType,
Params.BackBufferFormat, Params.BackBufferFormat, FALSE)))
       return E_FAIL;


Lost Devices
Microsoft DirectX 9.0 SDK Update (October 2004)

Lost Devices

A Microsoft Direct3D device can be in either an operational state or a lost state. The operational state is the normal state of the device in which the device runs and presents all rendering as expected. The device makes a transition to the lost state when an event, such as the loss of keyboard focus in a full-screen application, causes rendering to become impossible. The lost state is characterized by the silent failure of all rendering operations, which means that the rendering methods can return success codes even though the rendering operations fail. In this situation, the error code D3DERR_DEVICELOST is returned by IDirect3DDevice9::Present.

By design, the full set of scenarios that can cause a device to become lost is not specified. Some typical examples include loss of focus, such as when the user presses ALT+TAB or when a system dialog is initialized. Devices can also be lost due to a power management event, or when another application assumes full-screen operation. In addition, any failure from IDirect3DDevice9::Reset puts the device into a lost state.

All methods that derive from IUnknown are guaranteed to work after a device is lost. After device loss, each function generally has the following three options:

  • Fail with D3DERR_DEVICELOST - This means that the application needs to recognize that the device was lost, so that the application identifies that something isn't happening as expected.
  • Silently fail, returning S_OK or any other return codes - If a function silently fails, the application generally can't distinguish between the result of "success" and a "silent failure."
  • The function returns a return code.

Responding to a Lost Device

A lost device must re-create resources (including video memory resources) after it has been reset. If a device is lost, the application queries the device to see if it can be restored to the operational state. If not, the application waits until the device can be restored.

If the device can be restored, the application prepares the device by destroying all video-memory resources and any swap chains. Then, the application calls the IDirect3DDevice9::Reset method. Reset is the only method that has an effect when a device is lost, and is the only method by which an application can change the device from a lost to an operational state. Reset will fail unless the application releases all resources that are allocated in D3DPOOL_DEFAULT, including those created by the IDirect3DDevice9::CreateRenderTarget and IDirect3DDevice9::CreateDepthStencilSurface methods.

For the most part, the high-frequency calls of Direct3D do not return any information about whether the device has been lost. The application can continue to call rendering methods, such as IDirect3DDevice9::DrawPrimitive, without receiving notification of a lost device. Internally, these operations are discarded until the device is reset to the operational state.

The application can determine what to do on encountering a lost device by querying the return value of the IDirect3DDevice9::TestCooperativeLevel method.

Locking Operations

Internally, Direct3D does enough work to ensure that a lock operation will succeed after a device is lost. However, it is not guaranteed that the video-memory resource's data will be accurate during the lock operation. It is guaranteed that no error code will be returned. This allows applications to be written without concern for device loss during a lock operation.

Resources

Resources can consume video memory. Because a lost device is disconnected from the video memory owned by the adapter, it is not possible to guarantee allocation of video memory when the device is lost. As a result, all resource creation methods are implemented to succeed by returning D3D_OK, but do in fact allocate only dummy system memory. Because any video-memory resource must be destroyed before the device is resized, there is no issue of over-allocating video memory. These dummy surfaces allow lock and copy operations to appear to function normally until the application calls IDirect3DDevice9::Present and discovers that the device has been lost.

All video memory must be released before a device can be reset from a lost state to an operational state. This means that the application should release any swap chains created with IDirect3DDevice9::CreateAdditionalSwapChain and any resources placed in the D3DPOOL_DEFAULT memory class. The application need not release resources in the D3DPOOL_MANAGED or D3DPOOL_SYSTEMMEM memory classes. Other state data is automatically destroyed by the transition to an operational state.

You are encouraged to develop applications with a single code path to respond to device loss. This code path is likely to be similar, if not identical, to the code path taken to initialize the device at startup.

Retrieved Data

Direct3D allows applications to validate texture and render states against single pass rendering by the hardware using IDirect3DDevice9::ValidateDevice. This method, which is typically invoked during initialization of the application, will return D3DERR_DEVICELOST if the device has been lost.

Direct3D also allows applications to copy generated or previously written images from video-memory resources to nonvolatile system-memory resources. Because the source images of such transfers might be lost at any time, Direct3D allows such copy operations to fail when the device is lost.

Regarding asynchronous queries, IDirect3DQuery9::GetData returns D3DERR_DEVICELOST if the FLUSH flag is specified, in order to indicate to the application that IDirect3DQuery9::GetData will never return S_OK.

The copy operation, IDirect3DDevice9::GetFrontBufferData, can fail with D3DERR_DEVICELOST since there is no primary surface when the device is lost. IDirect3DDevice9::CreateAdditionalSwapChain can also fail with D3DERR_DEVICELOST because a back buffer can't be created when the device is lost. Note that these cases are the only instance of D3DERR_DEVICELOST outside of the IDirect3DDevice9::Present, IDirect3DDevice9::TestCooperativeLevel, and IDirect3DDevice9::Reset methods.

Programmable Shaders

In Microsoft DirectX 9.0, Vertex Shaders and Pixel Shaders don't need to be re-created after reset. They will be remembered. In previous versions of DirectX, a lost device required shaders to be re-created.


Determining Hardware Support
Microsoft DirectX 9.0 SDK Update (October 2004)

Determining Hardware Support

Microsoft Direct3D provides the following functions to determine hardware support.

  • IDirect3D9::CheckDeviceFormat

    Used to verify whether a surface format can be used as a texture, whether a surface format can be used as a texture and a render target, or whether a surface format can be used as a depth-stencil buffer. In addition, this method is used to verify depth buffer format support and depth-stencil buffer format support.

  • IDirect3D9::CheckDeviceType

    Used to verify a device's ability to perform hardware acceleration, a device's ability to build a swap chain for presentation, or a device's ability to render to the current display format.

  • IDirect3D9::CheckDepthStencilMatch

    Used to verify whether a depth-stencil buffer format is compatible with a render-target format. Note that before calling this method, the application should call IDirect3D9::CheckDeviceFormat on both the depth-stencil and render-target formats.


Processing Vertex Data
Microsoft DirectX 9.0 SDK Update (October 2004)

Processing Vertex Data

The IDirect3DDevice9 interface supports vertex processing in both software and hardware. In general, the device capabilities for software and hardware vertex processing are not identical. Hardware capabilities are variable, depending on the display adapter and driver, while software capabilities are fixed.

The following flags control vertex processing behavior for the hardware abstraction layer (HAL) and reference devices.

  • D3DCREATE_SOFTWARE_VERTEXPROCESSING
  • D3DCREATE_HARDWARE_VERTEXPROCESSING
  • D3DCREATE_MIXED_VERTEXPROCESSING

Specify one of the vertex processing behavior flags when calling IDirect3D9::CreateDevice. The mixed-mode flag enables the device to perform both software and hardware vertex processing. Only one vertex processing flag may be set for a device at any one time. Note that the D3DCREATE_HARDWARE_VERTEXPROCESSING flag is required to be set when creating a pure device (D3DCREATE_PUREDEVICE).

To avoid dual vertex processing capabilities on a single device, only the hardware vertex processing capabilities can be queried at run time. Software vertex processing capabilities are fixed and cannot be queried at run time.

You can consult the VertexProcessingCaps member of the D3DCAPS9 structure to determine the hardware vertex processing capabilities of the device. For software vertex processing the following capabilities are supported.

  • the D3DVTXPCAPS_DIRECTIONALLIGHTS member of D3DVTXPCAPS
  • the D3DVTXPCAPS_LOCALVIEWER member of D3DVTXPCAPS
  • the D3DVTXPCAPS_MATERIALSOURCE7 member of D3DVTXPCAPS
  • the D3DVTXPCAPS_POSITIONALLIGHTS member of D3DVTXPCAPS
  • the D3DVTXPCAPS_TEXGEN member of D3DVTXPCAPS
  • the D3DVTXPCAPS_TWEENING member of D3DVTXPCAPS

In addition, the following table lists the values that are set for members of the D3DCAPS9 structure for a device in software vertex processing mode.

Member | Software vertex processing capabilities
MaxActiveLights | Unlimited
MaxUserClipPlanes | 6
MaxVertexBlendMatrices | 4
MaxStreams | 16
MaxVertexIndex | 0xFFFFFFFF

Software vertex processing provides a guaranteed set of vertex processing capabilities, including an unbounded number of lights and full support for programmable vertex shaders. You can toggle between software and hardware vertex processing at any time when using the HAL Device, the only device type that supports both hardware and software vertex processing. The only requirement is that vertex buffers used for software vertex processing must be allocated in system memory.

Note The performance of hardware vertex processing is comparable to that of software vertex processing. For this reason, it's a good idea to provide, within a single device type, both hardware- and software-emulation functionality for vertex processing. This is not the case for rasterization, for which host processors are much slower than specialized graphics hardware. Thus both hardware- and software-emulated rasterization is not provided within a single device type. Software vertex processing is the only instance of functionality duplicated between the run time and the hardware (driver) within a single device. Thus all other device capabilities represent potentially variable functionality provided by the driver.


Primitives
Microsoft DirectX 9.0 SDK Update (October 2004)

Primitives

Microsoft Direct3Ddevices can create and manipulate the following types of primitives.

  • Point Lists
  • Line Lists
  • Line Strips
  • Triangle Lists
  • Triangle Strips
  • Triangle Fans

You can render primitive types from a C++ application with any of the rendering methods of the IDirect3DDevice9 interface.

Related Topics

  • 3-D Primitives


Point Lists
Microsoft DirectX 9.0 SDK Update (October 2004)

Point Lists

A point list is a collection of vertices that are rendered as isolated points. Your application can use them in 3-D scenes for star fields, or dotted lines on the surface of a polygon.

The following illustration depicts a rendered point list.

Your application can apply materials and textures to a point list. The colors in the material or texture appear only at the points drawn, and not anywhere between the points.

The following code shows how to create vertices for this point list.

struct CUSTOMVERTEX
{
    float x,y,z;
};

CUSTOMVERTEX Vertices[] =
{
    {-5.0, -5.0, 0.0},
    { 0.0,  5.0, 0.0},
    { 5.0, -5.0, 0.0},
    {10.0,  5.0, 0.0},
    {15.0, -5.0, 0.0},
    {20.0,  5.0, 0.0}
};

The code example below shows how to use IDirect3DDevice9::DrawPrimitive to render this point list.

//
// It is assumed that d3dDevice is a valid
// pointer to a IDirect3DDevice9 interface.
//
d3dDevice->DrawPrimitive( D3DPT_POINTLIST, 0, 6 );


Line Lists
Microsoft DirectX 9.0 SDK Update (October 2004)

Line Lists

A line list is a list of isolated, straight line segments. Line lists are useful for such tasks as adding sleet or heavy rain to a 3-D scene. Applications create a line list by filling an array of vertices. Note that the number of vertices in a line list must be an even number greater than or equal to two.

The following illustration shows a rendered line list.

You can apply materials and textures to a line list. The colors in the material or texture appear only along the lines drawn, not at any point in between the lines.

The following code shows how to create vertices for this line list.

struct CUSTOMVERTEX
{
    float x,y,z;
};

CUSTOMVERTEX Vertices[] =
{
    {-5.0, -5.0, 0.0},
    { 0.0,  5.0, 0.0},
    { 5.0, -5.0, 0.0},
    {10.0,  5.0, 0.0},
    {15.0, -5.0, 0.0},
    {20.0,  5.0, 0.0}
};

The code example below shows how to use IDirect3DDevice9::DrawPrimitive to render this line list.

//
// It is assumed that d3dDevice is a valid
// pointer to a IDirect3DDevice9 interface.
//
d3dDevice->DrawPrimitive( D3DPT_LINELIST, 0, 3 );


Line Strips
Microsoft DirectX 9.0 SDK Update (October 2004)

Line Strips

A line strip is a primitive that is composed of connected line segments. Your application can use line strips for creating polygons that are not closed. A closed polygon is a polygon whose last vertex is connected to its first vertex by a line segment. If your application makes polygons based on line strips, the vertices are not guaranteed to be coplanar.

The following illustration depicts a rendered line strip.

The following code shows how to create vertices for this line strip.

struct CUSTOMVERTEX
{
    float x,y,z;
};

CUSTOMVERTEX Vertices[] =
{
    {-5.0, -5.0, 0.0},
    { 0.0,  5.0, 0.0},
    { 5.0, -5.0, 0.0},
    {10.0,  5.0, 0.0},
    {15.0, -5.0, 0.0},
    {20.0,  5.0, 0.0}
};

The code example below shows how to use IDirect3DDevice9::DrawPrimitive to render this line strip.

//
// It is assumed that d3dDevice is a valid
// pointer to a IDirect3DDevice9 interface.
//
d3dDevice->DrawPrimitive( D3DPT_LINESTRIP, 0, 5 );


Triangle Lists
Microsoft DirectX 9.0 SDK Update (October 2004)

Triangle Lists

A triangle list is a list of isolated triangles. They might or might not be near each other. A triangle list must have at least three vertices and the total number of vertices must be divisible by three.

Use triangle lists to create an object that is composed of disjoint pieces. For instance, one way to create a force-field wall in a 3-D game is to specify a large list of small, unconnected triangles. Then apply a material and texture that appears to emit light to the triangle list. Each triangle in the wall appears to glow. The scene behind the wall becomes partially visible through the gaps between the triangles, as a player might expect when looking at a force field.

Triangle lists are also useful for creating primitives that have sharp edges and are shaded with Gouraud shading. See Face and Vertex Normal Vectors.

The following illustration depicts a rendered triangle list.

Rendered triangle list

The following code shows how to create vertices for this triangle list.

struct CUSTOMVERTEX
{
    float x,y,z;
};

CUSTOMVERTEX Vertices[] =
{
    {-5.0, -5.0, 0.0},
    { 0.0,  5.0, 0.0},
    { 5.0, -5.0, 0.0},
    {10.0,  5.0, 0.0},
    {15.0, -5.0, 0.0},
    {20.0,  5.0, 0.0}

};

The code example below shows how to use IDirect3DDevice9::DrawPrimitive to render this triangle list.

//
// It is assumed that d3dDevice is a valid
// pointer to a IDirect3DDevice9 interface.
//
d3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, 2 );


Triangle Strips
Microsoft DirectX 9.0 SDK Update (October 2004)

Triangle Strips

A triangle strip is a series of connected triangles. Because the triangles are connected, the application does not need to repeatedly specify all three vertices for each triangle. For example, you need only seven vertices to define the following triangle strip:

The system uses vertices v1, v2, and v3 to draw the first triangle; v2, v4, and v3 to draw the second triangle; v3, v4, and v5 to draw the third; v4, v6, and v5 to draw the fourth; and so on. Notice that the vertices of the second and fourth triangles are out of order; this is required to make sure that all the triangles are drawn in a clockwise orientation.

Most objects in 3-D scenes are composed of triangle strips. This is because triangle strips can be used to specify complex objects in a way that makes efficient use of memory and processing time.

The following illustration depicts a rendered triangle strip.

Rendered triangle strip

The following code shows how to create vertices for this triangle strip.

struct CUSTOMVERTEX
{
    float x,y,z;
};

CUSTOMVERTEX Vertices[] =
{
    {-5.0, -5.0, 0.0},
    { 0.0,  5.0, 0.0},
    { 5.0, -5.0, 0.0},
    {10.0,  5.0, 0.0},
    {15.0, -5.0, 0.0},
    {20.0,  5.0, 0.0}
};

The code example below shows how to use IDirect3DDevice9::DrawPrimitive to render this triangle strip.

//
// It is assumed that d3dDevice is a valid
// pointer to a IDirect3DDevice9 interface.
//
d3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 4);


Triangle Fans
Microsoft DirectX 9.0 SDK Update (October 2004)

Triangle Fans

A triangle fan is similar to a triangle strip, except that all the triangles share one vertex. This is shown in the following illustration:

The system uses vertices v2, v3, and v1 to draw the first triangle; v3, v4, and v1 to draw the second triangle; v4, v5, and v1 to draw the third triangle; and so on. When flat shading is enabled, the system shades the triangle with the color from its first vertex.

This illustration depicts a rendered triangle fan.

Rendered triangle fan

The following code shows how to create vertices for this triangle fan.

struct CUSTOMVERTEX
{
    float x,y,z;
};

CUSTOMVERTEX Vertices[] =
{
    { 0.0, 0.0, 0.0},
    {-5.0, 5.0, 0.0},
    {-3.0,  7.0, 0.0},
    { 0.0, 10.0, 0.0},
    { 3.0,  7.0, 0.0},
    { 5.0,  5.0, 0.0},
};

The code example below shows how to use IDirect3DDevice9::DrawPrimitive to render this triangle fan.

//
// It is assumed that d3dDevice is a valid
// pointer to a IDirect3DDevice9 interface.
//
d3dDevice->DrawPrimitive( D3DPT_TRIANGLEFAN, 0, 4 );


States
Microsoft DirectX 9.0 SDK Update (October 2004)

States

A Microsoft Direct3D device uses states to set-up all of the pipeline processing. Sampler states control the set-up of the texture samplers by defining texture addressing and filter modes for example. Texture states set-up the multi-texture blender which controls how textures are combined and blended with each other. Render states control most of the pipeline state.

State blocks are a convenient mechanism for saving and restoring state. See State Blocks Save and Restore State


State Blocks Save and Restore State
Microsoft DirectX 9.0 SDK Update (October 2004)

State Blocks Save and Restore State

A state block is a group of device states. Device state is made up of render state, vertex state, pixel state, or all of the above. A state block contains a snapshot of a device's current state, or you can create a state block that records each state change that your application makes.

  • Create a State Block
  • Capture State Information

Create a State Block

Choose the type of state that you want to capture, and create a state block like this:

  IDirect3DStateBlock9* pStateBlock = NULL;
  pd3dDevice->CreateStateBlock( D3DSBT_ALL, &pStateBlock );
);

IDirect3DDevice9::CreateStateBlock creates a state block, and captures the device state. The device state is specified by the state block type in the first argument. This state can be one of the following:

  • All device state (see Saving All Device State With a StateBlock).
  • All pixel state (see Saving Pixel States With a StateBlock).
  • All vertex state (see Saving Vertex States With a StateBlock).

Capture State Information

Creating a state block automatically captures the current device state. The effect system uses a state block to save state. After ID3DXEffect::Begin is called, a state block is created and state is captured. When ID3DXEffect::End is called, the state block state is reapplied to the device.

To save a custom state sequence, wrap the state that you want to save in a IDirect3DDevice9::BeginStateBlock and IDirect3DDevice9::EndStateBlock pair. IDirect3DDevice9::BeginStateBlock tells the current device to set up a state block and add to it every state change that occurs until IDirect3DDevice9::EndStateBlock is called. Here's an example:

  IDirect3DStateBlock9* pStateBlock = NULL;
  pd3dDevice->BeginStateBlock();

  // Any number of state changes can occur here
  // SetRenderState, SetSamplerState, SetTextureStageState ...

  pd3dDevice->EndStateBlock( &pStateBlock );

This will save any number of state changes in any sequence to a custom stateblock. Later, when you want to use the stateblock to reset the device state, call IDirect3DStateBlock9::Apply. This will overwrite only the device state that has been captured in the state block. Any other device state that was not captured with the custom stateblock will not be changed. Once again, since the stateblock object is an interface, you will need to release it when you are done with it.


Saving All Device States with a StateBlock
Microsoft DirectX 9.0 SDK Update (October 2004)

Saving All Device States with a StateBlock

A state block can be used to capture all device states (see State Blocks Save and Restore State). The following state elements are included in the device state:

  • Vertex state (see Saving Vertex States With a StateBlock).
  • Pixel state (see Saving Pixel States With a StateBlock).
  • Each texture assigned to a sampler.
  • Each vertex texture.
  • Each displacement map texture.
  • The current texture palette.
  • For each vertex stream: a pointer to the vertex buffer, each argument from IDirect3DDevice9::SetStreamSource, and the divider (if any) from IDirect3DDevice9::SetStreamSourceFreq.
  • A pointer to the index buffer.
  • The viewport.
  • The scissors rectangle.
  • The world, view, and projection matrices.
  • The texture transforms.
  • The clipping planes (if any).
  • The current material.

To capture all device states with a state block, specify D3DSBT_ALL when calling IDirect3DDevice9::CreateStateBlock.


Saving Vertex States With a StateBlock
Microsoft DirectX 9.0 SDK Update (October 2004)

Saving Vertex States With a StateBlock

A state block can be used to capture only vertex state (see State Blocks Save and Restore State). The following state is vertex state:

  • Vertex render state (see Vertex Pipeline: Render State).
  • Vertex sampler state (see Vertex Pipeline: Sampler State).
  • Vertex texture state (see Vertex Pipeline: Texture State).
  • The NPatch mode segments from IDirect3DDevice9::SetNPatchMode.
  • Each light from IDirect3DDevice9::SetLight, as well as whether or not the light is enabled with IDirect3DDevice9::LightEnable.
  • The current vertex shader and each of the vertex shader constants.
  • For each vertex stream, store the divider value from IDirect3DDevice9::SetStreamSourceFreq.
  • The current vertex declaration.

To capture vertex state with a state block, specify D3DSBT_VERTEXSTATE when calling IDirect3DDevice9::CreateStateBlock.

Vertex Pipeline: Render State

Device render states affect the behavior of almost every part of the pipeline. Render states are set by calling IDirect3DDevice9::SetRenderState.

The following table includes all render states that set-up vertex state:

Render States | Default Value
D3DRS_CULLMODE | D3DCULL_CCW
D3DRS_FOGCOLOR | 0
D3DRS_FOGTABLEMODE | D3DFOG_NONE
D3DRS_FOGSTART | 0
D3DRS_FOGEND | 1
D3DRS_FOGDENSITY | 1
D3DRS_RANGEFOGENABLE | FALSE
D3DRS_AMBIENT | 0
D3DRS_COLORVERTEX | TRUE
D3DRS_FOGVERTEXMODE | D3DFOG_NONE
D3DRS_CLIPPING | TRUE
D3DRS_LIGHTING | TRUE
D3DRS_LOCALVIEWER | TRUE
D3DRS_EMISSIVEMATERIALSOURCE | D3DMCS_MATERIAL
D3DRS_AMBIENTMATERIALSOURCE | D3DMCS_MATERIAL
D3DRS_DIFFUSEMATERIALSOURCE | D3DMCS_COLOR1
D3DRS_SPECULARMATERIALSOURCE | D3DMCS_COLOR2
D3DRS_VERTEXBLEND | D3DVBF_DISABLE
D3DRS_CLIPPLANEENABLE | 0
D3DRS_POINTSIZE | Driver dependent
D3DRS_POINTSIZE_MIN | 1
D3DRS_POINTSPRITEENABLE | FALSE
D3DRS_POINTSCALEENABLE | FALSE
D3DRS_POINTSCALE_A | 1
D3DRS_POINTSCALE_B | 0
D3DRS_POINTSCALE_C | 0
D3DRS_MULTISAMPLEANTIALIAS | TRUE
D3DRS_MULTISAMPLEMASK | 0xffffffff
D3DRS_PATCHEDGESTYLE | D3DPATCHEDGE_DISCRETE
D3DRS_POINTSIZE_MAX | 1
D3DRS_INDEXEDVERTEXBLENDENABLE | FALSE
D3DRS_TWEENFACTOR | 0
D3DRS_POSITIONDEGREE | D3DDEGREE_CUBIC
D3DRS_NORMALDEGREE | D3DDEGREE_LINEAR
D3DRS_MINTESSELLATIONLEVEL | 1
D3DRS_MAXTESSELLATIONLEVEL | 1
D3DRS_ADAPTIVETESS_X | 0
D3DRS_ADAPTIVETESS_Y | 0
D3DRS_ADAPTIVETESS_Z | 1
D3DRS_ADAPTIVETESS_W | 0
D3DRS_ENABLEADAPTIVETESSELLATION | FALSE

Vertex Pipeline: Sampler State

Sampler states control sampling related topics such as filtering, tiling, and texture coordinate address modes. Use IDirect3DDevice9::SetSamplerState to set up the sampler state (including the one used in the tessellator unit to sample displacement maps). The sampler states have been renamed with a "D3DSAMP_" prefix to enable compile time error detection when porting from Microsoft DirectX 8.x.

The following table includes all sampler states that set-up vertex state:

Sampler States | Default Value
D3DSAMP_DMAPOFFSET | 256

Vertex Pipeline: Texture State

Texture states control texture blending operations of the multi-texture blender. Use IDirect3DDevice9::SetTextureStageState to set-up texture states. Use IDirect3DDevice9::SetTexture to associate a texture with a sampler stage.

The following table includes all the texture states that set-up vertex state:

Texture States | Default Value
D3DTSS_TEXCOORDINDEX | 0
D3DTSS_TEXTURETRANSFORMFLAGS | D3DTTFF_DISABLE

D3DTSS_TEXCOORDINDEX is a fixed function vertex processing state. If a programmable vertex shader is used, this state is ignored.


Saving Pixel State With a StateBlock
Microsoft DirectX 9.0 SDK Update (October 2004)

Saving Pixel State With a StateBlock

A state block can be used to capture only pixel state (see State Blocks Save and Restore State). The following state is pixel state:

  • Pixel render state (see Pixel Pipeline: Render State).
  • Pixel texture state (see Pixel Pipeline: Texture State).
  • Pixel sampler state (see Pixel Pipeline: Sampler State).
  • The current pixel shader and each of the pixel shader constants.

To capture pixel state with a state block, specify D3DSBT_PIXELSTATE when calling IDirect3DDevice9::CreateStateBlock.

Pixel Pipeline: Render State

Device render states affect the behavior of almost every part of the pipeline. Render states are set by calling IDirect3DDevice9::SetRenderState.

The following table includes all render states that set-up pixel state:

Render States | Default Value
D3DRS_ZENABLE | D3DZB_FALSE
D3DRS_SPECULARENABLE | FALSE
D3DFILLMODE | D3DFILL_SOLID
D3DSHADEMODE | D3DSHADE_GOURAUD
D3DRS_ZWRITEENABLE | TRUE
D3DRS_ALPHATESTENABLE | FALSE
D3DRS_LASTPIXEL | TRUE
D3DRS_SRCBLEND | D3DBLEND_ONE
D3DRS_DESTBLEND | D3DBLEND_ZERO
D3DRS_ZFUNC | D3DCMP_LESSEQUAL
D3DRS_ALPHAREF | 0
D3DRS_ALPHAFUNC | D3DCMP_ALWAYS
D3DRS_DITHERENABLE | FALSE
D3DRS_FOGSTART | 0
D3DRS_FOGEND | 1
D3DRS_FOGDENSITY | 1
D3DRS_ALPHABLENDENABLE | FALSE
D3DRS_DEPTHBIAS | 0
D3DRS_STENCILENABLE | FALSE
D3DRS_STENCILFAIL | D3DSTENCILOP_KEEP
D3DRS_STENCILZFAIL | D3DSTENCILOP_KEEP
D3DRS_STENCILPASS | D3DSTENCILOP_KEEP
D3DRS_STENCILFUNC | D3DCMP_ALWAYS
D3DRS_STENCILREF | 0
D3DRS_STENCILMASK | 0xffffffff
D3DRS_STENCILWRITEMASK | 0xffffffff
D3DRS_TEXTUREFACTOR | 0xffffffff
D3DRS_WRAP0 | 0
D3DRS_WRAP1 | 0
D3DRS_WRAP2 | 0
D3DRS_WRAP3 | 0
D3DRS_WRAP4 | 0
D3DRS_WRAP5 | 0
D3DRS_WRAP6 | 0
D3DRS_WRAP7 | 0
D3DRS_WRAP8 | 0
D3DRS_WRAP9 | 0
D3DRS_WRAP10 | 0
D3DRS_WRAP11 | 0
D3DRS_WRAP12 | 0
D3DRS_WRAP13 | 0
D3DRS_WRAP14 | 0
D3DRS_WRAP15 | 0
D3DRS_LOCALVIEWER | TRUE
D3DRS_EMISSIVEMATERIALSOURCE | D3DMCS_MATERIAL
D3DRS_AMBIENTMATERIALSOURCE | D3DMCS_MATERIAL
D3DRS_DIFFUSEMATERIALSOURCE | D3DMCS_COLOR1
D3DRS_SPECULARMATERIALSOURCE | D3DMCS_COLOR2
D3DRS_COLORWRITEENABLE | 0x0000000f
D3DBLENDOP | D3DBLENDOP_ADD
D3DRS_SCISSORTESTENABLE | FALSE
D3DRS_SLOPESCALEDEPTHBIAS | 0
D3DRS_ANTIALIASEDLINEENABLE | FALSE
D3DRS_TWOSIDEDSTENCILMODE | FALSE
D3DRS_CCW_STENCILFAIL | D3DSTENCILOP_KEEP
D3DRS_CCW_STENCILZFAIL | D3DSTENCILOP_KEEP
D3DRS_CCW_STENCILPASS | D3DSTENCILOP_KEEP
D3DRS_CCW_STENCILFUNC | D3DCMP_ALWAYS
D3DRS_COLORWRITEENABLE1 | 0x0000000f
D3DRS_COLORWRITEENABLE2 | 0x0000000f
D3DRS_COLORWRITEENABLE3 | 0x0000000f
D3DRS_BLENDFACTOR | 0xffffffff
D3DRS_SRGBWRITEENABLE | 0
D3DRS_SEPARATEALPHABLENDENABLE | FALSE
D3DRS_SRCBLENDALPHA | D3DBLEND_ONE
D3DRS_DESTBLENDALPHA | D3DBLEND_ZERO
D3DRS_BLENDOPALPHA | D3DBLENDOP_ADD

Pixel Pipeline: Sampler State

Sampler states control sampling related topics such as filtering, tiling, and texture coordinate address modes. Use IDirect3DDevice9::SetSamplerState to set up the sampler state (including the one used in the tessellator unit to sample displacement maps). The sampler states have been renamed with a "D3DSAMP_" prefix to enable compile time error detection when porting from Microsoft DirectX 8.x.

The following table includes all sampler states that set-up pixel state:

Sampler States | Default Value
D3DSAMP_ADDRESSU | D3DTADDRESS_WRAP
D3DSAMP_ADDRESSV | D3DTADDRESS_WRAP
D3DSAMP_ADDRESSW | D3DTADDRESS_WRAP
D3DSAMP_BORDERCOLOR | 0x00000000
D3DSAMP_MAGFILTER | D3DTEXF_POINT
D3DSAMP_MINFILTER | D3DTEXF_POINT
D3DSAMP_MIPFILTER | D3DTEXF_NONE
D3DSAMP_MIPMAPLODBIAS | 0
D3DSAMP_MAXMIPLEVEL | 0
D3DSAMP_MAXANISOTROPY | 1
D3DSAMP_SRGBTEXTURE | 0
D3DSAMP_ELEMENTINDEX | 0

Pixel Pipeline: Texture State

Texture states control texture blending operations of the multi-texture blender. Use IDirect3DDevice9::SetTextureStageState to set-up texture stage states. Use IDirect3DDevice9::SetTexture to associate a texture with a sampler stage.

The following table includes all the texture states that set-up pixel state:

Texture States | Default Value
D3DTSS_COLOROP | D3DTOP_DISABLE
D3DTSS_COLORARG1 | D3DTA_TEXTURE
D3DTSS_COLORARG2 | D3DTA_CURRENT
D3DTSS_ALPHAOP | D3DTOP_DISABLE
D3DTSS_ALPHAARG1 | D3DTA_TEXTURE
D3DTSS_ALPHAARG2 | D3DTA_CURRENT
D3DTSS_BUMPENVMAT00 | 0
D3DTSS_BUMPENVMAT01 | 0
D3DTSS_BUMPENVMAT10 | 0
D3DTSS_BUMPENVMAT11 | 0
D3DTSS_TEXCOORDINDEX | 0
D3DTSS_BUMPENVLSCALE | 0
D3DTSS_BUMPENVLOFFSET | 0
D3DTSS_TEXTURETRANSFORMFLAGS | D3DTTFF_DISABLE
D3DTSS_COLORARG0 | D3DTA_CURRENT
D3DTSS_ALPHAARG0 | D3DTA_CURRENT
D3DTSS_RESULTARG | D3DTA_CURRENT


Render States
Microsoft DirectX 9.0 SDK Update (October 2004)

Render States

Device render states affect the behavior of almost every part of the pipeline. Render states are set by calling IDirect3DDevice9::SetRenderState.

Additional information is contained in the following topics:

  • Alpha Blending State
  • Alpha Testing State
  • Ambient Lighting State
  • Antialiasing State
  • Culling State
  • Depth Buffering State
  • Fog State
  • Lighting State
  • Outline and Fill State
  • Per-Vertex Color State
  • Primitive Clipping State
  • Shading State
  • Stencil Buffer State
  • Texture Wrapping State


Alpha Blending State
Microsoft DirectX 9.0 SDK Update (October 2004)

Alpha Blending State

The alpha value of a color controls its transparency. Enabling alpha blending allows colors, materials, and textures on a surface to be blended with transparency onto another surface.

For more information, see Alpha Texture Blending and Texture Blending.

Applications written in C++ use the D3DRS_ALPHABLENDENABLE render state to enable alpha transparency blending. The Microsoft Direct3D application programming interface (API) allows many types of alpha blending. However, it is important to note the user's 3-D hardware might not support all the blending states allowed by Direct3D.

The type of alpha blending that is done depends on the D3DRS_SRCBLEND and D3DRS_DESTBLEND render states. Source and destination blend states are used in pairs. The following code example demonstrates how the source blend state is set to D3DBLEND_SRCCOLOR and the destination blend state is set to D3DBLEND_INVSRCCOLOR.

// This code example assumes that d3dDevice is a
// valid pointer to an IDirect3DDevice9 interface.

// Set the source blend state.
d3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCCOLOR);

// Set the destination blend state.

d3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCCOLOR);

Altering the source and destination blend states can give the appearance of emissive objects in a foggy or dusty atmosphere. For instance, if your application models flames, force fields, plasma beams, or similarly radiant objects in a foggy environment, set the source and destination blend states to D3DBLEND_ONE.

Another application of alpha blending is to control the lighting in a 3-D scene, also called light mapping. Setting the source blend state to D3DBLEND_ZERO and the destination blend state to D3DBLEND_SRCALPHA darkens a scene according to the source alpha information. The source primitive is used as a light map that scales the contents of the frame buffer to darken it when appropriate. This produces monochrome light mapping.

You can achieve color light mapping by setting the source alpha blending state to D3DBLEND_ZERO and the destination blend state to D3DBLEND_SRCCOLOR.


Alpha Testing State
Microsoft DirectX 9.0 SDK Update (October 2004)

Alpha Testing State

C++ applications can use alpha testing to control when pixels are written to the render-target surface. By using the D3DRS_ALPHATESTENABLE render state, your application sets the current Microsoft Direct3D device so that it tests each pixel according to an alpha test function. If the test succeeds, the pixel is written to the surface. If it does not, Direct3D ignores the pixel. Select the alpha test function with the D3DRS_ALPHAFUNC render state. Your application can set a reference alpha value for all pixels to compare against by using the D3DRS_ALPHAREF render state.

The most common use for alpha testing is to improve performance when rasterizing objects that are nearly transparent. If the color data being rasterized is more opaque than the color at a given pixel (D3DPCMPCAPS_GREATEREQUAL), then the pixel is written. Otherwise, the rasterizer ignores the pixel altogether, saving the processing required to blend the two colors. The following code example checks if a given comparison function is supported and, if so, it sets the comparison function parameters required to improve performance during rendering.

// This code example assumes that pCaps is a
// D3DCAPS9 structure that was filled with a
// previous call to IDirect3D9::GetDeviceCaps.

if (pCaps.AlphaCmpCaps & D3DPCMPCAPS_GREATEREQUAL)
{
    dev->SetRenderState(D3DRS_ALPHAREF, (DWORD)0x00000001);
    dev->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
    dev->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL);
}

// If the comparison is not supported, render anyway.
// The only drawback is no performance gain.

Not all hardware supports all alpha-testing features. You can check the device capabilities by calling the IDirect3D9::GetDeviceCaps method. After retrieving the device capabilities, check the associated D3DCAPS9 structure's AlphaCmpCaps member for the desired comparison function. If the AlphaCmpCaps member contains only the D3DPCMPCAPS_ALWAYS capability or only the D3DPCMPCAPS_NEVER capability, the driver does not support alpha tests.


Ambient Lighting State
Microsoft DirectX 9.0 SDK Update (October 2004)

Ambient Lighting State

Ambient light is surrounding light that radiates from all directions. For information about how Microsoft Direct3D uses ambient light, see Mathematics of Lighting.

A C++ application sets the color of ambient lighting by invoking the IDirect3DDevice9::SetRenderState method and passing the enumerated value D3DRS_AMBIENT as the first parameter. The second parameter is a color value. The default value is zero.

// This code example assumes that d3dDevice is a
// valid pointer to an IDirect3DDevice9 interface.

// Set the ambient light.

d3dDevice->SetRenderState(D3DRS_AMBIENT, 0x00202020);


Antialiasing State
Microsoft DirectX 9.0 SDK Update (October 2004)

Antialiasing State

Antialiasing is a method of making lines and edges appear smoother on the screen. By default, Microsoft Direct3D does not perform antialiasing. To enable full-scene antialiasing, set the D3DRS_MULTISAMPLEANTIALIAS render state to TRUE. To disable it, set D3DRS_MULTISAMPLEANTIALIAS to FALSE.


Culling State
Microsoft DirectX 9.0 SDK Update (October 2004)

Culling State

To improve rendering performance, you can cull out (or remove) a primitive that faces away from the camera. For single-sided primitives, this saves rendering time because a back-face is not visible. To enable culling, you need to know the winding order of the vertices (typically counter-clockwise). This example will remove any primitive whose back face is facing forward (given a counter-clockwise winding order):

SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);


Depth Buffering State
Microsoft DirectX 9.0 SDK Update (October 2004)

Depth Buffering State

Depth buffering is a method of removing hidden lines and surfaces. By default, Microsoft Direct3D does not use depth buffering.

For a conceptual overview of depth buffers, see Depth Buffers.

C++ applications update the depth-buffering state with the D3DRS_ZENABLE render state, using a member of the D3DZBUFFERTYPE enumeration to specify the new state value.

If your application needs to prevent Direct3D from writing to the depth buffer, it can use the D3DRS_ZWRITEENABLE enumerated value, specifying D3DZB_FALSE as the second parameter for the call to IDirect3DDevice9::SetRenderState.

The following code example shows how the depth-buffer state is set to enable z-buffering.

// This code example assumes that d3dDevice is a
// valid pointer to an IDirect3DDevice9 interface.
// Enable z-buffering.
d3dDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);

Your application can also use the D3DRS_ZFUNC render state to control the comparison function that Direct3D uses when performing depth buffering.

Z-biasing is a method of displaying one surface in front of another, even if their depth values are the same. You can use this technique for a variety of effects. A common example is rendering shadows on walls. Both the shadow and the wall have the same depth value. However, you want your application to show the shadow on the wall. Giving a z-bias to the shadow makes Direct3D display them properly (see D3DRS_DEPTHBIAS).


Fog State
Microsoft DirectX 9.0 SDK Update (October 2004)

Fog State

Fog effects can give a 3-D scene greater realism. You can use fog effects for more than simulating fog. They can also decrease the clarity of a scene with distance. This mirrors what happens in the real world; as objects become more distant from the user, their detail is less distinct.

For more information about using fog in your application, see Fog.

A C++ application controls fog through device rendering states. The D3DRENDERSTATETYPE enumerated type includes states to control whether pixel (table) or vertex fog is used, what color it is, the fog formula the system applies, and the parameters of the formula.

You enable fog by setting the D3DRS_FOGENABLE render state to TRUE. The fog color can be set to any color value by using the D3DRS_FOGCOLOR render state; the alpha component of the fog color is ignored.

The D3DRS_FOGTABLEMODE and D3DRS_FOGVERTEXMODE render states control the fog formula applied for fog calculations, and they indirectly control which type of fog is applied. Both render states can be set to a member of the D3DFOGMODE enumerated type. Setting either render state to D3DFOG_NONE disables pixel or vertex fog, respectively. If both render states are set to valid modes, the system applies only pixel fog effects.

The D3DRS_FOGSTART and D3DRS_FOGEND render states control fog formula parameters for the D3DFOG_LINEAR mode. The D3DRS_FOGDENSITY render state controls fog density in the exponential fog modes.

For more information, see Fog Parameters.


Lighting State
Microsoft DirectX 9.0 SDK Update (October 2004)

Lighting State

If you do not light with a vertex shader or a pixel shader, you may choose to use the lighting engine in the runtime. The lighting engine requires that the vertex data contains per-vertex normals; vertices without normal data will generate a dot product of zero in all lighting computations. The lighting calculations are covered in more detail in Mathematics of Lighting.

To enable the lighting engine, use:

SetRenderState(D3DRS_LIGHTING, TRUE);


Outline and Fill State
Microsoft DirectX 9.0 SDK Update (October 2004)

Outline and Fill State

Primitives that have no textures are rendered with the color specified by their material, or with the colors specified for the vertices, if any. You can select the method to fill them by specifying a value defined by the D3DFILLMODE enumerated type for the D3DRS_FILLMODE render state.

To enable dithering, your application must pass the D3DRS_DITHERENABLE enumerated value as the first parameter to IDirect3DDevice9::SetRenderState. It must set the second parameter to TRUE to enable dithering, and FALSE to disable it.

At times, drawing the last pixel in a line can cause unsightly overlap with surrounding primitives. You can control this using the D3DRS_LASTPIXEL enumerated value. However, do not alter this setting without some forethought. Under some conditions, suppressing the rendering of the last pixel can cause unsightly gaps between primitives.

Object outlines can be drawn by setting the appropriate line drawing pattern. The default line drawing state is to draw solid lines. For more information, see Line Drawing Support in D3DX render state.


Per-Vertex Color State
Microsoft DirectX 9.0 SDK Update (October 2004)

Per-Vertex Color State

The Microsoft Direct3D lighting engine can use per-vertex color data when performing lighting if you tell the runtime the data is present. This is done by turning on the following render state:

// disable per-vertex color
SetRenderState(D3DRS_COLORVERTEX, FALSE);

// enable per-vertex color
SetRenderState(D3DRS_COLORVERTEX, TRUE);

If per-vertex color is enabled, applications can configure the source from which the system retrieves color information for a vertex. The D3DRS_AMBIENTMATERIALSOURCE, D3DRS_DIFFUSEMATERIALSOURCE, D3DRS_EMISSIVEMATERIALSOURCE, and D3DRS_SPECULARMATERIALSOURCE render states control the ambient, diffuse, emissive, and specular color component sources, respectively. Each state can be set to members of the D3DMATERIALCOLORSOURCE enumerated type, which defines constants that instruct the system to use the current material, diffuse color, or specular color as the source for the specified color component.


Primitive Clipping State
Microsoft DirectX 9.0 SDK Update (October 2004)

Primitive Clipping State

Primitives that do not lie inside of nor intersect with the view frustum need to be clipped so that only the visible portion of the primitive will be rendered. Clipping reduces the amount of work that is done to only those primitives or portions of a primitive that will be visible.

To use the pipeline for clipping, set the D3DRS_CLIPPING render state to TRUE (the default value) to enable clipping, or to FALSE to disable Microsoft Direct3D clipping.


Shading State
Microsoft DirectX 9.0 SDK Update (October 2004)

Shading State

Microsoft Direct3D supports both flat and Gouraud shading. The default is Gouraud shading. To control the current shading mode, your C++ application specifies a member of the D3DSHADEMODE enumerated type for the D3DRS_SHADEMODE render state.

The following C++ code example demonstrates the process of setting the shading state to flat shading mode.

// This code example assumes that d3dDevice is a
// valid pointer to a IDirect3DDevice9 interface.
// Set the shading state.
d3dDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_FLAT);


Stencil Buffer State
Microsoft DirectX 9.0 SDK Update (October 2004)

Stencil Buffer State

Applications use the stencil buffer to determine whether a pixel is written to the rendering target surface. For details, see Stencil Buffer Techniques.

To enable stencil testing, use:

pDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);

To set the comparison function that the stencil testing uses to accept or reject pixels, use a member of D3DCMPFUNC like this:

pDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_EQUAL);

To set the reference value used in the comparison, use:

pDevice->SetRenderState(D3DRS_STENCILREF, 0);

By default, the stencil reference value is zero. Any integer value is valid.

To set the stencil mask, use:

pDevice->SetRenderState(D3DRS_STENCILMASK, 0);

Microsoft Direct3D performs a bitwise AND of the stencil reference value and a stencil mask value before the stencil test.

You can control what pixel information is output depending on the stencil comparison. For instance, to set what happens to stencil buffer data when the stencil test fails, use:

pDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_KEEP);

to keep the information in the stencil buffer unchanged if the stencil test fails. Use D3DRS_STENCILZFAIL instead, if you want to control the z-buffer if the z-buffer test fails.

You can write your own formula for the value you want written into the stencil buffer. For instance, you could use the write mask, the stencil-op, and the stencil buffer value as shown here:

NewStencilBufferValue = (StencilBufferValue & ~StencilWriteMask) |
                        (StencilWriteMask & StencilOp(StencilBufferValue))

Naturally, the stencil operation will depend on the render states that are set.

Lastly, use a write mask to control what is written to the stencil buffer like this:

pDevice->SetRenderState(D3DRS_STENCILWRITEMASK, D3DSTENCILOP_KEEP);


Texture Wrapping State
Microsoft DirectX 9.0 SDK Update (October 2004)

Texture Wrapping State

The D3DRS_WRAP0 thru D3DRS_WRAP7 render states enable and disable u- and v-wrapping for various textures in the device's multitexture cascade. You can set these render states to a combination of the D3DWRAPCOORD_0, D3DWRAPCOORD_1, D3DWRAPCOORD_2, and D3DWRAPCOORD_3 flags to enable wrapping in first, second, third, and fourth directions of the texture. Use a value of zero to disable wrapping altogether. Texture wrapping is disabled in all directions for all texture stages by default.

For a conceptual overview, see Texture Wrapping.


Direct3D Resources
Microsoft DirectX 9.0 SDK Update (October 2004)

Direct3D Resources

Resources are the textures and buffers that are used to render a scene. Applications need to create, load, copy, and use resources. This section gives a brief introduction to resources and the steps and methods used by applications when working with resources.

All resources, including the geometry resources IDirect3DIndexBuffer9 and IDirect3DVertexBuffer9, inherit from the IDirect3DResource9 interface. The texture resources, IDirect3DCubeTexture9, IDirect3DTexture9, and IDirect3DVolumeTexture9, also inherit from the IDirect3DBaseTexture9 interface.

  • Resource Properties
  • Manipulating Resources
  • Locking Resources
  • Resource Relationships
  • Managing Resources
  • Application-Managed Resources and Allocation Strategies
  • Index Buffers
  • Vertex Buffers


Resource Properties
Microsoft DirectX 9.0 SDK Update (October 2004)

Resource Properties

All resources share the following properties.

  • Usage. The way a resource is used, for example, as a texture or a render target.
  • Format. The format of the data, for example, the pixel format of a 2-D surface.
  • Pool. The type of memory where the resource is allocated.
  • Type. The type of resource, for example, a vertex buffer or render target.

Resource uses are enforced. An application that will use a resource in a certain operation must specify that operation at resource-creation time. For a list of the usage constants defined for resources, see D3DUSAGE.

The D3DUSAGE_RTPATCHES, D3DUSAGE_NPATCHES, and D3DUSAGE_POINTS constants indicate to the driver that the data in these buffers is likely to be used for triangular or grid patches, N-patches, or point sprites, respectively. These flags are provided in case the hardware cannot perform these operations without host processing. Therefore, the driver will want to allocate these surfaces in system memory so that the CPU can access them. If the driver can perform these operations entirely in hardware, it can allocate these surfaces in video or accelerated graphics port (AGP) memory to avoid a host copy and improve performance at least twofold. Note that the information provided by these flags is not absolutely required. A driver can detect that such operations are being performed on the data, and it will move the buffer back to system memory for subsequent frames.

For details about the usage flags and how they relate to specific resources, see the reference pages on the individual resource creation methods.

For information about the surface format of resources, see the D3DFORMAT enumerated type.

The class of memory that holds a resource's buffers is called a pool. Pool values are defined by the D3DPOOL enumerated type. A pool cannot be mixed for different objects contained in a single resource—that is, mip levels in a mipmap—and, when a pool is chosen for a resource, the pool cannot be changed.

The resources types are set implicitly at run time when the application calls a resource creation method such as IDirect3DDevice9::CreateCubeTexture. Resource types are defined by the D3DRESOURCETYPE enumerated type. Applications can query these types at run time; however, it is expected that most scenarios will not require run-time type checking.


Manipulating Resources
Microsoft DirectX 9.0 SDK Update (October 2004)

Manipulating Resources

Your application manipulates resources in order to render a scene. First, an application needs to create a texture resource with one of the following methods:

  • IDirect3DDevice9::CreateCubeTexture
  • IDirect3DDevice9::CreateTexture
  • IDirect3DDevice9::CreateVolumeTexture

A texture resource can instead be created with one of the D3DXCreatexxx texturing functions.

The texture objects returned by the texture creation methods are containers for surfaces or volumes; these containers are generically known as buffers. The buffers owned by the resource inherit the usages, format, and pool of the resource but have their own type. For more information, see Resource Properties.

The application gains access to the contained surfaces, for the purpose of loading artwork, by calling the following methods. For details, see Locking Resources.

  • IDirect3DCubeTexture9::LockRect
  • IDirect3DTexture9::LockRect
  • IDirect3DVolumeTexture9::LockBox

The lock methods take arguments denoting the contained surface—for example, the mipmap sub-level or cube face of the texture—and return pointers to the pixels. The typical application never uses a surface object directly.

Create geometry-oriented resources by calling IDirect3DDevice9::CreateIndexBuffer or IDirect3DDevice9::CreateVertexBuffer.

Lock and fill the buffer resources by calling either IDirect3DIndexBuffer9::Lock or IDirect3DVertexBuffer9::Lock, depending upon the resource.

For managed texture resources, the resource creation process ends here. For non-managed texture resources, an application promotes system memory resources to device-accessible resources (for hardware acceleration) by calling IDirect3DDevice9::UpdateTexture.

To present images rendered from resources, the application also needs color and depth-stencil buffers. For typical applications, the color buffer is owned by the device's swap chain, which is a collection of back-buffer surfaces, and is implicitly created with the device. Depth-stencil surfaces can be implicitly created, or explicitly created by using the IDirect3DDevice9::CreateDepthStencilSurface method. The application associates a device and its depth and color buffer with a call to IDirect3DDevice9::SetRenderTarget or IDirect3DDevice9::SetDepthStencilSurface.

For details on presenting the final image, see Presenting a Scene.


Locking Resources
Microsoft DirectX 9.0 SDK Update (October 2004)

Locking Resources

Locking a resource means granting CPU access to its storage. The following locking options are defined for resources:

  • D3DLOCK_DISCARD
  • D3DLOCK_READONLY
  • D3DLOCK_NOOVERWRITE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_NO_DIRTY_UPDATE

For details on locking flags and how they relate to specific resources, see the reference pages on the individual resource locking methods. Application developers should note that the D3DLOCK_DISCARD, D3DLOCK_READONLY, and D3DLOCK_NOOVERWRITE flags are only hints. The run time does not check that applications are following the functionality specified by these flags. An application that specifies D3DLOCK_READONLY but then writes to the resource should expect undefined results. In general, working against locking flags, including the locking usage flags, is not guaranteed to work in later releases and may incur a significant performance penalty.

A lock operation is followed by an unlock operation. For example, after locking a texture, the application subsequently relinquishes direct access to locked textures by unlocking them. In addition to granting processor access, any other operations involving that resource are serialized for the duration of a lock. Only a single lock for a resource is allowed, even for non-overlapping regions, and no accelerator operations on a surface can be ongoing while a lock operation is outstanding on that surface.

Each resource interface has methods for locking the contained buffers. Each texture resource can also lock a sub-portion of that resource. 2-D resources (surfaces) allow the locking of sub-rectangles, and volume resources allow the locking of sub-volumes or boxes. Each lock method returns a structure that contains a pointer to the storage backing the resource and values representing the distances between rows or planes of data, depending on the resource type. For details, see the method lists for the resource interfaces. The returned pointer always points to the top-left byte in the locked sub-regions.

When working with index and vertex buffers, you can make multiple lock calls; however, you must ensure that the number of lock calls matches the number of unlock calls.

The DXTn Compressed Texture Formats store pixels in encoded 4x4 blocks, and can only be locked on 4x4 boundaries.


Resource Relationships
Microsoft DirectX 9.0 SDK Update (October 2004)

Resource Relationships

The following diagram illustrates the operations that are syntactically possible on specific resources and their contents. For more information about how to use resources, see Manipulating Resources.

Arrows running from left to right indicate that the target types are created by the given methods, while arrows running from right to left indicate that those resource types can be passed as arguments to the given methods.


Managing Resources
Microsoft DirectX 9.0 SDK Update (October 2004)

Managing Resources

Resource management is the process where resources are promoted from system-memory storage to device-accessible storage and discarded from device-accessible storage. The Microsoft Direct3D run time has its own management algorithm based on a least-recently-used priority technique. Direct3D switches to a most-recently-used priority technique when it detects that more resources than can coexist in device-accessible memory are used in a single frame—between IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene calls.

Use the D3DPOOL_MANAGED flag at creation time to specify a managed resource. Managed resources persist through transitions between the lost and operational states of the device. The device can be restored with a call to IDirect3DDevice9::Reset, and such resources continue to function normally without being reloaded with artwork. However, if the device must be destroyed and re-created, all resources created using D3DPOOL_MANAGED must be re-created.

Use the D3DPOOL_DEFAULT flag at creation time to specify that a resource be placed in the default pool. Resources in the default pool do not persist through transitions between the lost and operational states of the device. These resources must be released before calling reset and must then be re-created.

For more information about the lost state of a device, see Lost Devices.

Note that resource management is not supported for all types and usages. For example, objects created with the D3DUSAGE_RENDERTARGET flag are not supported. In addition, resource management is not recommended for objects whose contents are changing with high frequency. For example, a managed vertex buffer that changes every frame can significantly degrade performance for some hardware. However, this is not a problem for texture resources.


Application-Managed Resources and Allocation Strategies
Microsoft DirectX 9.0 SDK Update (October 2004)

Application-Managed Resources and Allocation Strategies

Managed vertex-buffer or index-buffer resources cannot be declared dynamic by specifying D3DUSAGE_DYNAMIC at creation time. This would require an additional copy for every modification to the vertex buffer contents. Dynamic vertex buffers are intended for rendering dynamic geometry and data pulled in from binary space partitioned trees or other visibility data structures. This can be accomplished by pre-allocating buffers of the desired format. These resources are then parceled out to support application needs by a resource manager within the application. The total number of dynamic vertex buffers is small because an application will use simultaneously only a few different vertex strides and because a different vertex buffer is required only for unique strides. When managing dynamic resources in this way, ensure that high-frequency demands on the resources do not significantly decrease the application's performance.

When using resources managed by both Microsoft Direct3D and applications, allocate application-managed resources in D3DPOOL_DEFAULT memory prior to creating Direct3D-managed resources. This enables the memory manager to maintain an accurate count of available memory.


Vertex Buffers
Microsoft DirectX 9.0 SDK Update (October 2004)

Vertex Buffers

Vertex buffers, represented by the IDirect3DVertexBuffer9 interface, are memory buffers that contain vertex data. Vertex buffers can contain any vertex type - transformed or untransformed, lit or unlit - that can be rendered through the use of the rendering methods in the IDirect3DDevice9 interface. You can process the vertices in a vertex buffer to perform operations such as transformation, lighting, or generating clipping flags. Transformation is always performed.

The flexibility of vertex buffers make them ideal staging points for reusing transformed geometry. You could create a single vertex buffer, transform, light, and clip the vertices in it, and render the model in the scene as many times as needed without re-transforming it, even with interleaved render state changes. This is useful when rendering models that use multiple textures: the geometry is transformed only once, and then portions of it can be rendered as needed, interleaved with the required texture changes. Render state changes made after vertices are processed take effect the next time the vertices are processed.

  • Description
  • Memory Pool and Usage

Description

A vertex buffer is described in terms of its capabilities: if it can exist only in system memory, if it is only used for write operations, and the type and number of vertices it can contain. All these traits are held in a D3DVERTEXBUFFER_DESC structure.

The Format member is set to D3DFMT_VERTEXDATA to indicate that this is a vertex buffer. The Type identifies the resource type of the vertex buffer. The Usage structure member contains general capability flags. The D3DUSAGE_SOFTWAREPROCESSING flag indicates that the vertex buffer is to be used with software vertex processing. The presence of the D3DUSAGE_WRITEONLY flag in Usage indicates that the vertex buffer memory is used only for write operations. This frees the driver to place the vertex data in the best memory location to enable fast processing and rendering. If the D3DUSAGE_WRITEONLY flag is not used, the driver is less likely to put the data in a location that is inefficient for read operations. This sacrifices some processing and rendering speed. If this flag is not specified, it is assumed that applications perform read and write operations on the data within the vertex buffer.

Pool specifies the memory class that is allocated for the vertex buffer. The D3DPOOL_SYSTEMMEM flag indicates that the system created the vertex buffer in system memory.

The Size member stores the size, in bytes, of the vertex buffer data. The FVF member contains a combination of D3DFVF that identify the type of vertices that the buffer contains.

Memory Pool and Usage

You can create vertex buffers with the IDirect3DDevice9::CreateVertexBuffer method, which takes pool (memory class) and usage parameters. IDirect3DDevice9::CreateVertexBuffer can also be created with a specified flexible vertex format (FVF) code for use in fixed function vertex processing, or as the output of process vertices. For details, see FVF Vertex Buffers.

The D3DUSAGE_SOFTWAREPROCESSING flag can be set when mixed-mode or software vertex processing (D3DCREATE_MIXED_VERTEXPROCESSING / D3DCREATE_SOFTWARE_VERTEXPROCESSING) is enabled for that device. D3DUSAGE_SOFTWAREPROCESSING must be set for buffers to be used with software vertex processing in mixed mode, but it should not be set for the best possible performance when using hardware vertex processing in mixed mode.(D3DCREATE_HARDWARE_VERTEXPROCESSING). However, setting D3DUSAGE_SOFTWAREPROCESSING is the only option when a single buffer is to be used with both hardware and software vertex processing. D3DUSAGE_SOFTWAREPROCESSING is allowed for mixed as well as for software devices.

It is possible to force vertex and index buffers into system memory by specifying D3DPOOL_SYSTEMMEM, even when the vertex processing is done in hardware. This is a way to avoid overly large amounts of page-locked memory when a driver is putting these buffers into AGP memory.

This section introduces the concepts necessary to understand and use vertex buffers in a Microsoft Direct3D application. Information is divided into the following sections.

  • Creating a Vertex Buffer
  • Accessing the Contents of a Vertex Buffer
  • Rendering from a Vertex Buffer
  • FVF Vertex Buffers
  • Fixed Function Vertex Processing
  • Programmable Vertex Processing
  • Device Types and Vertex Processing Requirements


Creating a Vertex Buffer
Microsoft DirectX 9.0 SDK Update (October 2004)

Creating a Vertex Buffer

You create a vertex buffer object by calling the IDirect3DDevice9::CreateVertexBuffer method, which accepts five parameters. The first parameter specifies the vertex buffer length, in bytes. Use the sizeof operator to determine the size of a vertex format, in bytes. Consider the following custom vertex format.

struct CUSTOMVERTEX {
        FLOAT x, y, z;
        FLOAT rhw;
        DWORD color;
        FLOAT tu, tv;   // Texture coordinates
};

// Custom flexible vertex format (FVF) describing the custom vertex structure
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1)

To create a vertex buffer to hold four CUSTOMVERTEX structures, specify [4*sizeof(CUSTOMVERTEX)] for the Length parameter.

The second parameter is a set of usage controls. Among other things, its value determines whether the vertex buffer is capable of containing clipping information—in the form of clip flags—for vertices that exist outside the viewing area. To create a vertex buffer that cannot contain clip flags, include the D3DUSAGE_DONOTCLIP flag for the Usage parameter. The D3DUSAGE_DONOTCLIP flag is applied only if you also indicate that the vertex buffer will contain transformed vertices—the D3DFVF_XYZRHW flag is included in the FVF parameter. The IDirect3DDevice9::CreateVertexBuffer method ignores the D3DUSAGE_DONOTCLIP flag if you indicate that the buffer will contain untransformed vertices (the D3DFVF_XYZ flag). Clipping flags occupy additional memory, making a clipping-capable vertex buffer slightly larger than a vertex buffer incapable of containing clipping flags. Because these resources are allocated when the vertex buffer is created, you must request a clipping-capable vertex buffer ahead of time.

The third parameter, FVF, is a combination of D3DFVF that describe the vertex format of the vertex buffer. If you specify 0 for this parameter, then the vertex buffer is a non-FVF vertex buffer. For more information, see FVF Vertex Buffers. The fourth parameter describes the memory class into which to place the vertex buffer.

The final parameter that IDirect3DDevice9::CreateVertexBuffer accepts is the address of a variable that will be filled with a pointer to the new IDirect3DVertexBuffer9 interface of the vertex buffer object, if the call succeeds.

You cannot produce clip flags for a vertex buffer that was created without support for them.

The following C++ code example shows what creating a vertex buffer might look like in code.

// d3dDevice contains the address of an IDirect3DDevice9 interface
// g_pVB is a variable of type LPDIRECT3DVERTEXBUFFER9

// The custom vertex type
struct CUSTOMVERTEX {
        FLOAT x, y, z;
        FLOAT rhw;
        DWORD color;
        FLOAT tu, tv;   // The texture coordinates
};

#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1)

// Create a clipping-capable vertex buffer. Allocate enough memory
// in the default memory pool to hold three CUSTOMVERTEX
// structures

    if( FAILED( d3dDevice->CreateVertexBuffer( 3*sizeof(CUSTOMVERTEX),
        0 /*Usage*/, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL ) ) )
        return E_FAIL;


Accessing the Contents of a Vertex Buffer
Microsoft DirectX 9.0 SDK Update (October 2004)

Accessing the Contents of a Vertex Buffer

Vertex buffer objects enable applications to directly access the memory allocated for vertex data. You can retrieve a pointer to vertex buffer memory by calling the IDirect3DVertexBuffer9::Lock method, and then accessing the memory as needed to fill the buffer with new vertex data or to read any data it already contains. The IDirect3DVertexBuffer9::Lock method accepts four parameters. The first, OffsetToLock, is the offset into the vertex data. The second parameter is the size, measured in bytes, of the vertex data. The third parameter accepted is the address of a pointer that points to the vertex data, if the call succeeds.

The last parameter, Flags, tells the system how the memory should be locked. Specify constants for the Flags parameter according to the way the vertex data will be accessed. Make sure the value chosen for D3DUSAGE matches the value chosen for D3DLOCK. For example, if you are creating a vertex buffer with write access only, it doesn't make sense to try to read the data by specifying D3DLOCK_READONLY. Wisely using these flags allows the driver to lock the memory and provide the best performance, given the requested access type.

After you finish filling or reading the vertex data, call the IDirect3DVertexBuffer9::Unlock method, as shown in the following code example.

// This code example assumes the g_pVB is a variable of type
//   LPDIRECT3DVERTEXBUFFER9 and that g_Vertices has been
//   properly initialized with vertices

// Lock the buffer to gain access to the vertices
VOID* pVertices;

if(FAILED(g_pVB->Lock(0, sizeof(g_Vertices),
      (BYTE**)&pVertices, 0 ) ) )
    return E_FAIL;

memcpy(pVertices, g_Vertices, sizeof(g_Vertices));
g_pVB->Unlock();

If you create a vertex buffer with the D3DUSAGE_WRITEONLY flag, do not use the D3DLOCK_READONLY locking flag. Use the D3DLOCK_READONLY flag if your application will read only from the vertex buffer memory. Including this flag enables Microsoft Direct3D to optimize its internal procedures to improve efficiency, given that access to the memory will be read-only.

See Using Dynamic Vertex and Index Buffers for information about using D3DLOCK_DISCARD or D3DLOCK_NOOVERWRITE for the Flags parameter of IDirect3DVertexBuffer9::Lock.

In C++, because you directly access the memory allocated for the vertex buffer, make sure your application properly accesses the allocated memory. Otherwise, you risk rendering that memory invalid. Use the stride of the vertex format that your application uses to move from one vertex in the allocated buffer to another. The vertex buffer memory is a simple array of vertices specified in flexible vertex format (FVF). Use the stride of whatever vertex format structure you define. You can calculate the stride of each vertex at run time by examining the D3DFVF contained in the vertex buffer description. The following table shows the size for each vertex component.

Vertex Format Flag | Size
D3DFVF_DIFFUSE | sizeof(DWORD)
D3DFVF_NORMAL | sizeof(float) x 3
D3DFVF_SPECULAR | sizeof(DWORD)
D3DFVF_TEXn | sizeof(float) x n
D3DFVF_XYZ | sizeof(float) x 3
D3DFVF_XYZRHW | sizeof(float) x 4

The number of texture coordinates present in the vertex format is described by the D3DFVF_TEXn flags (where n is a value from 0 to 8). Multiply the number of texture coordinate sets by the size of one set of texture coordinates, which can range from one to four floats, to calculate the memory required for that number of texture coordinates.

Use the total vertex stride to increment and decrement the memory pointer as needed to access particular vertices.

Retrieving Vertex Buffer Descriptions

You can retrieve information about a vertex buffer by calling the IDirect3DVertexBuffer9::GetDesc method. This method fills the members of the D3DVERTEXBUFFER_DESC structure with information about the vertex buffer.


Rendering from a Vertex Buffer
Microsoft DirectX 9.0 SDK Update (October 2004)

Rendering from a Vertex Buffer

Rendering vertex data from a vertex buffer requires a few steps. First, you need to set the stream source by calling the IDirect3DDevice9::SetStreamSource method, as shown in the following example.

d3dDevice->SetStreamSource( 0, g_pVB, sizeof(CUSTOMVERTEX) );

The first parameter of IDirect3DDevice9::SetStreamSource tells Microsoft Direct3D the source of the device data stream. The second parameter is the vertex buffer to bind to the data stream. The third parameter is the size of the component, in bytes. In the sample code above, the size of a CUSTOMVERTEX is used for the size of the component.

The next step is to inform Direct3D which vertex shader to use by calling the IDirect3DDevice9::SetVertexShader method. The following sample code sets an flexible vertex format (FVF) code for the vertex shader. This informs Direct3D of the types of vertices it is dealing with.

d3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );

After setting the stream source and vertex shader, any draw methods will use the vertex buffer. The code example below shows how to render vertices from a vertex buffer with the IDirect3DDevice9::DrawPrimitive method.

d3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, 1 );

The second parameter that IDirect3DDevice9::DrawPrimitive accepts is the index of the first vector in the vertex buffer to load.


FVF Vertex Buffers
Microsoft DirectX 9.0 SDK Update (October 2004)

FVF Vertex Buffers

Setting the flexible vertex format (FVF) parameter of the IDirect3DDevice9::CreateVertexBuffer method to a nonzero value, which must be a valid FVF code, indicates that the buffer content is to be characterized by an FVF code. A vertex buffer that is created with an FVF code is referred to as an FVF vertex buffer. Some methods or uses of IDirect3DDevice9 require FVF vertex buffers, and others require non-FVF vertex buffers. FVF vertex buffers are required as the destination vertex buffer argument for IDirect3DDevice9::ProcessVertices.

FVF vertex buffers can be bound to a source data stream for any stream number.

The presence of the D3DFVF_XYZRHW component on FVF vertex buffers indicates that the vertices in that buffer have been processed. Vertex buffers used for IDirect3DDevice9::ProcessVertices destination vertex buffers must be post-processed. Vertex buffers used for fixed function shader inputs can be either preprocessed or postprocessed. If the vertex buffer is post-processed, then the shader is effectively bypassed and the data is passed directly to the primitive clipping and setup module.

FVF vertex buffers can be used with vertex shaders. Also, vertex streams can represent the same vertex formats that non-FVF vertex buffers can. They do not have to be used to input data from separate vertex buffers. The additional flexibility of the new vertex streams enables applications that need to keep their data separate to work better, but it is not required. If the application can maintain interleaved data in advance, then that is a performance boost. If the application will only interleave the data before every rendering call, then it should enable the application programming interface (API) or hardware to do this with multiple streams.

The most important things with vertex performance is to use a 32-byte vertex, and to maintain good cache ordering.


Fixed Function Vertex Processing
Microsoft DirectX 9.0 SDK Update (October 2004)

Fixed Function Vertex Processing

In the fixed function vertex pipeline, processing the vertices in a vertex buffer applies the current transformation matrices for the device. Vertex operations such as lighting, generating clip flags, and updating extents can also be applied, optionally. When using fixed function vertex processing, modifying the elements in the destination vertex buffer is controlled by the D3DPV_DONOTCOPYDATA flag. This flag applies only to fixed function vertex processing. The IDirect3DDevice9 interface exposes the IDirect3DDevice9::ProcessVertices method to process vertices. You process vertices from a vertex shader to the set of input data streams, generating a single stream of interleaved vertex data to the destination vertex buffer by calling the IDirect3DDevice9::ProcessVertices method. The method accepts five parameters that describe the location and quantity of vertices that the method targets, the destination vertex buffer, and the processing options. After the call, the destination buffer contains the processed vertex data.

The first, second, and third parameters, SrcStartIndex, DestIndex, and VertexCount, reflect the index of the first vertex to load, the index within the destination buffer at which the vertices will be placed, and the total number of vertices to process and place in the destination buffer, respectively. The fourth parameter, pDestBuffer should be set to the address of the IDirect3DVertexBuffer9 interface of the vertex buffer object that will receive the source vertices. The SrcStartIndex parameter specifies the index at which the method should start processing vertices.

The final parameter, Flags, determines special processing options for the method. You can set this parameter to 0 for default vertex processing, or to D3DPV_DONOTCOPYDATA to optimize processing in some situations. You can also combine the D3DPV_DONOTCOPYDATA value with one or more D3DLOCK values appropriate for the destination buffer. When you set Flags to 0, vertex components of the destination vertex buffer's vertex format that are not affected by the vertex operation are still copied from the vertex shader or set to 0. However, when using D3DPV_DONOTCOPYDATA, IDirect3DDevice9::ProcessVertices does not overwrite color and texture coordinate information in the destination buffer unless this data is generated by Microsoft Direct3D. Diffuse color is generated when lighting is enabled, that is, D3DRS_LIGHTING is set to TRUE. Specular color is generated when lighting is enabled and specular is enabled, that is, D3DRS_SPECULARENABLE and D3DRS_LIGHTING are set to TRUE. Specular color is also generated when fog is enabled. Texture coordinates are generated when texture transform or texture generation is enabled. IDirect3DDevice9::ProcessVertices uses the current render states to determine what vertex processing should be done.

FVF Usage Settings for Destination Vertex Buffers

The IDirect3DDevice9::ProcessVertices method requires specific settings for the D3DFVF of the destination vertex buffer. The flexible vertex format (FVF) usage settings must be compatible with the current settings for vertex processing.

For fixed function vertex processing, IDirect3DDevice9::ProcessVertices requires the following FVF settings:

  • Position type is always D3DFVF_XYZRHW; therefore, D3DFVF_XYZ and D3DFVF_XYZB1 through D3DFVF_XYZB5 are invalid.
  • The D3DFVF_NORMAL, D3DFVF_RESERVED0, and D3DFVF_RESERVED2 flags must not be set.
  • The D3DFVF_DIFFUSE flag must be set if an OR operation of the following conditions returns true:
    • Lighting is enabled; that is, D3DRS_LIGHTING is true.
    • Lighting is disabled, diffuse color is present in the input vertex streams, and D3DPV_DONOTCOPYDATA is not set.
  • The D3DFVF_SPECULAR flag must be set if an OR operation of the following conditions returns true:
    • Lighting is enabled and specular color is enabled; that is, D3DRS_SPECULARENABLE is true.
    • Lighting is disabled, specular color is present in the input vertex streams, and D3DPV_DONOTCOPYDATA is not set.
    • Vertex fog is enabled; that is, D3DRS_FOGVERTEXMODE is not set to D3DFOG_NONE.

In addition, the texture coordinate count must be set in the following manner:

  • If texture transform and texture generation are disabled for all active texture stages, and the D3DPV_DONOTCOPYDATA is not set, then the number and type of output texture coordinates are required to match those of the input vertex texture coordinates. If D3DPV_DONOTCOPYDATA is set and texture transform and texture generation are disabled, then the output texture coordinates are ignored.
  • If texture transform or texture generation is enabled for any active texture stages, the output vertex might need to contain more texture coordinate sets than the input vertex. This is due to the proliferation of texture coordinates from those being generated by texture generation or derived by texture transforms. Note that a similar proliferation of texture coordinates occurs during IDirect3DDevice9::DrawPrimitive calls, but is not visible to the application programmer. In this case, Direct3D generates a new set of texture coordinates. The new set of texture coordinates is derived by stepping through the texture stages and analyzing the settings for texture generation, texture transformation, and texture coordinate index to determine if a unique set of texture coordinates is required for that stage. Each time a new set is required it is allocated in increasing order. Note that the maximum, and typical, requirement is one set per stage, although it might be less due to sharing of nontransformed texture coordinates through D3DTSS_TEXCOORDINDEX.

Thus, for each texture stage, a new set of texture coordinates is generated if a texture is bound to that stage and any of the following conditions are true:

  • Texture generation is enabled for that stage.
  • Texture transformation is enabled for that stage.
  • Nontransformed input texture coordinates are referenced through D3DTSS_TEXCOORDINDEX for the first time.

When Direct3D is generating texture coordinates, the application is required to perform the following actions:

  1. Use a destination vertex buffer with the appropriate FVF usage.
  2. Reprogram the D3DTSS_TEXCOORDINDEX of the texture stage according to the placement of the postprocessed texture coordinates. Note that the reprogramming of the D3DTSS_TEXCOORDINDEX setting occurs when the processed vertex buffer is used in subsequent IDirect3DDevice9::DrawPrimitive and IDirect3DDevice9::DrawIndexedPrimitive calls.

Finally, texture coordinate dimensionality (D3DFVF_TEX0 through D3DFVF_TEX8) must be set in the following manner:

  • For each texture coordinate set, if texture transform and texture generation are disabled, then the output texture coordinate dimensionality must match the input. If the texture transform is enabled, then the output dimensionality must match the count defined by the D3DTTFF_COUNT1, D3DTTFF_COUNT2, D3DTTFF_COUNT3, or D3DTTFF_COUNT4 settings. If the texture transform is disabled and texture generation is enabled, then the output dimensionality must match the settings for the texture generation mode; currently all modes generate three float values.

When IDirect3DDevice9::ProcessVertices fails due to an incompatible destination vertex buffer FVF code, the expected code is printed to the debug output (debug builds only).


Programmable Vertex Processing
Microsoft DirectX 9.0 SDK Update (October 2004)

Programmable Vertex Processing

When using a programmed vertex shader, the elements updated in the destination vertex buffer are controlled by the shader function program. When the application writes to one of the destination vertex registers, the corresponding element within each vertex of the destination vertex buffer is updated. Elements in the destination vertex buffer that are not written to by the application are not modified. IDirect3DDevice9::ProcessVertices will fail if the application writes to elements that are not present in the destination vertex buffer.


Device Types and Vertex Processing Requirements
Microsoft DirectX 9.0 SDK Update (October 2004)

Device Types and Vertex Processing Requirements

The performance of vertex processing operations, including transformation and lighting, depends heavily on where the vertex buffer exists in memory and what type of rendering device is being used. Applications control the memory allocation for vertex buffers when they are created. When the D3DPOOL_SYSTEMMEM memory flag is set, the vertex buffer is created in system memory. When the D3DPOOL_DEFAULT memory flag is used, the device driver determines where the memory for the vertex buffer is best allocated, often referred to as driver-optimal memory. Driver-optimal memory can be local video memory, nonlocal video memory, or system memory.

Setting the D3DUSAGE_SOFTWAREPROCESSING constant with IDirect3DDevice9::CreateVertexBuffer enables software vertex processing on the vertex buffer data. This flag is required for software vertex processing while in mixed mode. The flag may not be used for hardware vertex processing mode. Vertex buffers used with software vertex processing include the following:

  • All input streams for IDirect3DDevice9::ProcessVertices.
  • All input streams for IDirect3DDevice9::DrawPrimitive and IDirect3DDevice9::DrawIndexedPrimitive.

The reasoning you use to determine the memory location - system or driver optimal - for vertex buffers is the same as that for textures. Vertex processing, including transformation and lighting, in hardware works best when the vertex buffers are allocated in driver-optimal memory, while software vertex processing works best with vertex buffers allocated in system memory. For textures, hardware rasterization works best when textures are allocated in driver-optimal memory, while software rasterization works best with system-memory textures.

Microsoft Direct3D for Microsoft DirectX 9.0 supports standalone processing of vertices, without rendering any primitive with the IDirect3DDevice9::ProcessVertices method. This standalone vertex processing is always performed in software on the host processor. Because of this, vertex buffers used as sources set with IDirect3DDevice9::SetStreamSource must be created with the D3DUSAGE_SOFTWAREPROCESSING flag. The functionality provided by IDirect3DDevice9::ProcessVertices is identical to that of the IDirect3DDevice9::DrawPrimitive and IDirect3DDevice9::DrawIndexedPrimitive methods while using software vertex processing.

If your application performs its own vertex processing and passes transformed, lit, and clipped vertices to rendering methods, then the application can directly write vertices to a vertex buffer allocated in driver-optimal memory. This technique prevents a redundant copy operation later. Note that this technique will not work well if your application reads data back from a vertex buffer, because read operations done by the host from driver-optimal memory can be very slow. Therefore, if your application needs to read during processing or writes data to the buffer erratically, a system-memory vertex buffer is a better choice.

When using the Direct3D vertex processing features (by passing untransformed vertices to vertex-buffer rendering methods), processing can occur in either hardware or software depending on the device type and device creation flags. It is recommended that vertex buffers be allocated in pool D3DPOOL_DEFAULT for best performance in virtually all cases. When a device is using hardware vertex processing, there are a number of additional optimizations that may be done based on the flags D3DUSAGE_DYNAMIC and D3DUSAGE_WRITEONLY. See IDirect3DDevice9::CreateVertexBuffer for more information about using these flags.


Vertex Declaration
Microsoft DirectX 9.0 SDK Update (October 2004)

Vertex Declaration

A vertex declaration defines the vertex buffer layout and programs the tessellation engine. Starting with Microsoft DirectX 9.0, vertex streams are expressed as an array of D3DVERTEXELEMENT9 structures (instead of using flexible vertex format (FVF) codes). Each array element describes each per-vertex data type. Converting FVF codes into the new format is covered in the following topics:

  • Mapping FVF Codes to a DirectX 9 Declaration
  • Fixed Function FVF Codes
  • Mapping between a DirectX 9 Declaration and FVF Codes
  • Mapping between a DirectX 9 Declaration and a DirectX 8 Declaration
  • Programming One or More Streams


Mapping FVF Codes to a DirectX 9 Declaration
Microsoft DirectX 9.0 SDK Update (October 2004)

Mapping FVF Codes to a DirectX 9 Declaration

This table maps flexible vertex format (FVF) codes to a D3DVERTEXELEMENT9 structure.

FVF | Data type | Usage | Usage index
D3DFVF_XYZ | D3DDECLTYPE_FLOAT3 | D3DDECLUSAGE_POSITION | 0
D3DFVF_XYZRHW | D3DDECLTYPE_FLOAT4 | D3DDECLUSAGE_POSITIONT | 0
D3DFVF_XYZW | D3DDECLTYPE_FLOAT4 | D3DDECLUSAGE_POSITION | 0
D3DFVF_XYZB5 and D3DFVF_LASTBETA_UBYTE4 | D3DVSDT_FLOAT3 D3DVSDT_FLOAT4 D3DVSDT_UBYTE4 | D3DDECLUSAGE_POSITION D3DDECLUSAGE_BLENDWEIGHT D3DDECLUSAGE_BLENDINDICES | 0
D3DFVF_XYZB5 and D3DFVF_LASTBETA_D3DCOLOR | D3DVSDT_FLOAT3 D3DVSDT_FLOAT4 D3DVSDT_D3DCOLOR | D3DDECLUSAGE_POSITION D3DDECLUSAGE_BLENDWEIGHT D3DDECLUSAGE_BLENDINDICES | 0
D3DFVF_XYZB5 | D3DDECLTYPE_FLOAT3 D3DDECLTYPE_FLOAT4 D3DDECLTYPE_FLOAT1 | D3DDECLUSAGE_POSITION D3DDECLUSAGE_BLENDWEIGHT D3DDECLUSAGE_BLENDINDICES | 0
D3DFVF_XYZBn (n=1..4) | D3DDECLTYPE_FLOAT3 D3DDECLTYPE_FLOATn | D3DDECLUSAGE_POSITION D3DDECLUSAGE_BLENDWEIGHT | 0
D3DFVF_XYZBn (n=1..4) and D3DFVF_LASTBETA_UBYTE4 | D3DDECLTYPE_FLOAT3 D3DDECLTYPE_FLOAT(n-1) D3DDECLTYPE_UBYTE4 | D3DDECLUSAGE_POSITION D3DDECLUSAGE_BLENDWEIGHT D3DDECLUSAGE_BLENDINDICES | 0
D3DFVF_XYZBn (n=1..4) and D3DFVF_LASTBETA_D3DCOLOR | D3DDECLTYPE_FLOAT3 D3DDECLTYPE_FLOAT(n-1) D3DDECLTYPE_D3DCOLOR | D3DDECLUSAGE_POSITION D3DDECLUSAGE_BLENDWEIGHT D3DDECLUSAGE_BLENDINDICES | 0
D3DFVF_NORMAL | D3DDECLTYPE_FLOAT3 | D3DDECLUSAGE_NORMAL | 0
D3DFVF_PSIZE | D3DDECLTYPE_FLOAT1 | D3DDECLUSAGE_PSIZE | 0
D3DFVF_DIFFUSE | D3DDECLTYPE_D3DCOLOR | D3DDECLUSAGE_COLOR | 0
D3DFVF_SPECULAR | D3DDECLTYPE_D3DCOLOR | D3DDECLUSAGE_COLOR | 1
D3DFVF_TEXCOORDSIZEm(n) | D3DDECLTYPE_FLOATm | D3DDECLUSAGE_TEXCOORD | n

Vertex Declarations with D3DDECLUSAGE_POSITIONT

The presence of a vertex element with (D3DUSAGE_POSITIONT, 0) is used to indicate to the device that the vertex data coming in has already been through vertex processing (like an FVF with D3DFVF_XYZRHW bit set). At draw time, if the currently set declaration has an element with the (D3DUSAGE_POSITIONT, 0) semantic, the entire vertex processing is skipped (just as if an FVF with D3DFVF_XYZRHW bit has been set).

There are some restrictions on vertex declarations with (D3DDECLUSAGE_POSITIONT, 0):

  • Only stream zero can be used in such declarations.
  • Vertex elements must be sorted by increasing stream offset.
  • The stream offset must be DWORD aligned.
  • The same (Usage, Usage Index) pair should be listed only once.
  • Only the D3DDECLMETHOD_DEFAULT method can be used.
  • Other vertex elements cannot have the (D3DDECLUSAGE_POSITION, 0) semantic.

In addition, there are some restrictions on such declaration related to the device driver version. These restrictions are in effect because Microsoft Direct3D sends such declarations directly to the driver without doing any conversion.

Vertex Declarations without D3DDECLUSAGE_POSITIONT

Runtime validates the creation of declarations. Following are the general rules for what declarations are legal.

  • All vertex elements for a stream must be consecutive and sorted by offset.
  • The stream offset must be DWORD aligned.
  • The same (Usage, Usage Index) pair should be listed only once.
  • If the D3DDEVCAPS2_VERTEXELEMENTSCANSHARESTREAMOFFSET is set then
    • Multiple vertex elements can share the same offset in a stream.
    • The vertex elements can all be of different types which can be of different sizes.
    • The vertex elements can overlap arbitrarily. For example, one element can start at a location of a stream that is, at the same time, in the middle of another element.
    • Vertex elements are allowed to have stream offset in any order.
  • The number of vertex elements cannot be greater than 64.
  • UsageIndex should be in the range [0-15].
  • Declaration, used with the DrawPrimitive application programming interface (API), should not have vertex elements other than D3DDECLMETHOD_DEFAULT, D3DDECLMETHOD_LOOKUPPRESAMPLED, or D3DDECLMETHOD_LOOKUP.
  • Declaration, which contains D3DDECLMETHOD_LOOKUP or LOOKUPPRESAMPLED, should be used only with the programmable vertex pipeline.
  • Declaration, used with the DrawRectPatch/DrawTriPatch API, cannot have vertex elements with D3DDECLMETHOD_LOOKUPPRESAMPLED or D3DDECLMETHOD_LOOKUP.
  • Declaration should have only one element with D3DDECLMETHOD_LOOKUP or D3DDECLMETHOD_LOOKUPPRESAMPLED method.
  • Declaration with D3DDECLMETHOD_LOOKUP or D3DDECLMETHOD_LOOKUPPRESAMPLED should not have elements other than D3DDECLMETHOD_DEFAULT, because displacement mapping is done only for N-patches.
  • Vertex elements with D3DDECLMETHOD_LOOKUP or D3DDECLMETHOD_LOOKUPPRESAMPLED can only be used with the (D3DDECLUSAGE_SAMPLE, n) semantic and vice versa.
  • If a vertex element with D3DDECLMETHOD_LOOKUP method has a stream index and offset of an already existing vertex element, this vertex element should have the same data type.
  • A vertex element with the D3DDECLMETHOD_LOOKUP method should have the D3DDECLTYPE_FLOAT2/3/4 data type
  • Vertex elements with types D3DDECLMETHOD_CROSSUV, D3DDECLMETHOD_PARTIALU, and D3DDECLMETHOD_PARTIALV should have an offset of a vertex element with a compatible data type.
  • A vertex element with the method D3DDECLMETHOD_UV or D3DDECLMETHOD_LOOKUPPRESAMPLED must have type D3DDECLTYPE_UNUSED, stream index zero, and stream offset zero.
  • Declarations with methods D3DDECLMETHOD_UV, D3DDECLMETHOD_PARTIALU, and D3DDECLMETHOD_PARTIALV can only be used with DrawRectPatch.
  • Usage D3DDECLUSAGE_TESSFACTOR should be used only with data type D3DDECLTYPE_FLOAT1 and usage index 0.
  • When a declaration is used for tessellation (DrawRectPatch, DrawTriPatch, N-patches), data type must be less than or equal to D3DDECLTYPE_SHORT4.
  • Declarations that contain methods requiring certain device capabilities (for example, displacement mapping, RT-patches) can only be created if the device supports them.
  • A vertex declaration used to draw points and lines cannot have methods other than D3DDECLMETHOD_DEFAULT.
  • The declarations that can be created also depends on the driver capabilities.

Driver Considerations

Pre-DirectX 9.0 Drivers

  • The input declaration must be translatable to a valid FVF (have the same order of vertex elements and their data types).
  • Gaps in texture coordinates are not allowed. This means that if there is a vertex element with (D3DDECLUSAGE_TEXCOORD, n) then there also should be a vertex element with (D3DDECLUSAGE_TEXCOORD, n-1).

DirectX 9.0 Drivers without Pixel Shader Version 3 Support

  • The input declaration must be translatable to a valid FVF (have the same order of vertex elements and their data types).
  • Gaps in texture coordinates are allowed.

DirectX 9.0 Drivers with Pixel Shader Version 3 Support

More general declarations are allowed.

  • Vertex elements can be in arbitrary order and can have any data types.
  • Multiple vertex elements can share the same stream offset and be of a different type in the same time if D3DDEVCAPS2_VERTEXELEMENTSCANSHARESTREAMOFFSET is set by device.

Vertex Declaration Usage with the Programmable Vertex Pipeline

  • At draw time, Direct3D looks for the same "usage - usage index" combination in the current vertex declaration and the current vertex shader function. When the combination is found, the register from shader function DCL is used as the destination for the vertex element.
  • When a vertex element in the current vertex declaration has a usage which is not found in the current vertex shader, that vertex element is ignored.
  • When using a vertex shaders version less than 2.0, all semantics mentioned in the shader code need to be present in the declaration bound at draw time. When using vertex shaders 2.0 and above, this restriction that allows applications to use different vertex declarations with the same vertex shader does not exist. This is useful when a vertex shader reads input data based on static conditions. Vertex shader registers not initialized because of this will have undefined values.

There are additional restrictions when using with hardware vertex processing on a Microsoft DirectX 8.x driver:

  • Vertex elements cannot overlap or share the same offset.
  • Data types are limited to what the DirectX 8.x driver can understand.

The CreateVertexDeclaration might fail if the declaration provided cannot be converted to a DirectX 8.x-style declaration. For a mixed mode device, this failure will happen at Draw* time because that is the only time it can be known whether this shader is being used with hardware or software vertex processing.

Vertex Declaration Usage with the Fixed Function Pipeline

Only declarations that adhere to the following rules can be used:

  • There should be no gaps between vertex elements (SKIP was not allowed in a DirectX 8.x declaration, which is used for the fixed function pipeline).
  • Semantic (D3DDECLUSAGE_POSITION, 0) must be specified and should have D3DDECLTYPE_FLOAT3 data type.
  • A vertex element with method D3DDECLMETHOD_UV must specify usage D3DDECLUSAGE_TEXCOORD or D3DDECLUSAGE_BLENDWEIGHT.
  • A vertex element with method D3DDECLMETHOD_PARTIALU, _PARTIALV, or _CROSSUV can only be used with D3DDECLUSAGE_POSITION, _NORMAL, _BLENDWEIGHT, or _TEXCOORD, and must use input type D3DDECLTYPE_FLOAT3.

When a declaration is used with hardware vertex processing on a DirectX 8.x driver, the Direct3D runtime converts it to a DirectX 8.x-style declaration with the following rules:

  • Vertex elements cannot share the same offset in a stream and they cannot overlap.
  • Data type must be less or equal D3DDECLTYPE_SHORT4.
  • Only the following methods are allowed: D3DDECLMETHOD_DEFAULT, D3DDECLMETHOD_CROSSUV, and D3DDECLMETHOD_UV
  • Mapping between a DirectX 9 Declaration and a DirectX 8 Declaration shows which DirectX 9.0 semantics could be converted to DirectX 8.x-style declaration. Usage and UsageIndex are converted to a register value.
  • If there are n vertex elements in a declaration and 0 - m (m < n) maps to an FVF (elements described in the Mapping between a DirectX 9 Declaration and FVF Codes), but m + 1 does not, then:
    • If any of m + 2 until n - 1 vertex elements map to FVF/dx8decl, the declaration is invalid.
    • The elements 0 to m are converted (by the runtime for DirectX 8.0 and older drivers, and by the DirectX 9.0 drivers) using the Mapping between a DirectX 9 Declaration and FVF Codes, m + 1, m + 2 until n - 1 become mapped to contiguous texcoord(k), texcoord(k+1), starting from any texcoord in elements 0 - m.
    • The data type at a mapped texcoord is assumed to be float[1234] replacing whatever data type the current element contains (but the same size). Therefore, the existing data type can be something that is not in Mapping between a DirectX 9 Declaration and FVF Codes.
    • If k reaches 8, the declaration is invalid for FVF/dx8decl.
    • If any mappings to texcoords have occurred, the entire declaration is required to have no elements with generation method other than DEFAULT or the declaration is invalid for FVF/dx8decl.

Using Vertex Declarations with ProcessVertices

A vertex declaration could be used to describe the output of ProcessVertices. Such declaration should adhere to the following rules:

  • Only stream 0 must be used.
  • Only D3DDECLMETHOD_DEFAULT methods are allowed.
  • Only D3DDECLTYPE_FLOATn or D3DDECLTYPE_D3DCOLOR data types can be used.
  • Vertex elements cannot share the same offset or overlap with each other.
  • Vertex elements with (D3DDECLUSAGE_POSITION, 0) or (D3DDECLUSAGE_POSITIONT,0) are not required.
  • Vertex elements with (D3DDECLUSAGE_POSITION, 0) and (D3DDECLUSAGE_POSITIONT,0) cannot be present in the same declaration.
  • The current vertex shader must be version 3.0 or higher when such declaration is used.


Fixed Function FVF Codes
Microsoft DirectX 9.0 SDK Update (October 2004)

Fixed Function FVF Codes

A flexible vertex format (FVF) code describes the contents of vertices stored interleaved in a single data stream. It generally specifies data to be processed by the fixed function vertex processing pipeline. This is an older-style vertex declaration; to see the current vertex declaration style, see D3DVERTEXELEMENT9.

Microsoft Direct3D applications can define model vertices in several different ways. Support for flexible vertex definitions, also known as flexible vertex formats or flexible vertex format codes, makes it possible for your application to use only the vertex components it needs, eliminating those components that aren't used. By using only the needed vertex components, your application can conserve memory and minimize the processing bandwidth required to render models. You describe how your vertices are formatted by using a combination of D3DFVF codes.

The FVF specification includes formats for point size, specified by D3DFVF_PSIZE. This size is expressed in camera space units for non-transformed and lit (TL) vertices, and in device-space units for TL vertices.

The rendering methods of the IDirect3DDevice9 interface provide C++ applications with methods that accept a combination of these flags, and use them to determine how to render primitives. Basically, these flags tell the system which vertex components—position, vertex blending weights, normal, colors, and the number and format of texture coordinates—your application uses and, indirectly, which parts of the rendering pipeline you want Direct3D to apply to them. In addition, the presence or absence of a particular vertex format flag communicates to the system which vertex component fields are present in memory and which you've omitted.

To determine device limitations, you can query a device for the values of D3DFVFCAPS_DONOTSTRIPELEMENTS and D3DFVFCAPS_TEXCOORDCOUNTMASK in the FVFCaps member of D3DCAPS9.

Texture coordinates can be declared in different formats, allowing textures to be addressed using as few as one coordinate or as many as four texture coordinates (for 2-D projected texture coordinates). For more information, see Texture Coordinate Formats. Use the D3DFVF_TEXCOORDSIZEn set of macros to create bit patterns that identify the texture coordinate formats that your vertex format uses.

No application will use every component. The reciprocal homogeneous W (RHW) and vertex normal fields are mutually exclusive. Nor will most applications try to use all eight sets of texture coordinates, but Direct3D has this capacity. There are several restrictions on which flags you can use with other flags. For example, you cannot use the D3DFVF_XYZ and D3DFVF_XYZRHW flags together, as this would indicate that your application is describing a vertex's position with both untransformed and transformed vertices.

To use indexed vertex blending, the D3DFVF_LASTBETA_UBYTE4 flag should appear at the end of the FVF declaration. The presence of this flag indicates that the fifth blending weight will be treated as a DWORD instead of float. For more information, see Indexed Vertex Blending.

The following code samples shows the difference between an FVF code that uses the D3DFVF_LASTBETA_UBYTE4 flag and one that doesn't. The flag D3DFVF_XYZB3 is present when four blending indices are used because you always subtract the sum of the first three from the number one to obtain the fourth (blend4 = 1 - (blend1 + blend2 + blend3)).

#define D3DFVF_BLENDVERTEX (D3DFVF_XYZB3|D3DFVF_NORMAL|D3DFVF_TEX1)

struct BLENDVERTEX
{
    D3DXVECTOR3 v;       // Referenced as v0 in the vertex shader
    FLOAT       blend1;  // Referenced as v1.x in the vertex shader
    FLOAT       blend2;  // Referenced as v1.y in the vertex shader
    FLOAT       blend3;  // Referenced as v1.z in the vertex shader
                         // v1.w = 1.0 - (v1.x + v1.y + v1.z)
    D3DXVECTOR3 n;       // Referenced as v3 in the vertex shader
    FLOAT       tu, tv;  // Referenced as v7 in the vertex shader
};

The FVF defined below uses the D3DFVF_LAST_UBYTE4 flag.

#define D3DFVF_BLENDVERTEX (D3DFVF_XYZB4 | D3DFVF_LASTBETA_UBYTE4 |D3DFVF_NORMAL|D3DFVF_TEX1)

struct BLENDVERTEX
{
    D3DXVECTOR3 v;       // Referenced as v0 in the vertex shader
    FLOAT       blend1;  // Referenced as v1.x in the vertex shader
    FLOAT       blend2;  // Referenced as v1.y in the vertex shader
    FLOAT       blend3;  // Referenced as v1.z in the vertex shader
                         // v1.w = 1.0 - (v1.x + v1.y + v1.z)
    DWORD       indices; // Referenced as v2.xyzw in the vertex shader
    D3DXVECTOR3 n;       // Referenced as v3 in the vertex shader
    FLOAT       tu, tv;  // Referenced as v7 in the vertex shader
};


Mapping between a DirectX 9 Declaration and a DirectX 8 Declaration
Microsoft DirectX 9.0 SDK Update (October 2004)

Mapping between a DirectX 9 Declaration and a DirectX 8 Declaration

This table maps members of a D3DVERTEXELEMENT9 declaration to a Microsoft DirectX 8.0 declaration.

DirectX 9.0 Usage | DirectX 9.0 Usage index | DirectX 8.0
D3DDECLUSAGE_POSITION | 0 | D3DVSDE_POSITION
D3DDECLUSAGE_POSITION | 1 | D3DVSDE_POSITION2
D3DDECLUSAGE_NORMAL | 0 | D3DVSDE_NORMAL
D3DDECLUSAGE_NORMAL | 1 | D3DVSDE_NORMAL2
D3DDECLUSAGE_BLENDWEIGHT | 0 | D3DVSDE_BLENDWEIGHT
D3DDECLUSAGE_BLENDINDICES | 0 | D3DVSDE_BLENDINDICES
D3DDECLUSAGE_PSIZE | 0 | D3DVSDE_PSIZE
D3DDECLUSAGE_COLOR | 0 | D3DVSDE_DIFFUSE
D3DDECLUSAGE_COLOR | 1 | D3DVSDE_SPECULAR
D3DDECLUSAGE_TEXCOORD | n | D3DVSDE_TEXCOORDn

When a declaration is used with hardware vertex processing on a DirectX 7.0 driver, the Microsoft Direct3D runtime converts it to a flexible vertex format (FVF) with the following rules:

  • Only stream 0 should be used (evident from the MaxStreams cap).
  • The order of vertex elements should be the same as order of FVF bits.
  • Gaps in texture coordinates are not allowed.
  • Any vertex element not described the table cannot be converted into a valid FVF for all pre-DirectX 8.0 drivers and, hence, cannot be used on those drivers.
  • Only D3DDECLTYPE_FLOAT2 is allowed for vertex elements with D3DDECLUSAGE_TEXCOORD if device does not set either of the D3DPTEXTURECAPS_PROJECTED or D3DPTEXTURECAPS_CUBEMAP caps.


Programming One or More Streams
Microsoft DirectX 9.0 SDK Update (October 2004)

Programming One or More Streams

This section describes shaders that can be used for the programmable stream model.

Using Streams

Microsoft DirectX 8.0 introduced the notion of a stream to bind data to input registers for use by shaders. A stream is a uniform array of component data, where each component consists of one or more elements that represent a single entity such as position, normal, color, and so on. Streams enable graphic chips to perform a direct memory access (DMA) from multiple vertex buffers in parallel and also provide a more natural mapping from application data. They also enable trivial multitexture versus multipass. Think of it like this:

  • A vertex is composed of n streams.
  • A stream is composed of m elements.
  • An element is [position, color, normal, texture coordinate].

The IDirect3DDevice9::SetStreamSource method binds a vertex buffer to a device data stream, creating an association between the vertex data and one of several data stream ports that feed the primitive processing functions. The actual references to the stream data do not occur until a drawing method, such as IDirect3DDevice9::DrawPrimitive, is called.

The mapping of the input vertex elements to the vertex input registers for programmable vertex shaders is defined in the shader declaration, but the input vertex elements do not have specific semantics about their use. The interpretation of the input vertex elements is programmed using the shader instructions. The vertex shader function is defined by an array of instructions that are applied to each vertex. The vertex output registers are explicitly written to, using instructions in the shader function.

For this discussion, though, be less concerned with the semantic mapping of elements to registers and more concerned with the reason for using streams and what problem is solved by using streams. The main benefit of streams is that they remove the vertex data costs previously associated with multitexturing. Before streams, a user had to either duplicate vertex data sets to handle the single and multitexture case with no unused data elements, or carry data elements that would be unused except in the multitexture case.

Here is an example of using two sets of vertex data, one for single texture and one for multitexturing.

struct CUSTOMVERTEX_TEX1
{
    FLOAT x, y, z;      // The untransformed position for the vertex
    DWORD diffColor;    // The vertex diffuse color
    DWORD specColor;    // The vertex specular color
    float tu_1, tv_1;   // Texture coordinates for a single texture
};

struct CUSTOMVERTEX_TEX2
{
    FLOAT x, y, z;      // The untransformed position for the vertex
    DWORD diffColor;    // The vertex diffuse color
    DWORD specColor;    // The vertex specular color
    float tu_2, tv_2;   // Texture coordinates for multitexturing
};

The alternative was to have a single vertex element that contained both sets of texture coordinates.

struct CUSTOMVERTEX_TEX2
{
    FLOAT x, y, z;      // The untransformed position for the vertex
    DWORD diffColor;    // The vertex diffuse color
    DWORD specColor;    // The vertex specular color
    float tu_1, tv_1;   // Texture coordinates for a single texture
    float tu_2, tv_2;   // Texture coordinates for multitexturing
};

With this vertex data, only one copy of the position and color data are carried in memory, at the expense of carrying both sets of texture coordinates around for rendering even in the single texture case.

Now that the tradeoff is clear, streams provide an elegant fix to this dilemma. Here is a set of vertex definitions to support three streams: one with position and color, one with the first set of texture coordinates, and one with the second set of texture coordinates.

// Multistream vertex
// Stream 0, pos, diffuse, specular
struct POSCOLORVERTEX
{
    FLOAT x, y, z;
    DWORD diffColor, specColor;
};
#define D3DFVF_POSCOLORVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_SPECULAR)

// Stream 1, tex coord 0
struct TEXC0VERTEX
{
    FLOAT tu1, tv1;
};
#define D3DFVF_TEXC0VERTEX (D3DFVF_TEX1)

// Stream 2, tex coord 1
struct TEXC1VERTEX
{
    FLOAT tu2, tv2;
};
#define D3DFVF_TEXC1VERTEX (D3DFVF_TEX0)

The vertex declaration would be as follows:

// Multitexture - multistream

D3DVERTEXELEMENT9 dwDecl3[] =
{
    {0, 0,  D3DDECLTYPE_FLOAT3,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_POSITION, 0},
    {0, 12, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_COLOR, 0},
    {0, 16, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_COLOR, 1},
    {1,  0, D3DDECLTYPE_FLOAT2,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_TEXCOORD, 0},
    {2,  0, D3DDECLTYPE_FLOAT2,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_TEXCOORD, 1},
    D3DDECL_END()
};

Now create the vertex declaration object and set it as shown:

LPDIRECT3DVERTEXDECLARATION9 m_pVertexDeclaration;
g_d3dDevice->CreateVertexDeclaration(dwDecl3, &m_pVertexDeclaration);

m_pd3dDevice->SetVertexDeclaration(m_pVertexDeclaration);

Examples of Combinations

One Stream Diffuse Color

The vertex declaration and stream settings for diffuse color rendering would look like this:

D3DVERTEXELEMENT9 dwDecl3[] =
{
    {0,  0,  D3DDECLTYPE_FLOAT3,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_POSITION, 0},
    {0, 12,  D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_COLOR, 0 ,
    {0, 16,  D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_COLOR, 1},
    D3DDECL_END()
};

   m_pd3dDevice->SetStreamSource(0, m_pVBVertexShader0, 0,
                                      sizeof(CUSTOMVERTEX));
   m_pd3dDevice->SetStreamSource(1, NULL, 0, 0);
   m_pd3dDevice->SetStreamSource(2, NULL, 0, 0);

Two Streams with Color and Texture

The vertex declaration and stream settings for single texture rendering would look like this:

D3DVERTEXELEMENT9 dwDecl3[] =
{
    {0, 0,  D3DDECLTYPE_FLOAT3,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_POSITION, 0},
    {0, 12, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_COLOR, 0},
    {0, 16, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_COLOR, 1},

    {1,  0, D3DDECLTYPE_FLOAT2,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_TEXCOORD, 0},

    D3DDECL_END()
};

   m_pd3dDevice->SetStreamSource(0, m_pVBPosColor, 0,
                                           sizeof(POSCOLORVERTEX));
   m_pd3dDevice->SetStreamSource(1, m_pVBTexC0, 0,
                                           sizeof(TEXC0VERTEX));
   m_pd3dDevice->SetStreamSource(2, NULL, 0, 0);

Two Streams with Color and two Textures

The vertex declaration and stream settings for two-texture multi-texture rendering would look like this:

D3DVERTEXELEMENT9 dwDecl3[] =
{
    {0, 0,  D3DDECLTYPE_FLOAT3,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_POSITION, 0},
    {0, 12, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_COLOR, 0},
    {0, 16, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_COLOR, 1},

    {1,  0, D3DDECLTYPE_FLOAT2,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_TEXCOORD, 0},

    {2,  0, D3DDECLTYPE_FLOAT2,   D3DDECLMETHOD_DEFAULT,
                                      D3DDECLUSAGE_TEXCOORD, 1},

    D3DDECL_END()
};

m_pd3dDevice->SetStreamSource(0, m_pVBPosColor, 0,
                                          sizeof(POSCOLORVERTEX));
m_pd3dDevice->SetStreamSource(1, m_pVBTexC0, 0,
                                          sizeof(TEXC0VERTEX));
m_pd3dDevice->SetStreamSource(2, m_pVBTexC1, 0,
                                          sizeof(TEXC1VERTEX));

In every case, the following IDirect3DDevice9::DrawPrimitive invocation suffices.

       m_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, NUM_TRIS);

This shows the flexibility of streams in solving the problem of data duplication/redundant data transmission across the bus (that is, of wasting bandwidth).


Index Buffers
Microsoft DirectX 9.0 SDK Update (October 2004)

Index Buffers

Index buffers, represented by the IDirect3DIndexBuffer9 interface, are memory buffers that contain index data. Index data, or indices, are integer offsets into vertex buffers and are used to render primitives using the IDirect3DDevice9::DrawIndexedPrimitive method.

A vertex buffer contains vertices; therefore, you can draw a vertex buffer either with or without indexed primitives. However, because an index buffer contains indices, you cannot use an index buffer without a corresponding vertex buffer. (As a side note, IDirect3DDevice9::DrawIndexedPrimitiveUP and IDirect3DDevice9::DrawPrimitiveUP are the only draw methods that draw without an index or a vertex buffer.)

An index buffer is described in terms of its capabilities: such as where it exists in memory, whether it supports reading and writing, and the type and number of indices it can contain. These traits are held in a D3DINDEXBUFFER_DESC structure.

Index buffer descriptions tell your application how an existing buffer was created. You provide an empty description structure for the system to fill with the capabilities of a previously created index buffer. For more information about this task, see Access the Contents of an Index Buffer.

The Format member describes the surface format of the index buffer data.

The Type identifies the resource type of the index buffer.

The Usage structure member contains general capability flags. The D3DUSAGE_SOFTWAREPROCESSING flag indicates that the index buffer is to be used with software vertex processing. The presence of the D3DUSAGE_WRITEONLY flag in Usage indicates that the index buffer memory is used only for write operations. This frees the driver to place the index data in the best memory location to enable fast processing and rendering. If the D3DUSAGE_WRITEONLY flag is not used, the driver is less likely to put the data in a location that is inefficient for read operations. This sacrifices some processing and rendering speed. If this flag is not specified, it is assumed that applications perform read and write operations on the data in the index buffer.

Pool specifies the memory class allocated for the index buffer. The D3DPOOL_SYSTEMMEM flag indicates that the system created the index buffer in system memory.

The Size member stores the size, in bytes, of the vertex buffer data.

Additional information is contained in the following topics:

  • Create an Index Buffer
  • Access the Contents of an Index Buffer
  • Render from an Index Buffer


Create an Index Buffer
Microsoft DirectX 9.0 SDK Update (October 2004)

Create an Index Buffer

Create an index buffer object by calling the IDirect3DDevice9::CreateIndexBuffer method, which accepts five parameters. The first parameter specifies the index buffer length, in bytes.

The second parameter is a set of usage controls. Among other things, its value determines whether the vertices being referred to by the indices are capable of containing clipping information. To improve performance, specify D3DUSAGE_DONOTCLIP when clipping is not required.

It is possible to force vertex and index buffers into system memory by specifying D3DPOOL_SYSTEMMEM, even when the index processing is being done in hardware. This is a way to avoid overly large amounts of page-locked memory when a driver is putting these buffers into AGP memory.

The third parameter is either the D3DFMT_INDEX16 or D3DFMT_INDEX32 member of the D3DFORMAT enumerated type that specifies the size of each index.

The fourth parameter is a member of the D3DPOOL enumerated type that tells the system where in memory to place the new index buffer.

The final parameter that IDirect3DDevice9::CreateIndexBuffer accepts is the address of a variable that is filled with a pointer to the new IDirect3DIndexBuffer9 interface of the vertex buffer object, if the call succeeds.

Index Processing Requirements

The performance of index processing operations depends heavily on where the index buffer exists in memory and what type of rendering device is being used. Applications control the memory allocation for index buffers when they are created. When the D3DPOOL_SYSTEMMEM memory flag is set, the index buffer is created in system memory. When the D3DPOOL_DEFAULT memory flag is used, the device driver determines where the memory for the index buffer is best allocated, often referred to as driver-optimal memory. Driver-optimal memory can be local video memory, nonlocal video memory, or system memory.

Setting the D3DUSAGE_SOFTWAREPROCESSING behavior flag when calling the IDirect3DDevice9::CreateIndexBuffer method specifies that the index buffer is to be used with software vertex processing. This flag is required in mixed mode vertex processing (D3DCREATE_MIXED_VERTEXPROCESSING) when software vertex processing is used.

The application can directly write indices to a index buffer allocated in driver-optimal memory. This technique prevents a redundant copy operation later. This technique does not work well if your application reads data back from an index buffer, because read operations done by the host from driver-optimal memory can be very slow. Therefore, if your application needs to read during processing or writes data to the buffer erratically, a system-memory index buffer is a better choice.

Note Always use D3DPOOL_DEFAULT, except when you don't want to expend video memory or expand large amounts of page-locked RAM when the driver is putting vertex or index buffers into AGP memory.


Access the Contents of an Index Buffer
Microsoft DirectX 9.0 SDK Update (October 2004)

Access the Contents of an Index Buffer

Index buffer objects enable applications to directly access the memory allocated for index data. You can retrieve a pointer to index buffer memory by calling the IDirect3DIndexBuffer9::Lock method, and then accessing the memory as needed to fill the buffer with new index data or to read any data it contains. The Lock method accepts four parameters. The first, OffsetToLock, is the offset into the index data. The second parameter is the size, measured in bytes, of the index data. The third parameter accepted by the IDirect3DIndexBuffer9::Lock method, ppbData, is the address of a BYTE pointer filled with a pointer to the index data, if the call succeeds.

The last parameter, Flags, tells the system how the memory should be locked. You can use it to indicate how the application accesses the data in the buffer. Specify constants for the Flags parameter according to the way the index data will be accessed by your application. This allows the driver to lock the memory and provide the best performance given the requested access type. Use D3DLOCK_READONLY flag if your application will read only from the index buffer memory. Including this flag enables Microsoft Direct3D to optimize its internal procedures to improve efficiency, given that access to the memory will be read-only.

After you fill or read the index data, call the IDirect3DIndexBuffer9::Unlock method, as shown in the following code example.

// This code example assumes the m_pIndexBuffer is a variable of type
// LPDIRECT3DINDEXBUFFER9 and that g_Indices has been properly
// initialized with indices.

// To fill the index buffer, you must lock the buffer to gain
// access to the indices. This mechanism is required because index
// buffers may be in device memory.

VOID* pIndices;

if( FAILED( m_pIndexBuffer->Lock(
      0,                 // Fill from start of the buffer
      sizeof(g_Indices), // Size of the data to load
      BYTE**)&pIndices,  // Returned index data
      0 ) ) )            // Send default flags to the lock
{
    SAFE_RELEASE(m_pIndexBuffer);
    return E_FAIL;
}

memcpy( pIndices, g_Indices, sizeof(g_Indices) );
m_pIndexBuffer->Unlock();
Note

If you create an index buffer with the D3DUSAGE_WRITEONLY flag, do not use the D3DLOCK_READONLY locking flag. Use the D3DLOCK_READONLY flag if your application will read only from the index buffer memory. Including this flag enables Direct3D to optimize its internal procedures to improve efficiency, given that access to the memory will be read-only.

For information about using D3DLOCK_DISCARD or D3DLOCK_NOOVERWRITE for the Flags parameter of the IDirect3DIndexBuffer9::Lock method, see Using Dynamic Vertex and Index Buffers.

In C++, because you directly access the memory allocated for the index buffer, make sure your application properly accesses the allocated memory. Otherwise, you risk rendering that memory invalid. Use the stride of the index format your application uses to move from one index in the allocated buffer to another.

Retrieving Index Buffer Descriptions

Retrieve information about an index buffer by calling the IDirect3DIndexBuffer9::GetDesc method. This method fills the members of the D3DINDEXBUFFER_DESC structure with information about the vertex buffer.


Render from an Index Buffer
Microsoft DirectX 9.0 SDK Update (October 2004)

Render from an Index Buffer

Rendering index data from an index buffer requires a few steps. First, you need to set the stream source by calling the IDirect3DDevice9::SetStreamSource method.

d3dDevice->SetStreamSource(0, VB, 0, sizeof(CUSTOMVERTEX));

The first parameter of SetStreamSource tells Microsoft Direct3D the source of the device data stream. The second parameter is the vertex buffer to bind to the data stream. The third parameter is the size of the component, in bytes. In the sample code above, the size of a CUSTOMVERTEX is used for the size of the component.

The next step is to call the IDirect3DDevice9::SetIndices method to set the source of the index data.

d3dDevice->SetIndices(IB);

IDirect3DDevice9::SetIndices accepts a parameter that is the address of the index buffer to set.

After setting the stream source and the indices, use IDirect3DDevice9::DrawIndexedPrimitive to render vertices that use indices from the index buffer.

d3dDevice->DrawIndexedPrimitive(
    D3DPT_TRIANGLELIST,
    0,            // offset to the first vertex index in the vertex buffer
    dwVertices,   // number of indices
    0,            // offset to the first index in the index buffer
    dwIndices / 3 // number of primitives to render
);

The code sample uses triangles; therefore, the number of primitives to render is the number of indices divided by three.

For more examples of rendering from a vertex buffer or an index buffer, see Rendering from Vertex and Index Buffers.


3-D Coordinate Systems and Geometry
Microsoft DirectX 9.0 SDK Update (October 2004)

3-D Coordinate Systems and Geometry

Programming Microsoft Direct3D applications requires a working familiarity with 3-D geometric principles. This section introduces the most important geometric concepts for creating 3-D scenes. The following topics are covered.

  • 3-D Coordinate Systems
  • 3-D Primitives
  • Face and Vertex Normal Vectors
  • Triangle Rasterization Rules
  • Rectangles
  • Triangle Interpolation
  • Vectors, Vertices, and Quaternions

These topics provide high-level descriptions of the basic concepts employed by a Direct3D application. For more information about these topics, see Further Information.


3-D Coordinate Systems
Microsoft DirectX 9.0 SDK Update (October 2004)

3-D Coordinate Systems

Typically 3-D graphics applications use two types of Cartesian coordinate systems: left-handed and right-handed. In both coordinate systems, the positive x-axis points to the right, and the positive y-axis points up. You can remember which direction the positive z-axis points by pointing the fingers of either your left or right hand in the positive x-direction and curling them into the positive y-direction. The direction your thumb points, either toward or away from you, is the direction that the positive z-axis points for that coordinate system. The following illustration shows these two coordinate systems.

Two coordinate systems

Microsoft Direct3D uses a left-handed coordinate system. If you are porting an application that is based on a right-handed coordinate system, you must make two changes to the data passed to Direct3D.

  • Flip the order of triangle vertices so that the system traverses them clockwise from the front. In other words, if the vertices are v0, v1, v2, pass them to Direct3D as v0, v2, v1.
  • Use the view matrix to scale world space by -1 in the z-direction. To do this, flip the sign of the _31, _32, _33, and _34 member of the D3DMATRIX structure that you use for your view matrix.

To obtain what amounts to a right-handed world, use the D3DXMatrixPerspectiveRH and D3DXMatrixOrthoRH functions to define the projection transform. However, be careful to use the corresponding D3DXMatrixLookAtRH function, reverse the backface-culling order, and lay out the cube maps accordingly.

Although left-handed and right-handed coordinates are the most common systems, there is a variety of other coordinate systems used in 3-D software. For example, it is not unusual for 3-D modeling applications to use a coordinate system in which the y-axis points toward or away from the viewer, and the z-axis points up. In this case, right-handedness is defined as any positive axis (x, y, or z) pointing toward the viewer. Left-handedness is defined as any positive axis (x, y, or z) pointing away from the viewer. If you are porting a left-handed modeling application where the z-axis points up, you must do a rotation on all the vertex data in addition to the previous steps.

The essential operations performed on objects defined in a 3-D coordinate system are translation, rotation, and scaling. You can combine these basic transformations to create a transform matrix. For details, see Transforms.

When you combine these operations, the results are not commutative; the order in which you multiply matrices is important.


3-D Primitives
Microsoft DirectX 9.0 SDK Update (October 2004)

3-D Primitives

A 3-D primitive is a collection of vertices that form a single 3-D entity. The simplest primitive is a collection of points in a 3-D coordinate system, which is called a point list.

Often, 3-D primitives are polygons. A polygon is a closed 3-D figure delineated by at least three vertices. The simplest polygon is a triangle. Microsoft Direct3D uses triangles to compose most of its polygons because all three vertices in a triangle are guaranteed to be coplanar. Rendering nonplanar vertices is inefficient. You can combine triangles to form large, complex polygons and meshes.

The following illustration shows a cube. Two triangles form each face of the cube. The entire set of triangles forms one cubic primitive. You can apply textures and materials to the surfaces of primitives to make them appear to be a single solid form. For details, see Materials and Direct3D Textures.

You can also use triangles to create primitives whose surfaces appear to be smooth curves. The following illustration shows how a sphere can be simulated with triangles. After a material is applied, the sphere looks curved when it is rendered. This is especially true if you use Gouraud shading. For details, see Gouraud Shading.

Related Topics

  • Primitives


Face and Vertex Normal Vectors
Microsoft DirectX 9.0 SDK Update (October 2004)

Face and Vertex Normal Vectors

Each face in a mesh has a perpendicular normal vector. The vector's direction is determined by the order in which the vertices are defined and by whether the coordinate system is right- or left-handed. The face normal points away from the front side of the face. In Microsoft Direct3D, only the front of a face is visible. A front face is one in which vertices are defined in clockwise order.

Any face that is not a front face is a back face. Direct3D does not always render back faces; therefore, back faces are said to be culled. You can change the culling mode to render back faces if you want. See Culling State for more information.

Direct3D uses the vertex normals for Gouraud shading, lighting, and texturing effects.

When applying Gouraud shading to a polygon, Direct3D uses the vertex normals to calculate the angle between the light source and the surface. It calculates the color and intensity values for the vertices and interpolates them for every point across all the primitive's surfaces. Direct3D calculates the light intensity value by using the angle. The greater the angle, the less light is shining on the surface.

If you are creating an object that is flat, set the vertex normals to point perpendicular to the surface, as shown in the following illustration. A flat surface composed of two triangles is defined.

It is more likely, however, that your object is made up of triangle strips and the triangles are not coplanar. One simple way to achieve smooth shading across all the triangles in the strip is to first calculate the surface normal vector for each polygonal face with which the vertex is associated. The vertex normal can be set to make an equal angle with each surface normal. However, this method might not be efficient enough for complex primitives.

This method is illustrated by the following figure, which shows two surfaces, S1 and S2 seen edge-on from above. The normal vectors for S1 and S2 are shown in blue. The vertex normal vector is shown in red. The angle that the vertex normal vector makes with the surface normal of S1 is the same as the angle between the vertex normal and the surface normal of S2. When these two surfaces are lit and shaded with Gouraud shading, the result is a smoothly shaded, smoothly rounded edge between them.

If the vertex normal leans toward one of the faces with which it is associated, it causes the light intensity to increase or decrease for points on that surface, depending on the angle it makes with the light source. An example is shown in the following figure. Again, these surfaces are seen edge-on. The vertex normal leans toward S1, causing it to have a smaller angle with the light source than if the vertex normal had equal angles with the surface normals.

You can use Gouraud shading to display some objects in a 3-D scene with sharp edges. To do so, duplicate the vertex normal vectors at any intersection of faces where a sharp edge is required, as shown in the following illustration.

If you use the DrawPrimitive methods to render your scene, define the object with sharp edges as a triangle list, rather than a triangle strip. When you define an object as a triangle strip, Direct3D treats it as a single polygon composed of multiple triangular faces. Gouraud shading is applied both across each face of the polygon and between adjacent faces. The result is an object that is smoothly shaded from face to face. Because a triangle list is a polygon composed of a series of disjoint triangular faces, Direct3D applies Gouraud shading across each face of the polygon. However, it is not applied from face to face. If two or more triangles of a triangle list are adjacent, they appear to have a sharp edge between them.

Another alternative is to change to flat shading when rendering objects with sharp edges. This is computationally the most efficient method, but it may result in objects in the scene that are not rendered as realistically as the objects that are Gouraud-shaded.


Rasterization Rules
Microsoft DirectX 9.0 SDK Update (October 2004)

Rasterization Rules

Often, the points specified for vertices do not precisely match the pixels on the screen. When this happens, Microsoft Direct3D applies triangle rasterization rules to decide which pixels apply to a given triangle.

  • Triangle Rasterization Rules
  • Point and Line Rules
  • Point Sprite Rules

Triangle Rasterization Rules

Direct3D uses a top-left filling convention for filling geometry. This is the same convention that is used for rectangles in Microsoft Windows Graphics Device Interface (GDI) and OpenGL. In Direct3D, the center of the pixel is the decisive point. If the center is inside a triangle, the pixel is part of the triangle. Pixel centers are at integer coordinates.

This description of triangle-rasterization rules used by Direct3D does not necessarily apply to all available hardware. Your testing may uncover minor variations in the implementation of these rules.

The following illustration shows a rectangle whose upper-left corner is at (0, 0) and whose lower-right corner is at (5, 5). This rectangle fills 25 pixels, just as you would expect. The width of the rectangle is defined as right minus left. The height is defined as bottom minus top.

Numbered square divided into six rows and columns

In the top-left filling convention, top refers to the vertical location of horizontal spans, and left refers to the horizontal location of pixels within a span. An edge cannot be a top edge unless it is horizontal. In general, most triangles have only left and right edges.

Numbered square containing two triangles

The top-left filling convention determines the action taken by Direct3D when a triangle passes through the center of a pixel. The following illustration shows two triangles, one at (0, 0), (5, 0), and (5, 5), and the other at (0, 5), (0, 0), and (5, 5). The first triangle in this case gets 15 pixels (shown in black), whereas the second gets only 10 pixels (shown in gray) because the shared edge is the left edge of the first triangle.

Numbered square containing diagonal line

If you define a rectangle with its upper-left corner at (0.5, 0.5) and its lower-right corner at (2.5, 4.5), the center point of this rectangle is at (1.5, 2.5). When the Direct3D rasterizer tessellates this rectangle, the center of each pixel is unambiguously inside each of the four triangles, and the top-left filling convention is not needed. The following illustration shows this. The pixels in the rectangle are labeled according to the triangle in which Direct3D includes them.

Numbered square containing rectangle divided into four triangles

If you move the rectangle in the previous example so that its upper-left corner is at (1.0, 1.0), its lower-right corner at (3.0, 5.0), and its center point at (2.0, 3.0), Direct3D applies the top-left filling convention. Most pixels in this rectangle straddle the border between two or more triangles, as the next illustration shows.

Numbered square containing rectangle divided into four triangles

For both rectangles, the same pixels are affected.

Numbered square containing rectangle divided into four triangles

Point and Line Rules

Points are rendered the same as point sprites, which are both rendered as screen-aligned quadrilaterals and thus adhere to the same rules as polygon rendering.

Non-antialiased line rendering rules are exactly the same as those for GDI.

For information about antialiased line rendering, see ID3DXLine.

Point Sprite Rules

Point sprites and patch primitives are rasterized as if the primitives were first tessellated into triangles and the resulting triangles rasterized. For more information, see Point Sprites.


Rectangles
Microsoft DirectX 9.0 SDK Update (October 2004)

Rectangles

Throughout Microsoft Direct3D and Microsoft Windows programming, objects on the screen are referred to in terms of bounding rectangles. The sides of a bounding rectangle are always parallel to the sides of the screen, so the rectangle can be described by two points, the upper-left corner and lower-right corner. Most applications use the RECT World Wide Web link structure to carry information about a bounding rectangle to use when blitting to the screen or performing hit detection.

In C++, the RECT structure has the following definition.

typedef struct tagRECT {
    LONG    left;    // This is the upper-left corner x-coordinate.
    LONG    top;     // The upper-left corner y-coordinate.
    LONG    right;   // The lower-right corner x-coordinate.
    LONG    bottom;  // The lower-right corner y-coordinate.
} RECT, *PRECT, NEAR *NPRECT, FAR *LPRECT;

In the preceding example, the left and top members are the x- and y-coordinates of a bounding rectangle's upper-left corner. Similarly, the right and bottom members make up the coordinates of the lower-right corner. The following diagram illustrates how you can visualize these values.

The column of pixels at the right edge and the row of pixels at the bottom edge are not included in the RECT object. For example, locking a RECT with members {10, 10, 138, 138} results in an object 128 pixels in width and height.

In the interest of efficiency, consistency, and ease of use, all Direct3D presentation functions work with rectangles.


Triangle Interpolation
Microsoft DirectX 9.0 SDK Update (October 2004)

Triangle Interpolation

During rendering, the pipeline interpolates vertex data across each triangle. Vertex data can be a broad variety of data and can include (but is not limited to): diffuse color, specular color, diffuse alpha (triangle opacity), specular alpha, and a fog factor (taken from specular alpha for fixed function vertex pipeline and from fog register for programmable vertex pipeline). The vertex data is defined by the Vertex Declaration.

For some vertex data, the interpolation is dependent on the current shading mode, as shown in the following table.

Shading mode | Description
Flat | Only the fog factor is interpolated in flat shade mode. For all other interpolated values, the color of the first vertex in the triangle is applied across the entire face.
Gouraud | Linear interpolation is performed between all three vertices.

The diffuse color and specular color are treated differently, depending on the color model. In the RGB color model, the system uses the red, green, and blue color components in the interpolation.

The alpha component of a color is treated as a separate interpolated value because device drivers can implement transparency in two different ways: by using texture blending or by using stippling.

Use the ShadeCaps member of the D3DCAPS9 structure to determine what forms of interpolation the current device driver supports.


Vectors, Vertices, and Quaternions
Microsoft DirectX 9.0 SDK Update (October 2004)

Vectors, Vertices, and Quaternions

Throughout Microsoft Direct3D, vertices describe position and orientation. Each vertex in a primitive is described by a vector that gives its position, color, texture coordinates, and a normal vector that gives its orientation.

Quaternions add a fourth element to the [x, y, z] values that define a three-component-vector. Quaternions are an alternative to the matrix methods that are typically used for 3-D rotations. A quaternion represents an axis in 3-D space and a rotation around that axis. For example, a quaternion might represent a (1,1,2) axis and a rotation of 1 radian. Quaternions carry valuable information, but their true power comes from the two operations that you can perform on them: composition and interpolation.

Performing composition on quaternions is similar to combining them. The composition of two quaternions is notated as follows:

The composition of two quaternions applied to a geometry means "rotate the geometry around axis2 by rotation2, then rotate it around axis1 by rotation1." In this case, Q represents a rotation around a single axis that is the result of applying q2, then q1 to the geometry.

Using quaternion interpolation, an application can calculate a smooth and reasonable path from one axis and orientation to another. Therefore, interpolation between q1 and q2 provides a simple way to animate from one orientation to another.

When you use composition and interpolation together, they provide you with a simple way to manipulate a geometry in a manner that appears complex. For example, imagine that you have a geometry that you want to rotate to a given orientation. You know that you want to rotate it r2 degrees around axis2, then rotate it r1 degrees around axis1, but you don't know the final quaternion. By using composition, you could combine the two rotations on the geometry to get a single quaternion that is the result. Then, you could interpolate from the original to the composed quaternion to achieve a smooth transition from one to the other.

The D3DX utility library includes functions that help you work with quaternions. For example, the D3DXQuaternionRotationAxis function adds a rotation value to a vector that defines an axis of rotation, and returns the result in a quaternion defined by a D3DXQUATERNION structure. Additionally, the D3DXQuaternionMultiply function composes quaternions and the D3DXQuaternionSlerp performs spherical linear interpolation between two quaternions.

Direct3D applications can use the following functions to simplify the task of working with quaternions.

  • D3DXQuaternionBaryCentric
  • D3DXQuaternionConjugate
  • D3DXQuaternionDot
  • D3DXQuaternionExp
  • D3DXQuaternionIdentity
  • D3DXQuaternionInverse
  • D3DXQuaternionIsIdentity
  • D3DXQuaternionLength
  • D3DXQuaternionLengthSq
  • D3DXQuaternionLn
  • D3DXQuaternionMultiply
  • D3DXQuaternionNormalize
  • D3DXQuaternionRotationAxis
  • D3DXQuaternionRotationMatrix
  • D3DXQuaternionRotationYawPitchRoll
  • D3DXQuaternionSlerp
  • D3DXQuaternionSquad
  • D3DXQuaternionToAxisAngle

Direct3D applications can use the following functions to simplify the task of working with three-component-vectors.

  • D3DXVec3Add
  • D3DXVec3BaryCentric
  • D3DXVec3CatmullRom
  • D3DXVec3Cross
  • D3DXVec3Dot
  • D3DXVec3Hermite
  • D3DXVec3Length
  • D3DXVec3LengthSq
  • D3DXVec3Lerp
  • D3DXVec3Maximize
  • D3DXVec3Minimize
  • D3DXVec3Normalize
  • D3DXVec3Project
  • D3DXVec3Scale
  • D3DXVec3Subtract
  • D3DXVec3Transform
  • D3DXVec3TransformCoord
  • D3DXVec3TransformNormal
  • D3DXVec3Unproject

Many additional functions that simplify tasks using two- and four-component-vectors are included among the Math Functions supplied by the D3DX utility library.


Transforms
Microsoft DirectX 9.0 SDK Update (October 2004)

Transforms

The part of Microsoft Direct3D that pushes geometry through the fixed function geometry pipeline is the transform engine. It locates the model and viewer in the world, projects vertices for display on the screen, and clips vertices to the viewport. The transform engine also performs lighting computations to determine diffuse and specular components at each vertex.

The geometry pipeline takes vertices as input. The transform engine applies the world, view, and projection transforms to the vertices, clips the result, and passes everything to the rasterizer.

At the head of the pipeline, a model's vertices are declared relative to a local coordinate system. This is a local origin and an orientation. This orientation of coordinates is often referred to as model space, and individual coordinates are called model coordinates.

The first stage of the geometry pipeline transforms a model's vertices from their local coordinate system to a coordinate system that is used by all the objects in a scene. The process of reorienting the vertices is called the world transform. This new orientation is commonly referred to as world space, and each vertex in world space is declared using world coordinates.

In the next stage, the vertices that describe your 3-D world are oriented with respect to a camera. That is, your application chooses a point-of-view for the scene, and world space coordinates are relocated and rotated around the camera's view, turning world space into camera space. This is the view transform.

The next stage is the projection transform. In this part of the pipeline, objects are usually scaled with relation to their distance from the viewer in order to give the illusion of depth to a scene; close objects are made to appear larger than distant objects, and so on. For simplicity, this documentation refers to the space in which vertices exist after the projection transform as projection space. Some graphics books might refer to projection space as post-perspective homogeneous space. Not all projection transforms scale the size of objects in a scene. A projection such as this is sometimes called an affine or orthogonal projection.

In the final part of the pipeline, any vertices that will not be visible on the screen are removed, so that the rasterizer doesn't take the time to calculate the colors and shading for something that will never be seen. This process is called clipping. After clipping, the remaining vertices are scaled according to the viewport parameters and converted into screen coordinates. The resulting vertices, seen on the screen when the scene is rasterized, exist in screen space.

Transforms are used to convert object geometry from one coordinate space to another. Direct3D uses matrices to perform 3-D transforms. This section explains how matrices create 3-D transforms, describes some common uses for transforms, and details how you can combine matrices to produce a single matrix that encompasses multiple transforms.

  • World Transform - convert from model space to world space
  • View Transform - convert from world space to view space
  • Projection Transform - convert from view space to projection space

Matrix Transforms

In applications that work with 3-D graphics, you can use geometrical transforms to do the following:

  • Express the location of an object relative to another object.
  • Rotate and size objects.
  • Change viewing positions, directions, and perspectives.

You can transform any point (x,y,z) into another point (x', y', z') using a 4 by 4 matrix.

Perform the following operations on (x, y, z) and the matrix to produce the point (x', y', z').

The most common transforms are translation, rotation, and scaling. You can combine the matrices that produce these effects into a single matrix to calculate several transforms at once. For example, you can build a single matrix to translate and rotate a series of points.

Matrices are written in row-column order. A matrix that evenly scales vertices along each axis, known as uniform scaling, is represented by the following matrix using mathematical notation.

In C++, Direct3D declares matrices as a two-dimensional array, using the D3DMATRIX structure. The following example shows how to initialize a D3DMATRIX structure to act as a uniform scaling matrix.

// In this example, s is a variable of type float.

D3DMATRIX scale = {
    s,               0.0f,            0.0f,            0.0f,
    0.0f,            s,               0.0f,            0.0f,
    0.0f,            0.0f,            s,               0.0f,
    0.0f,            0.0f,            0.0f,            1.0f
};

Translate

The following transform translates the point (x, y, z) to a new point (x', y', z').

You can manually create a translation matrix in C++. The following example shows the source code for a function that creates a matrix to translate vertices.

D3DXMATRIX Translate(const float dx, const float dy, const float dz) {
    D3DXMATRIX ret;

    D3DXMatrixIdentity(&ret);
    ret(3, 0) = dx;
    ret(3, 1) = dy;
    ret(3, 2) = dz;
    return ret;
}    // End of Translate

For convenience, the D3DX utility library supplies the D3DXMatrixTranslation function.

Scale

The following transform scales the point (x, y, z) by arbitrary values in the x-, y-, and z-directions to a new point (x', y', z').

Rotate

The transforms described here are for left-handed coordinate systems, and so may be different from transform matrices that you have seen elsewhere.

The following matrix rotates the point (x, y, z) around the x-axis, producing a new point (x', y', z').

x rotation matrix

The following matrix rotates the point around the y-axis.

y rotation matrix

The following matrix rotates the point around the z-axis.

z rotation matrix

In these example matrices, the Greek letter theta ( θ ) stands for the angle of rotation, in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

In a C++ application, use the D3DXMatrixRotationX, D3DXMatrixRotationY, and D3DXMatrixRotationZ functions supplied by the D3DX utility library to create rotation matrices. The following is the code for the D3DXMatrixRotationX function.

D3DXMATRIX* WINAPI D3DXMatrixRotationX
    ( D3DXMATRIX *pOut, float angle )
{
#if DBG
    if(!pOut)
        return NULL;
#endif

    float sin, cos;
    sincosf(angle, &sin, &cos);  // Determine sin and cos of angle

    pOut->_11 = 1.0f; pOut->_12 =  0.0f;   pOut->_13 = 0.0f; pOut->_14 = 0.0f;
    pOut->_21 = 0.0f; pOut->_22 =  cos;    pOut->_23 = sin;  pOut->_24 = 0.0f;
    pOut->_31 = 0.0f; pOut->_32 = -sin;    pOut->_33 = cos;  pOut->_34 = 0.0f;
    pOut->_41 = 0.0f; pOut->_42 =  0.0f;   pOut->_43 = 0.0f; pOut->_44 = 1.0f;

    return pOut;
}

Concatenating Matrices

One advantage of using matrices is that you can combine the effects of two or more matrices by multiplying them. This means that, to rotate a model and then translate it to some location, you don't need to apply two matrices. Instead, you multiply the rotation and translation matrices to produce a composite matrix that contains all their effects. This process, called matrix concatenation, can be written with the following formula.

Matrix concatenation formula

In this formula, C is the composite matrix being created, and M1 through Mn are the individual matrices. In most cases, only two or three matrices are concatenated, but there is no limit.

Use the D3DXMatrixMultiply function to perform matrix multiplication.

The order in which the matrix multiplication is performed is crucial. The preceding formula reflects the left-to-right rule of matrix concatenation. That is, the visible effects of the matrices that you use to create a composite matrix occur in left-to-right order. A typical world matrix is shown in the following example. Imagine that you are creating the world matrix for a stereotypical flying saucer. You would probably want to spin the flying saucer around its center - the y-axis of model space - and translate it to some other location in your scene. To accomplish this effect, you first create a rotation matrix, and then multiply it by a translation matrix, as shown in the following formula.

In this formula, Ry is a matrix for rotation about the y-axis, and Tw is a translation to some position in world coordinates.

The order in which you multiply the matrices is important because, unlike multiplying two scalar values, matrix multiplication is not commutative. Multiplying the matrices in the opposite order has the visual effect of translating the flying saucer to its world space position, and then rotating it around the world origin.

No matter what type of matrix you are creating, remember the left-to-right rule to ensure that you achieve the expected effects.


World Transform
Microsoft DirectX 9.0 SDK Update (October 2004)

World Transform

The discussion of the world transformation introduces basic concepts and provides details on how to set up a world transform.

What Is a World Transform?

A world transform changes coordinates from model space, where vertices are defined relative to a model's local origin, to world space, where vertices are defined relative to an origin common to all the objects in a scene. In essence, the world transform places a model into the world; hence its name. The following diagram illustrates the relationship between the world coordinate system and a model's local coordinate system.

The world transform can include any combination of translations, rotations, and scalings.

Setting Up a World Matrix

As with any other transform, create the world transform by concatenating a series of matrices into a single matrix that contains the sum total of their effects. In the simplest case, when a model is at the world origin and its local coordinate axes are oriented the same as world space, the world matrix is the identity matrix. More commonly, the world matrix is a combination of a translation into world space and possibly one or more rotations to turn the model as needed.

The following example, from a fictitious 3-D model class written in C++, uses the helper functions included in the D3DX utility library to create a world matrix that includes three rotations to orient a model and a translation to relocate it relative to its position in world space.

/*
 * For the purposes of this example, the following variables
 * are assumed to be valid and initialized.
 *
 * The m_xPos, m_yPos, m_zPos variables contain the model's
 * location in world coordinates.
 *
 * The m_fPitch, m_fYaw, and m_fRoll variables are floats that
 * contain the model's orientation in terms of pitch, yaw, and roll
 * angles, in radians.
 */

void C3DModel::MakeWorldMatrix( D3DXMATRIX* pMatWorld )
{
    D3DXMATRIX MatTemp;  // Temp matrix for rotations.
    D3DXMATRIX MatRot;   // Final rotation matrix, applied to
                         // pMatWorld.

    // Using the left-to-right order of matrix concatenation,
    // apply the translation to the object's world position
    // before applying the rotations.
    D3DXMatrixTranslation(pMatWorld, m_xPos, m_yPos, m_zPos);
    D3DXMatrixIdentity(&MatRot);

    // Now, apply the orientation variables to the world matrix
    if(m_fPitch || m_fYaw || m_fRoll) {
        // Produce and combine the rotation matrices.
        D3DXMatrixRotationX(&MatTemp, m_fPitch);         // Pitch
        D3DXMatrixMultiply(&MatRot, &MatRot, &MatTemp);
        D3DXMatrixRotationY(&MatTemp, m_fYaw);           // Yaw
        D3DXMatrixMultiply(&MatRot, &MatRot, &MatTemp);
        D3DXMatrixRotationZ(&MatTemp, m_fRoll);          // Roll
        D3DXMatrixMultiply(&MatRot, &MatRot, &MatTemp);

        // Apply the rotation matrices to complete the world matrix.
        D3DXMatrixMultiply(pMatWorld, &MatRot, pMatWorld);
    }
}

After you prepare the world matrix, call the IDirect3DDevice9::SetTransform method to set it, specifying the D3DTS_WORLD macro for the first parameter.

Note Microsoft Direct3D uses the world and view matrices that you set to configure several internal data structures. Each time you set a new world or view matrix, the system recalculates the associated internal structures. Setting these matrices frequently—for example, thousands of times per frame—is computationally time-consuming. You can minimize the number of required calculations by concatenating your world and view matrices into a world-view matrix that you set as the world matrix, and then setting the view matrix to the identity. Keep cached copies of individual world and view matrices so that you can modify, concatenate, and reset the world matrix as needed. For clarity, in this documentation Direct3D samples rarely employ this optimization.


View Transform
Microsoft DirectX 9.0 SDK Update (October 2004)

View Transform

This section introduces the basic concepts of the view transform and provides details on how to set up a view transform matrix in a Microsoft Direct3D application.

The view transform locates the viewer in world space, transforming vertices into camera space. In camera space, the camera, or viewer, is at the origin, looking in the positive z-direction. Recall that Direct3D uses a left-handed coordinate system, so z is positive into a scene. The view matrix relocates the objects in the world around a camera's position—the origin of camera space—and orientation.

There are many ways to create a view matrix. In all cases, the camera has some logical position and orientation in world space that is used as a starting point to create a view matrix that will be applied to the models in a scene. The view matrix translates and rotates objects to place them in camera space, where the camera is at the origin. One way to create a view matrix is to combine a translation matrix with rotation matrices for each axis. In this approach, the following general matrix formula applies.

In this formula, V is the view matrix being created, T is a translation matrix that repositions objects in the world, and Rx through Rz are rotation matrices that rotate objects along the x-, y-, and z-axis. The translation and rotation matrices are based on the camera's logical position and orientation in world space. So, if the camera's logical position in the world is <10,20,100>, the aim of the translation matrix is to move objects -10 units along the x-axis, -20 units along the y-axis, and -100 units along the z-axis. The rotation matrices in the formula are based on the camera's orientation, in terms of how much the axes of camera space are rotated out of alignment with world space. For example, if the camera mentioned earlier is pointing straight down, its z-axis is 90 degrees (pi/2 radians) out of alignment with the z-axis of world space, as shown in the following illustration.

The rotation matrices apply rotations of equal, but opposite, magnitude to the models in the scene. The view matrix for this camera includes a rotation of -90 degrees around the x-axis. The rotation matrix is combined with the translation matrix to create a view matrix that adjusts the position and orientation of the objects in the scene so that their top is facing the camera, giving the appearance that the camera is above the model.

Setting Up a View Matrix

The D3DXMatrixLookAtLH and D3DXMatrixLookAtRH helper functions create a view matrix based on the camera location and a look-at point.

The following example creates a view matrix for left-handed coordinates.

D3DXMATRIX out;
D3DXVECTOR3 eye(2,3,3);
D3DXVECTOR3 at(0,0,0);
D3DXVECTOR3 up(0,1,0);
D3DXMatrixLookAtLH(&out, &eye, &at, &up);

Direct3D uses the world and view matrices to configure several internal data structures. Each time you set a new world or view matrix, the system recalculates the associated internal structures. Setting these matrices frequently is computationally time-consuming. You can minimize the number of required calculations by concatenating your world and view matrices into a world-view matrix that you set as the world matrix, and then setting the view matrix to the identity. Keep cached copies of individual world and view matrices that you can modify, concatenate, and reset the world matrix as needed. For clarity, the samples rarely employ this optimization.


Projection Transform
Microsoft DirectX 9.0 SDK Update (October 2004)

Projection Transform

You can think of the projection transformation as controlling the camera's internals; it is analogous to choosing a lens for the camera. This is the most complicated of the three transformation types. This discussion of the projection transformation is organized into the following topics.

The projection matrix is typically a scale and perspective projection. The projection transformation converts the viewing frustum into a cuboid shape. Because the near end of the viewing frustum is smaller than the far end, this has the effect of expanding objects that are near to the camera; this is how perspective is applied to the scene.

In the viewing frustum, the distance between the camera and the origin of the viewing transform space is defined arbitrarily as D, so the projection matrix looks like:

The viewing matrix translates the camera to the origin by translating in the z direction by - D. The translation matrix is as follows:

Multiplying the translation matrix by the projection matrix (T*P) gives the composite projection matrix. It looks like:

The perspective transform converts a viewing frustum into a new coordinate space. Notice that the frustum becomes cuboid and also that the origin moves from the upper-right corner of the scene to the center.

In the perspective transform, the limits of the x- and y-directions are -1 and 1. The limits of the z-direction are 0 for the front plane and 1 for the back plane.

This matrix translates and scales objects based on a specified distance from the camera to the near clipping plane, but it doesn't consider the field of view (fov), and the z-values that it produces for objects in the distance can be nearly identical, making depth comparisons difficult. The following matrix addresses these issues, and it adjusts vertices to account for the aspect ratio of the viewport, making it a good choice for the perspective projection.

In this matrix, Zn is the z-value of the near clipping plane. The variables w, h, and Q have the following meanings. Note that fovw and fovk represent the viewport's horizontal and vertical fields of view, in radians.

For your application, using field-of-view angles to define the x- and y-scaling coefficients might not be as convenient as using the viewport's horizontal and vertical dimensions (in camera space). As the math works out, the following two formulas for w and h use the viewport's dimensions, and are equivalent to the preceding formulas.

In these formulas, Zn represents the position of the near clipping plane, and the Vw and Vh variables represent the width and height of the viewport, in camera space.

For a C++ application, these two dimensions correspond directly to the Width and Height members of the D3DVIEWPORT9 structure.

Whatever formula you decide to use, be sure to set Zn to as large a value as possible, because z-values extremely close to the camera don't vary by much. This makes depth comparisons using 16-bit z-buffers somewhat complicated.

As with the world and view transformations, you call the IDirect3DDevice9::SetTransform method to set the projection transform.

Setting Up a Projection Matrix

The following ProjectionMatrix sample function sets the front and back clipping planes, as well as the horizontal and vertical field of view angles. The fields of view should be less than pi radians.

D3DXMATRIX
ProjectionMatrix(const float near_plane, // Distance to near clipping
                                         // plane
                 const float far_plane,  // Distance to far clipping
                                         // plane
                 const float fov_horiz,  // Horizontal field of view
                                         // angle, in radians
                 const float fov_vert)   // Vertical field of view
                                         // angle, in radians
{
    float    h, w, Q;

    w = (float)1/tan(fov_horiz*0.5);  // 1/tan(x) == cot(x)
    h = (float)1/tan(fov_vert*0.5);   // 1/tan(x) == cot(x)
    Q = far_plane/(far_plane - near_plane);

    D3DXMATRIX ret;
    ZeroMemory(&ret, sizeof(ret));

    ret(0, 0) = w;
    ret(1, 1) = h;
    ret(2, 2) = Q;
    ret(3, 2) = -Q*near_plane;
    ret(2, 3) = 1;
    return ret;
}   // End of ProjectionMatrix

After creating the matrix, set it with IDirect3DDevice9::SetTransform specifying D3DTS_PROJECTION.

The D3DX utility library provides the following functions to help you set up your projection matrix.

  • D3DXMatrixPerspectiveLH
  • D3DXMatrixPerspectiveRH
  • D3DXMatrixPerspectiveFovLH
  • D3DXMatrixPerspectiveFovRH
  • D3DXMatrixPerspectiveOffCenterLH
  • D3DXMatrixPerspectiveOffCenterRH

A W-Friendly Projection Matrix

Microsoft Direct3D can use the w-component of a vertex that has been transformed by the world, view, and projection matrices to perform depth-based calculations in depth-buffer or fog effects. Computations such as these require that your projection matrix normalize w to be equivalent to world-space z. In short, if your projection matrix includes a (3,4) coefficient that is not 1, you must scale all the coefficients by the inverse of the (3,4) coefficient to make a proper matrix. If you don't provide a compliant matrix, fog effects and depth buffering are not applied correctly.

The following illustration shows a noncompliant projection matrix, and the same matrix scaled so that eye-relative fog will be enabled.

In the preceding matrices, all variables are assumed to be nonzero. For more information about eye-relative fog, see Eye-Relative vs. Z-Based Depth. For information about w-based depth buffering, see Depth Buffers.

Direct3D uses the currently set projection matrix in its w-based depth calculations. As a result, applications must set a compliant projection matrix to receive the desired w-based features, even if they do not use Direct3D for transforms.


Viewports and Clipping
Microsoft DirectX 9.0 SDK Update (October 2004)

Viewports and Clipping

Conceptually, a viewport is a two-dimensional (2-D) rectangle into which a three-dimensional (3-D) scene is projected. In Microsoft Direct3D, the rectangle exists as coordinates within a Direct3D surface that the system uses as a rendering target. The projection transformation converts vertices into the coordinate system used for the viewport. A viewport is also used to specify the range of depth values on a render-target surface into which a scene will be rendered (usually 0.0 to 1.0).

The Viewing Frustum

A viewing frustum is 3-D volume in a scene positioned relative to the viewport's camera. The shape of the volume affects how models are projected from camera space onto the screen. The most common type of projection, a perspective projection, is responsible for making objects near the camera appear bigger than objects in the distance. For perspective viewing, the viewing frustum can be visualized as a pyramid, with the camera positioned at the tip. This pyramid is intersected by a front and back clipping plane. The volume within the pyramid between the front and back clipping planes is the viewing frustum. Objects are visible only when they are in this volume.

If you imagine that you are standing in a dark room and looking through a square window, you are visualizing a viewing frustum. In this analogy, the near clipping plane is the window, and the back clipping plane is whatever finally interrupts your view—the skyscraper across the street, the mountains in the distance, or nothing at all. You can see everything inside the truncated pyramid that starts at the window and ends with whatever interrupts your view, and you can see nothing else.

The viewing frustum is defined by fov (field of view) and by the distances of the front and back clipping planes, specified in z-coordinates.

In this illustration, the variable D is the distance from the camera to the origin of the space that was defined in the last part of the geometry pipeline—the viewing transformation. This is the space around which you arrange the limits of your viewing frustum. For information about how this D variable is used to build the projection matrix, see the Projection Transform

Viewport Rectangle

You define the viewport rectangle in C++ by using the D3DVIEWPORT9 structure. The D3DVIEWPORT9 structure is used with the following viewport manipulation methods exposed by the IDirect3DDevice9 interface.

  • IDirect3DDevice9::GetViewport
  • IDirect3DDevice9::SetViewport

The D3DVIEWPORT9 structure contains four members—X, Y, Width, and Height—that define the area of the render-target surface into which a scene will be rendered. These values correspond to the destination rectangle, or viewport rectangle, as shown in the following illustration.

The values you specify for the X, Y, Width, and Height members of the D3DVIEWPORT9 structure are screen coordinates relative to the upper-left corner of the render-target surface. The structure defines two additional members (MinZ and MaxZ) that indicate the depth-ranges into which the scene will be rendered.

Direct3D assumes that the viewport clipping volume ranges from -1.0 to 1.0 in X, and from 1.0 to -1.0 in Y. These were the settings used most often by applications in the past. You can adjust the viewport aspect ratio before clipping using the projection transform.

Note The D3DVIEWPORT9 structure members MinZ and MaxZ indicate the depth-ranges into which the scene will be rendered and are not used for clipping. Most applications will set these members to 0.0 and 1.0 to enable the system to render to the entire range of depth values in the depth buffer. In some cases, you can achieve special effects by using other depth ranges. For instance, to render a heads-up display in a game, you can set both values to 0.0 to force the system to render objects in a scene in the foreground, or you might set them both to 1.0 to render an object that should always be in the background.

The dimensions used in the X, Y, Width, and Height members of the D3DVIEWPORT9 structure for a viewport define the location and dimensions of the viewport on the render-target surface. These values are in screen coordinates, relative to the upper-left corner of the surface.

Direct3D uses the viewport location and dimensions to scale the vertices to fit a rendered scene into the appropriate location on the target surface. Internally, Direct3D inserts these values into a matrix that is applied to each vertex:

This matrix scales vertices according to the viewport dimensions and desired depth range and translates them to the appropriate location on the render-target surface. The matrix also flips the y-coordinate to reflect a screen origin at the top-left corner with y increasing downward. After this matrix is applied, vertices are still homogeneous—that is, they still exist as [x,y,z,w] vertices—and they must be converted to non-homogeneous coordinates before being sent to the rasterizer.

Note The viewport scaling matrix incorporates the MinZ and MaxZ members of the D3DVIEWPORT9 structure to scale vertices to fit the depth range [MinZ, MaxZ]. This represents different semantics from previous releases of Microsoft DirectX, in which these members were used for clipping.
Note Applications typically set MinZ and MaxZ to 0.0 and 1.0 respectively to cause the system to render to the entire depth range. However, you can use other values to achieve certain affects. For example, you might set both values to 0.0 to force all objects into the foreground, or set both to 1.0 to render all objects into the background.

Clearing A Viewport

Clearing the viewport resets the contents of the viewport rectangle on the render-target surface. It can also clear the rectangle in the depth and stencil buffer surfaces.

Use IDirect3DDevice9::Clear to clear the viewport. The method accepts one or more rectangles that define the areas on the surface being cleared. Setting the Count parameter to 1, and the pRects parameter to the address of a single rectangle that covers the entire viewport area will clear the entire viewport. Another way to clear the entire viewport is to set the pRects parameter to NULL and the Count parameter to 0.

The IDirect3DDevice9::Clear can be used for clearing stencil bits within a depth buffer. Simply set the Flags parameter to determine how IDirect3DDevice9::Clear works with the render target and any associated depth or stencil buffers. The D3DCLEAR_TARGET flag will clear the viewport using an arbitrary RGBA color that you provide in the Color argument (this is not the material color). The D3DCLEAR_ZBUFFER flag will clear the depth buffer to an arbitrary depth you specify in Z: 0.0 is the closest distance, and 1.0 is the farthest. The D3DCLEAR_STENCIL flag will reset the stencil bits to the value you provide in the Stencil argument. You can use integers that range from 0 to 2n-1, where n is the stencil buffer bit depth.

In some situations, you might be rendering only to small portions of the render target and depth buffer surfaces. The clear methods also enable you to clear multiple areas of your surfaces in a single call. Do this by setting the Count parameter to the number of rectangles you want cleared, and specify the address of the first rectangle in an array of rectangles in the pRects parameter.

Setup The Viewport For Clipping

The results of the projection matrix determine the clipping volume in projection space as:

-wc <= xc <= wc

-wc <= yc <= wc

0 <= zc <= wc

Where: x, y, z, and w represent the vertex coordinates after the projection transformation is applied. Any vertices that have an x-, y-, or z-component outside these ranges are clipped, if clipping is enabled (the default behavior).

With the exception of vertex buffers, applications enable or disable clipping by way of the D3DRS_CLIPPING render state. Clipping information for vertex buffers is generated during processing. For more information, see Fixed Function Vertex Processing and Programmable Vertex Processing.

Direct3D does not clip transformed vertices of a primitive from a vertex buffer unless it comes from IDirect3DDevice9::ProcessVertices. If you are doing your own transforms and need Direct3D to do the clipping, you should not use vertex buffers. In this case, the application traverses the data to transform it. Direct3D traverses the data a second time to clip it, and then the driver renders the data, which is inefficient. So, if the application transforms the data, is should also clip the data.

When the device receives pre-transformed and lit vertices (T&L vertices) that need to be clipped, in order to perform the clipping operation the vertices are back-transformed to the clipping space using the vertex's reciprocal homogeneous w (RHW) and the viewport information. Clipping is then performed. Not all devices are capable of performing this back-transform in order to clip T&L vertices.

The D3DPMISCCAPS_CLIPTLVERTS device capability indicates whether the device is capable of clipping T&L vertices. If this capability is not set, the application is responsible for clipping the T&L vertices that it intends to send down to the device to be rendered. The device is always capable of clipping T&L vertices in the software vertex processing mode (regardless of whether the device is created in the software vertex processing mode, or switched to the software vertex processing mode).

The only requirement for configuring the viewport parameters for a rendering device is to set the viewport's clipping volume. To do this, you initialize and set clipping values for the clipping volume and for the render-target surface. Viewports are commonly set up to render to the full area of the render-target surface, but this isn't a requirement.

You can use the following settings for the members of the D3DVIEWPORT9 structure to achieve this in C++.

D3DVIEWPORT9 viewData = { 0, 0, width, height, 0.0f, 1.0f };

After setting values in the D3DVIEWPORT9 structure, apply the viewport parameters to the device by calling its IDirect3DDevice9::SetViewport method. The following code example shows what this call might look like.

HRESULT hr;

hr = pd3dDevice->SetViewport(&viewData);
if(FAILED(hr))
    return hr;

If the call succeeds, the viewport parameters are set and will take effect the next time a rendering method is called. To make changes to the viewport parameters, just update the values in the D3DVIEWPORT9 structure and call IDirect3DDevice9::SetViewport again.

Note The D3DVIEWPORT9 structure members MinZ and MaxZ indicate the depth-ranges into which the scene will be rendered and are not used for clipping. Most applications set these members to 0.0 and 1.0 to enable the system to render to the entire range of depth values in the depth buffer. In some cases, you can achieve special effects by using other depth ranges. For instance, to render a heads-up display in a game, you can set both values to 0.0 to force the system to render objects in a scene in the foreground, or you might set them both to 1.0 to render an object that should always be in the background.


Lights and Materials
Microsoft DirectX 9.0 SDK Update (October 2004)

Lights and Materials

Lights are used to illuminate objects in a scene. When lighting is enabled, Microsoft Direct3D calculates the color of each object vertex based on a combination of:

  • The current material color and the texels in an associated texture map.
  • The diffuse and specular colors at the vertex, if specified.
  • The color and intensity of light produced by light sources in the scene or the scene's ambient light level.

When you use Direct3D lighting and materials, you allow Direct3D to handle the details of illumination for you. Advanced users can perform lighting on their own, if desired.

How you work with lighting and materials makes a big difference in the appearance of the rendered scene. Materials define how light reflects off a surface. Direct light and ambient light levels define the light that is reflected. You must use materials to render a scene if lighting is enabled. Lights are not required to render a scene, but details in a scene rendered without light are not visible. At best, rendering an unlit scene results in a silhouette of the objects in the scene. This is not enough detail for most purposes.

Direct Light vs. Ambient Light

Although both direct and ambient light illuminate objects in a scene, they are independent of one another, they have very different effects, and they require that you work with them in completely different ways.

Direct light is just that: direct. Direct light always has direction and color, and it is a factor for shading algorithms, such as Gouraud shading. Different types of lights emit direct light in different ways, creating special attenuation effects. You create a set of light parameters for direct light by calling the IDirect3DDevice9::SetLight method.

Ambient light is effectively everywhere in a scene. You can think of it as a general level of light that fills an entire scene, regardless of the objects and their locations in that scene. Ambient light has no position or direction, only color and intensity. Each light adds to the overall ambient light in a scene. Set the ambient light level with a call to the IDirect3DDevice9::SetRenderState method, specifying D3DRS_AMBIENT as the State parameter, and the desired RGBA color as the Value parameter.

Ambient light color takes the form of an RGBA value, where each component is an integer value from 0 to 255. This is unlike most color values in Direct3D.

You can use the D3DCOLOR_RGBA macro to generate RGBA values. The red, green, and blue components combine to make the final color of the ambient light. The alpha component controls the transparency of the color. When using hardware acceleration or RGB emulation, the alpha component is ignored.

Direct3D Light Model vs. Nature

In nature, when light is emitted from a source, it is reflected off of hundreds, if not thousands or millions of objects before reaching the user's eye. Each time it is reflected, some light is absorbed by a surface, some is scattered in random directions, and the rest goes on to another surface or to the user's eye. This process continues until the light is reduced to nothing or a user perceives the light.

Obviously, the calculations required to perfectly simulate the natural behavior of light are too time-consuming to use for real-time 3-D graphics. Therefore, with speed in mind, the Direct3D light model approximates the way light works in the natural world. Direct3D describes light in terms of red, green, and blue components that combine to create a final color.

In Direct3D, when light reflects off a surface, the light color interacts mathematically with the surface itself to create the color eventually displayed on the screen. For specific information about the algorithms Direct3D uses, see Mathematics of Lighting.

The Direct3D light model generalizes light into two types: ambient light and direct light. Each has different attributes, and each interacts with the material of a surface in different ways. Ambient light is light that has been scattered so much that its direction and source are indeterminate: it maintains a low level of intensity everywhere. The indirect lighting used by photographers is a good example of ambient light. Ambient light in Direct3D, as in nature, has no real direction or source, only a color and intensity. In fact, the ambient light level is completely independent of any objects in a scene that generate light. Ambient light does not contribute to specular reflection.

Direct light is the light generated by a source within a scene; it always has color and intensity, and it travels in a specified direction. Direct light interacts with the material of a surface to create specular highlights, and its direction is used as a factor in shading algorithms, including Gouraud shading. When direct light is reflected, it does not contribute to the ambient light level in a scene. The sources in a scene that generate direct light have different characteristics that affect how they illuminate a scene.

Additionally, a polygon's material has properties that affect how that polygon reflects the light it receives. You set a single reflectance trait that describes how the material reflects ambient light, and you set individual traits to determine the material's specular and diffuse reflectance. For more information, see Materials.

Color Values for Lights and Materials

Direct3D describes color in terms of four components—red, green, blue, and alpha—that combine to make a final color. The D3DCOLORVALUE C++ structure is defined to contain values for each component. Each member is a floating-point value that typically ranges from 0.0 to 1.0, inclusive. Although both lights and materials use the same structure to describe color, the values in the structure are used a little differently by each.

Color values for light sources represent the amount of a particular light component it emits. Because lights don't use an alpha component, only the red, green, and blue components of the color are relevant. You can visualize the three components as the red, green, and blue lenses on a projection television. Each lens might be off (a 0.0 value in the appropriate member), it might be as bright as possible (a 1.0 value), or it might be some level in between. The colors coming through the lenses combine to make the light's final color. A combination like R(1.0), G(1.0), B(1.0) creates a white light, where R(0.0), G(0.0), B(0.0) doesn't emit light at all. You can make a light that emits only one component, resulting in a pure red, green, or blue light; or, the light could use combinations to emit colors like yellow or purple. You can even set negative color component values to create a "dark light" that actually removes light from a scene. Or, you might set the components to some value larger than 1.0 to create an extremely bright light.

With materials, on the other hand, color values represent how much of a light component is reflected by a surface that is rendered with that material. A material whose color components are R(1.0), G(1.0), B(1.0), A(1.0) reflects all the light that comes its way. Likewise, a material with R(0.0), G(1.0), B(0.0), A(1.0) reflects all the green light that is directed at it. Materials have multiple reflectance values to create various types of effects.

Additional information is contained in the following topics.

  • Light Types
  • Light Properties
  • Mathematics of Lighting
  • Materials


Light Types
Microsoft DirectX 9.0 SDK Update (October 2004)

Light Types

The light type property defines which type of light source you're using. The light type is set by using a value from the D3DLIGHTTYPE C++ enumeration in the Type member of the light's D3DLIGHT9 structure. There are three types of lights in Microsoft Direct3D—point lights, spotlights, and directional lights. Each type illuminates objects in a scene differently, with varying levels of computational overhead.

Point Light

Point lights have color and position within a scene, but no single direction. They give off light equally in all directions, as shown in the following illustration.

A light bulb is a good example of a point light. Point lights are affected by attenuation and range, and illuminate a mesh on a vertex-by-vertex basis. During lighting, Direct3D uses the point light's position in world space and the coordinates of the vertex being lit to derive a vector for the direction of the light, and the distance that the light has traveled. Both are used, along with the vertex normal, to calculate the contribution of the light to the illumination of the surface.

Directional Light

Directional lights have only color and direction, not position. They emit parallel light. This means that all light generated by directional lights travels through a scene in the same direction. Imagine a directional light as a light source at near infinite distance, such as the sun. Directional lights are not affected by attenuation or range, so the direction and color you specify are the only factors considered when Direct3D calculates vertex colors. Because of the small number of illumination factors, these are the least computationally intensive lights to use.

SpotLight

Spotlights have color, position, and direction in which they emit light. Light emitted from a spotlight is made up of a bright inner cone and a larger outer cone, with the light intensity diminishing between the two, as shown in the following illustration.

Spotlights are affected by falloff, attenuation, and range. These factors, as well as the distance light travels to each vertex, are figured in when computing lighting effects for objects in a scene. Computing these effects for each vertex makes spotlights the most computationally time-consuming of all lights in Direct3D.

The D3DLIGHT9 C++ structure contains three members that are used only by spotlights. These members—Falloff, Theta, and Phi—control how large or small a spotlight object's inner and outer cones are, and how light decreases between them.

The Theta value is the radian angle of the spotlight's inner cone, and the Phi value is the angle for the outer cone of light. The Falloff value controls how light intensity decreases between the outer edge of the inner cone and the inner edge of the outer cone. Most applications set Falloff to 1.0 to create falloff that occurs evenly between the two cones, but you can set other values as needed.

The following illustration shows the relationship between the values for these members and how they can affect a spotlight's inner and outer cones of light.

Spotlights emit a cone of light that has two parts: a bright inner cone and an outer cone. Light is brightest in the inner cone and isn't present outside the outer cone, with light intensity attenuating between the two areas. This type of attenuation is commonly referred to as falloff.

The amount of light a vertex receives is based on the vertex's location in the inner or outer cones. Direct3D computes the dot product of the spotlight's direction vector (L) and the vector from the light to the vertex (D). This value is equal to the cosine of the angle between the two vectors, and serves as an indicator of the vertex's position that can be compared to the light's cone angles to determine where the vertex might lie in the inner or outer cones. The following illustration provides a graphical representation of the association between these two vectors.

Spotlight direction vector and vector from vertex to spotlight

The system compares this value to the cosine of the spotlight's inner and outer cone angles. In the light's D3DLIGHT9 structure, the Theta and Phi members represent the total cone angles for the inner and outer cones. Because the attenuation occurs as the vertex becomes more distant from the center of illumination (rather than across the total cone angle), the runtime divides these cone angles in half before calculating their cosines.

If the dot product of vectors L and D is less than or equal to the cosine of the outer cone angle, the vertex lies beyond the outer cone and receives no light. If the dot product of L and D is greater than the cosine of the inner cone angle, then the vertex is within the inner cone and receives the maximum amount of light, still considering attenuation over distance. If the vertex is somewhere between the two regions, then falloff is calculated with the following formula:

Formula for light intensity at vertex, after falloff

Where:

  • If is light intensity after falloff
  • Alpha is the angle between vectors L and D
  • Theta is the inner cone angle
  • Phi is the outer cone angle
  • p is the falloff

This formula generates a value between 0.0 and 1.0 that scales the light's intensity at the vertex to account for falloff. Attenuation as a factor of the vertex's distance from the light is also applied. The following illustration shows how different falloff values can affect the falloff curve.

Graph of light intensity versus vertex distance from the light

The effect of various falloff values on the actual lighting is subtle, and a small performance penalty is incurred by shaping the falloff curve with falloff values other than 1.0. For these reasons, this value is typically set to 1.0.


Light Properties
Microsoft DirectX 9.0 SDK Update (October 2004)

Light Properties

Light properties describe a light source's type and color. Depending on the type of light being used, a light can have properties for attenuation and range, or for spotlight effects. But, not all types of lights use all properties. Microsoft Direct3D uses the D3DLIGHT9 structure to carry information about light properties for all types of light sources. This section contains information for all light properties. Information is divided into the following groups.

The position, range, and attenuation properties define a light's location in world space and how the light it emits behaves over distance. As with all light properties you use in C++, these are contained in a light's D3DLIGHT9 structure.

  • Light Attenuation
  • Light Color
  • Light Direction
  • Light Position
  • Light Range

Light Attenuation

Attenuation controls how a light's intensity decreases toward the maximum distance specified by the range property. Three D3DLIGHT9 structure members represent light attenuation: Attenuation0, Attenuation1, and Attenuation2. These members contain floating-point values ranging from 0.0 through infinity, controlling a light's attenuation. Some applications set the Attenuation1 member to 1.0 and the others to 0.0, resulting in light intensity that changes as 1 / D, where D is the distance from the light source to the vertex. The maximum light intensity is at the source, decreasing to 1 / (Light Range) at the light's range. Typically, an application sets Attenuation0 to 0.0, Attenuation1 to a constant value, and Attenuation2 to 0.0.

You can combine attenuation values to get more complex attenuation effects. Or, you might set them to values outside the normal range to create even stranger attenuation effects. Negative attenuation values, however, are not allowed. See Attenuation and Spotlight Factor.

Light Color

Lights in Direct3D emit three colors that are used independently in the system's lighting computations: a diffuse color, an ambient color, and a specular color. Each is incorporated by the Direct3D lighting module, interacting with a counterpart from the current material, to produce a final color used in rendering. The diffuse color interacts with the diffuse reflectance property of the current material, the specular color with the material's specular reflectance property, and so on. For specifics about how Direct3D applies these colors, see Mathematics of Lighting.

In a C++ application, the D3DLIGHT9 structure includes three members for these colors—Diffuse, Ambient, and Specular—each one is a D3DCOLORVALUE structure that defines the color being emitted.

The type of color that applies most heavily to the system's computations is the diffuse color. The most common diffuse color is white (R:1.0 G:1.0 B:1.0), but you can create colors as needed to achieve desired effects. For example, you could use red light for a fireplace, or you could use green light for a traffic signal set to "Go."

Generally, you set the light color components to values between 0.0 and 1.0, inclusive, but this isn't a requirement. For example, you might set all the components to 2.0, creating a light that is "brighter than white." This type of setting can be especially useful when you use attenuation settings other than constant.

Note that although Direct3D uses RGBA values for lights, the alpha color component is not used.

Usually material colors are used for lighting. However, you can specify that material colors—emissive, ambient, diffuse, and specular—are to be overridden by diffuse or specular vertex colors. This is done by calling IDirect3DDevice9::SetRenderState and setting the device state variables listed in the following table.

Device state variable | Meaning | Type | Default
D3DRS_AMBIENTMATERIALSOURCE | Defines where to get ambient material color. | D3DMATERIALCOLORSOURCE | D3DMCS_MATERIAL
D3DRS_DIFFUSEMATERIALSOURCE | Defines where to get diffuse material color. | D3DMATERIALCOLORSOURCE | D3DMCS_COLOR1
D3DRS_SPECULARMATERIALSOURCE | Defines where to get specular material color. | D3DMATERIALCOLORSOURCE | D3DMCS_COLOR2
D3DRS_EMISSIVEMATERIALSOURCE | Defines where to get emissive material color. | D3DMATERIALCOLORSOURCE | D3DMCS_MATERIAL
D3DRS_COLORVERTEX | Disables or enables use of vertex colors. | BOOL | TRUE

The alpha/transparency value always comes only from the diffuse color's alpha channel.

The fog value always comes only from the specular color's alpha channel.

D3DMATERIALCOLORSOURCE can have the following values.

  • D3DMCS_MATERIAL - Material color is used as source.
  • D3DMCS_COLOR1 - Diffuse vertex color is used as source.
  • D3DMCS_COLOR2 - Specular vertex color is used as source.

Light Direction

A light's direction property determines the direction that the light emitted by the object travels, in world space. Direction is used only by directional lights and spotlights, and is described with a vector.

Set the light direction in the Direction member of the light's D3DLIGHT9 structure. Direction member is of type D3DVECTOR. Direction vectors are described as distances from a logical origin, regardless of the light's position in a scene. Therefore, a spotlight that points straight into a scene—along the positive z-axis—has a direction vector of <0,0,1> no matter where its position is defined to be. Similarly, you can simulate sunlight shining directly on a scene by using a directional light whose direction is <0,-1,0>. Obviously, you don't have to create lights that shine along the coordinate axes; you can mix and match values to create lights that shine at more interesting angles.

Note Although you don't need to normalize a light's direction vector, always be sure that it has magnitude. In other words, don't use a <0,0,0> direction vector.

Light Position

Light position is described using a D3DVECTOR structure in the Position member of the D3DLIGHT9 structure. The x-, y-, and z-coordinates are assumed to be in world space. Directional lights are the only type of light that don't use the position property.

Light Range

A light's range property determines the distance, in world space, at which meshes in a scene no longer receive light emitted by that object. The Range member contains a floating-point value that represents the light's maximum range, in world space. Directional lights don't use the range property.


Mathematics of Lighting
Microsoft DirectX 9.0 SDK Update (October 2004)

Mathematics of Lighting

The Microsoft Direct3D Light Model covers ambient, diffuse, specular, and emissive lighting. This is enough flexibility to solve a wide range of lighting situations. You refer to the total amount of light in a scene as the global illumination and compute it using the following equation.

Global Illumination = Ambient Light + Diffuse Light + Specular Light + Emissive Light

Ambient Lighting is constant lighting. It is constant in all directions and it colors all pixels of an object the same. It is fast to calculate but leaves objects looking flat and unrealistic. To see how ambient lighting is calculated by Direct3D, see Ambient Lighting.

Diffuse Lighting depends on both the light direction and the object surface normal. It varies across the surface of an object as a result of the changing light direction and the changing surface numeral vector. It takes longer to calculate diffuse lighting because it changes for each object vertex, however the benefit of using it is that it shades objects and gives them three-dimensional (3-D) depth. To see how diffuse lighting is calculated in Direct3D, see Diffuse Lighting.

Specular Lighting identifies the bright specular highlights that occur when light hits an object surface and reflects back toward the camera. It is more intense than diffuse light and falls off more rapidly across the object surface. It takes longer to calculate specular lighting than diffuse lighting, however the benefit of using it is that it adds significant detail to a surface. To see how specular lighting is calculated in Direct3D, see Specular Lighting.

Emissive Lighting is light that is emitted by an object; for example, a glow. To see how emissive lighting is calculated in Direct3D, see Emissive Lighting.

Realistic lighting can be accomplished by applying each of these types of lighting to a 3-D scene. The values calculated for ambient, emissive, and diffuse components are output as the diffuse vertex color; the value for the specular lighting component is output as the specular vertex color. Ambient, diffuse, and specular light values can be affected by a given light's attenuation and spotlight factor. For more information about how attenuation works, see Attenuation and Spotlight Factor.

To achieve a more realistic lighting effect, you add more lights; however, the scene takes longer to render. To achieve all the effects a designer wants, some games use more CPU power than is commonly available. In this case, it is typical to reduce the number of lighting calculations to a minimum by using lighting maps and environment maps to add lighting to a scene while using texture maps.

Lighting is computed in the camera space. To see how lighting transformations are calculated, see Camera Space Transformations. Optimized lighting can be computed in model space, when special conditions exist: normal vectors are already normalized (D3DRS_NORMALIZENORMALS is True), vertex blending is not needed, transformation matrices are orthogonal, and so forth.


Ambient Lighting
Microsoft DirectX 9.0 SDK Update (October 2004)

Ambient Lighting

Ambient lighting provides constant lighting for a scene. It lights all object vertices the same because it is not dependent on any other lighting factors such as vertex normals, light direction, light position, range, or attenuation. It is the fastest type of lighting but it produces the least realistic results. Microsoft Direct3D contains a single global ambient light property that you can use without creating any light. Alternatively, you can set any light object to provide ambient lighting. The ambient lighting for a scene is described by the following equation.

Ambient Lighting = Ca*[Ga + Atti*Spoti*sum(Lai)]

Where:

Parameter | Default value | Type | Description
Ca | (0,0,0,0) | D3DCOLORVALUE | Material ambient color
Ga | (0,0,0,0) | D3DCOLORVALUE | Global ambient color
Atteni | (0,0,0,0) | D3DCOLORVALUE | Light attenuation of the ith light. See Attenuation and Spotlight Factor.
Spoti | (0,0,0,0) | D3DVECTOR | Spotlight factor of the ith light. See Attenuation and Spotlight Factor.
sum | N/A | N/A | Sum of the ambient light
Lai | (0,0,0,0) | D3DVECTOR | Light ambient color of the ith light

The value for Ca is either:

  • vertex color1, if AMBIENTMATERIALSOURCE = D3DMCS_COLOR1, and the first vertex color is supplied in the vertex declaration.
  • vertex color2, if AMBIENTMATERIALSOURCE = D3DMCS_COLOR2, and the second vertex color is supplied in vertex declaration.
  • material ambient color.
Note If either AMBIENTMATERIALSOURCE option is used, and the vertex color is not provided, then the material ambient color is used.

To use the material ambient color, use SetMaterial as shown in the example code below.

Ga is the global ambient color. It is set using SetRenderState(D3DRS_AMBIENT). There is one global ambient color in a Direct3D scene. This parameter is not associated with a Direct3D light object.

Lai is the ambient color of the ith light in the scene. Each Direct3D light has a set of properties, one of which is the ambient color. The term, sum(Lai) is a sum of all the ambient colors in the scene.

Example

In this example, the object is colored using the scene ambient light and a material ambient color.

#define GRAY_COLOR	0x00bfbfbf

// create material
D3DMATERIAL9 mtrl;
ZeroMemory(&mtrl, sizeof(mtrl));
mtrl.Ambient.r = 0.75f;
mtrl.Ambient.g = 0.0f;
mtrl.Ambient.b = 0.0f;
mtrl.Ambient.a = 0.0f;
m_pd3dDevice->SetMaterial(&mtrl);
m_pd3dDevice->SetRenderState(D3DRS_AMBIENT, GRAY_COLOR);

According to the equation, the resulting color for the object vertices is a combination of the material color and the light color.

These two images show the material color, which is gray, and the light color, which is bright red.

The resulting scene is shown below. The only object in the scene is a sphere. Ambient light lights all object vertices with the same color. It is not dependent on the vertex normal or the light direction. As a result, the sphere looks like a 2-D circle because there is no difference in shading around the surface of the object.

Sphere with ambient lighting

To give objects a more realistic look, apply diffuse or specular lighting in addition to ambient lighting.


Diffuse Lighting
Microsoft DirectX 9.0 SDK Update (October 2004)

Diffuse Lighting

After adjusting the light intensity for any attenuation effects, the lighting engine computes how much of the remaining light reflects from a vertex, given the angle of the vertex normal and the direction of the incident light. The lighting engine skips to this step for directional lights because they do not attenuate over distance. The system considers two reflection types, diffuse and specular, and uses a different formula to determine how much light is reflected for each. After calculating the amounts of light reflected, Microsoft Direct3D applies these new values to the diffuse and specular reflectance properties of the current material. The resulting color values are the diffuse and specular components that the rasterizer uses to produce Gouraud shading and specular highlighting.

Diffuse lighting is described by the following equation.

Diffuse Lighting = sum[Cd*Ld*(N.Ldir)*Atten*Spot]

Parameter | Default value | Type | Description
sum | N/A | N/A | Summation of each light's diffuse component.
Cd | (0,0,0,0) | D3DCOLORVALUE | Diffuse color.
Ld | (0,0,0,0) | D3DCOLORVALUE | Light diffuse color.
N | N/A | D3DVECTOR | Vertex normal
Ldir | N/A | D3DVECTOR | Direction vector from object vertex to the light.
Atten | N/A | FLOAT | Light attenuation. See Attenuation and Spotlight Factor.
Spot | N/A | FLOAT | Spotlight factor. See Attenuation and Spotlight Factor.

The value for Cd is either:

  • vertex color1, if DIFFUSEMATERIALSOURCE = D3DMCS_COLOR1, and the first vertex color is supplied in the vertex declaration.
  • vertex color2, if DIFFUSEMATERIALSOURCE = D3DMCS_COLOR2, and the second vertex color is supplied in the vertex declaration.
  • material diffuse color
Note If either DIFFUSEMATERIALSOURCE option is used, and the vertex color is not provided, the material diffuse color is used.

To calculate the attenuation (Atten) or the spotlight characteristics (Spot), see Attenuation and Spotlight Factor.

Diffuse components are clamped to be from 0 to 255, after all lights are processed and interpolated separately. The resulting diffuse lighting value is a combination of the ambient, diffuse and emissive light values.

Example

In this example, the object is colored using the light diffuse color and a material diffuse color. The code is shown below.

D3DMATERIAL9 mtrl;
ZeroMemory( &mtrl, sizeof(mtrl) );

D3DLIGHT9 light;
ZeroMemory( &light, sizeof(light) );
light.Type = D3DLIGHT_DIRECTIONAL;

D3DXVECTOR3 vecDir;
vecDir = D3DXVECTOR3(0.5f, 0.0f, -0.5f);
D3DXVec3Normalize( (D3DXVECTOR3*)&light.Direction, &vecDir );

// set directional light diffuse color
light.Diffuse.r = 1.0f;
light.Diffuse.g = 1.0f;
light.Diffuse.b = 1.0f;
light.Diffuse.a = 1.0f;
m_pd3dDevice->SetLight( 0, &light );
m_pd3dDevice->LightEnable( 0, TRUE );

// if a material is used, SetRenderState must be used
// vertex color = light diffuse color * material diffuse color
mtrl.Diffuse.r = 0.75f;
mtrl.Diffuse.g = 0.0f;
mtrl.Diffuse.b = 0.0f;
mtrl.Diffuse.a = 0.0f;
m_pd3dDevice->SetMaterial( &mtrl );
m_pd3dDevice->SetRenderState(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_MATERIAL);

According to the equation, the resulting color for the object vertices is a combination of the material color and the light color.

These two images show the material color, which is gray, and the light color, which is bright red.

The resulting scene is shown below. The only object in the scene is a sphere. The diffuse lighting calculation takes the material and light diffuse color and modifies it by the angle between the light direction and the vertex normal using the dot product. As a result, the backside of the sphere gets darker as the surface of the sphere curves away from the light.

Diffuse lighting only

Combining the diffuse lighting with the ambient lighting from the previous example shades the entire surface of the object. The ambient light shades the entire surface and the diffuse light helps reveal the object's 3-D shape.

Sphere with diffuse lighting

Diffuse lighting is more intensive to calculate than ambient lighting. Because it depends on the vertex normals and light direction, you can see the objects geometry in 3-D space, which produces a more realistic lighting than ambient lighting. You can use specular highlights to achieve a more realistic look.


Specular Lighting
Microsoft DirectX 9.0 SDK Update (October 2004)

Specular Lighting

Modeling specular reflection requires that the system not only know in what direction light is traveling, but also the direction to the viewer's eye. The system uses a simplified version of the Phong specular-reflection model, which employs a halfway vector to approximate the intensity of specular reflection.

The default lighting state does not calculate specular highlights. To enable specular lighting, be sure to set D3DRS_SPECULARENABLE to TRUE.

Specular Lighting Equation

Specular Lighting is described by the following equation.

Specular Lighting = Cs * sum[Ls * (N • H)P * Atten * Spot]

The following table identifies the variables, their types, and their ranges.

Parameter | Default value | Type | Description
Cs | (0,0,0,0) | D3DCOLORVALUE | Specular color.
sum | N/A | N/A | Summation of each light's specular component.
N | N/A | D3DVECTOR | Vertex normal.
H | N/A | D3DVECTOR | Half way vector. See the section on the halfway vector.
P | 0.0 | FLOAT | Specular reflection power. Range is 0 to +infinity
Ls | (0,0,0,0) | D3DCOLORVALUE | Light specular color.
Atten | N/A | FLOAT | Light attenuation value. See Attenuation and Spotlight Factor.
Spot | N/A | FLOAT | Spotlight factor. See Attenuation and Spotlight Factor.

The value for Cs is either:

if(SPECULARMATERIALSOURCE == D3DMCS_COLOR1)
  C = color1;
  • vertex color1, if the specular material source is D3DMCS_COLOR1 , and the first vertex color is supplied in the vertex declaration.
  • vertex color2, if specular material source is D3DMCS_COLOR2, and the second vertex color is supplied in the vertex declaration.
  • material specular color

Note If either specular material source option is used and the vertex color is not provided, then the material specular color is used.

Specular components are clamped to be from 0 to 255, after all lights are processed and interpolated separately.

The Halfway Vector

The halfway vector (H) exists midway between two vectors: the vector from an object vertex to the light source, and the vector from an object vertex to the camera position. Microsoft Direct3D provides two ways to compute the halfway vector. When D3DRS_LOCALVIEWER is set to TRUE, the system calculates the halfway vector using the position of the camera and the position of the vertex, along with the light's direction vector. The following formula illustrates this.

H = norm(norm(Cp - Vp) + Ldir)

Parameter | Default value | Type | Description
Cp | N/A | D3DVECTOR | Camera position.
Vp | N/A | D3DVECTOR | Vertex position.
Ldir | N/A | D3DVECTOR | Direction vector from vertex position to the light position.

Determining the halfway vector in this manner can be computationally intensive. As an alternative, setting D3DRS_LOCALVIEWER = FALSE instructs the system to act as though the viewpoint is infinitely distant on the z-axis. This is reflected in the following formula.

H = norm((0,0,1) + Ldir)

This setting is less computationally intensive, but much less accurate, so it is best used by applications that use orthogonal projection.

Example

In this example, the object is colored using the scene specular light color and a material specular color. The code is shown below.

D3DMATERIAL9 mtrl;
ZeroMemory( &mtrl, sizeof(mtrl) );

D3DLIGHT9 light;
ZeroMemory( &light, sizeof(light) );
light.Type = D3DLIGHT_DIRECTIONAL;

D3DXVECTOR3 vecDir;
vecDir = D3DXVECTOR3(0.5f, 0.0f, -0.5f);
D3DXVec3Normalize( (D3DXVECTOR3*)&light.Direction, &vecDir );

light.Specular.r = 1.0f;
light.Specular.g = 1.0f;
light.Specular.b = 1.0f;
light.Specular.a = 1.0f;

light.Range = 1000;
light.Falloff = 0;
light.Attenuation0 = 1;
light.Attenuation1 = 0;
light.Attenuation2 = 0;
m_pd3dDevice->SetLight( 0, &light );
m_pd3dDevice->LightEnable( 0, TRUE );
m_pd3dDevice->SetRenderState( D3DRS_SPECULARENABLE, TRUE );

mtrl.Specular.r = 0.5f;
mtrl.Specular.g = 0.5f;
mtrl.Specular.b = 0.5f;
mtrl.Specular.a = 0.5f;
mtrl.Power = 20;
m_pd3dDevice->SetMaterial( &mtrl );
m_pd3dDevice->SetRenderState(D3DRS_SPECULARMATERIALSOURCE, D3DMCS_MATERIAL);

According to the equation, the resulting color for the object vertices is a combination of the material color and the light color.

These two images show the specular material color, which is gray, and the specular light color, which is white.

The resulting specular highlight is shown below.

Specular highlight only

Combining the specular highlight with the ambient and diffuse lighting produces the following image. With all three types of lighting applied, this more clearly resembles a realistic object.

Specular highligh applied

Specular lighting is more intensive to calculate than diffuse lighting. It is typically used to provide visual clues about the surface material. The specular highlight varies in size and color with the material of the surface.


Emissive Lighting
Microsoft DirectX 9.0 SDK Update (October 2004)

Emissive Lighting

Emissive lighting is described by a single term.

Emissive Lighting = Ce

Where:

Parameter | Default value | Type | Description
Ce | (0,0,0,0) | D3DCOLORVALUE | Emissive color.

The value for Ce is either:

  • vertex color1, if EMISSIVEMATERIALSOURCE = D3DMCS_COLOR1, and the first vertex color is supplied in the vertex declaration.
  • vertex color2, if EMISSIVEMATERIALSOURCE = D3DMCS_COLOR2, and the second vertex color is supplied in the vertex declaration.
  • material emissive color
Note If either EMISSIVEMATERIALSOURCE option is used, and the vertex color is not provided, the material emissive color is used.

Example

In this example, the object is colored using the scene ambient light and a material ambient color. The code is shown below.

// create material
D3DMATERIAL9 mtrl;
ZeroMemory( &mtrl, sizeof(mtrl) );
mtrl.Emissive.r = 0.0f;
mtrl.Emissive.g = 0.75f;
mtrl.Emissive.b = 0.0f;
mtrl.Emissive.a = 0.0f;
m_pd3dDevice->SetMaterial( &mtrl );
m_pd3dDevice->SetRenderState(D3DRS_EMISSIVEMATERIALSOURCE, D3DMCS_MATERIAL);

According to the equation, the resulting color for the object vertices is the material color.

The image below shows the material color, which is green. Emissive light lights all object vertices with the same color. It is not dependent on the vertex normal or the light direction. As a result, the sphere looks like a 2-D circle because there is no difference in shading around the surface of the object.

This image shows how the emissive light blends with the other three types of lights, from the previous examples. On the right side of the sphere, there is a blend of the green emissive and the red ambient light. On the left side of the sphere, the green emissive light blends with red ambient and diffuse light producing a red gradient. The specular highlight is white in the center and creates a yellow ring as the specular light value falls off sharply leaving the ambient, diffuse and emissive light values which blend together to make yellow.

Green sphere with emissive light


Camera Space Transformations
Microsoft DirectX 9.0 SDK Update (October 2004)

Camera Space Transformations

Vertices in the camera space are computed by transforming the object vertices with the world view matrix.

V = V * wvMatrix

Vertex normals, in camera space, are computed by transforming the object normals with the inverse transpose of the world view matrix. The world view matrix may or may not be orthogonal.

N = N * (wvMatrix-1)T

The matrix inversion and matrix transpose operate on a 4x4 matrix. The multiply combines the normal with the 3x3 portion of the resulting 4x4 matrix.

If the render state, D3DRENDERSTATE_NORMALIZENORMALS is set to TRUE, vertex normal vectors are normalized after transformation to camera space as follows:

N = norm(N)

Light position in camera space is computed by transforming the light source position with the view matrix.

Lp = Lp * vMatrix

The direction to the light in camera space for a directional light is computed by multiplying the light source direction by the view matrix, normalizing, and negating the result.

Ldir = -norm(Ldir * wvMatrix)

For the D3DLIGHT_POINT and D3DLIGHT_SPOT the direction to light is computed as follows:

Ldir = norm(V * Lp), where the parameters are defined in the following table.

Parameter | Default value | Type | Description
Ldir | N/A | D3DVECTOR | Direction vector from object vertex to the light
V | N/A | D3DVECTOR | Vertex position in camera space
wvMatrix | Identity | D3DMATRIX | Composite matrix containing the world and view transforms
N | N/A | D3DVECTOR | Vertex normal
Lp | N/A | D3DVECTOR | Light position in camera space
vMatrix | Identity | D3DMATRIX | Matrix containing the view transform


Attenuation and Spotlight Factor
Microsoft DirectX 9.0 SDK Update (October 2004)

Attenuation and Spotlight Factor

The diffuse and specular lighting components of the global illumination equation contain terms that describe light attenuation and the spotlight cone. These terms are described below.

Attenuation

The attenuation of a light depends on the type of light and the distance between the light and the vertex position. To calculate attenuation, use one of the following equations.

Atten = 1/( att0i + att1i * d + att2i * d2)

Where:

Parameter | Default value | Type | Description | Range
att0i | 0.0 | FLOAT | Constant attenuation factor | 0 to +infinity
att1i | 0.0 | FLOAT | Linear attenuation factor | 0 to +infinity
att2i | 0.0 | FLOAT | Quadratic attenuation factor | 0 to +infinity
d | N/A | FLOAT | Distance from vertex position to light position | N/A
  • Atten = 1, if the light is a directional light.
  • Atten = 0, if the distance between the light and the vertex exceeds the light's range.

The att0, att1, att2 values are specified by the Attenuation0, Attenuation1, and Attenuation2 members of D3DLIGHT9.

The distance between the light and the vertex position is always positive.

d = | Ldir |

Where:

Parameter | Default value | Type | Description
Ldir | N/A | D3DVECTOR | Direction vector from vertex position to the light position

If d is greater than the light's range, that is, the Range member of a D3DLIGHT9 structure, Microsoft Direct3D makes no further attenuation calculations and applies no effects from the light to the vertex.

The attenuation constants act as coefficients in the formula—you can produce a variety of attenuation curves by making simple adjustments to them. You can set Attenuation1 to 1.0 to create a light that doesn't attenuate but is still limited by range, or you can experiment with different values to achieve various attenuation effects.

The attenuation at the maximum range of the light is not 0.0. To prevent lights from suddenly appearing when they are at the light range, an application can increase the light range. Or, the application can set up attenuation constants so that the attenuation factor is close to 0.0 at the light range. The attenuation value is multiplied by the red, green, and blue components of the light's color to scale the light's intensity as a factor of the distance light travels to a vertex.

Spotlight Factor

Formula for spotlight factor

Parameter | Default value | Type | Description | Range
rhoi | N/A | FLOAT | cosine(angle) for spotlight i | N/A
phii | 0.0 | FLOAT | Penumbra angle of spotlight i in radians | [thetai, pi)
thetai | 0.0 | FLOAT | Umbra angle of spotlight i in radians | [0, pi)
falloff | 0.0 | FLOAT | Falloff factor | (-infinity, +infinity)

Where:

rho = norm(Ldcs).norm(Ldir)

and:

Parameter | Default value | Type | Description
Ldcs | N/A | D3DVECTOR | The negative of the light direction in camera space
Ldir | N/A | D3DVECTOR | Direction vector from vertex position to the light position

After computing the light attenuation, Direct3D also considers spotlight effects if applicable, the angle that the light reflects from a surface, and the reflectance of the current material to calculate the diffuse and specular components for that vertex. For more information, see SpotLight.


Materials
Microsoft DirectX 9.0 SDK Update (October 2004)

Materials

Materials describe how polygons reflect light or appear to emit light in a 3-D scene. Material properties detail a material's diffuse reflection, ambient reflection, light emission, and specular highlight characteristics. Microsoft Direct3D uses the D3DMATERIAL9 structure to carry all material property information. With the exception of the specular property, each property is described as an RGBA color that represents how much of the red, green, and blue parts of a given type of light it reflects, and an alpha blending factor.

Diffuse and Ambient Reflection

The Diffuse and Ambient members of the D3DMATERIAL9 structure describe how a material reflects the ambient and diffuse light in a scene. Because most scenes contain much more diffuse light than ambient light, diffuse reflection plays the largest part in determining color. Additionally, because diffuse light is directional, the angle of incidence for diffuse light affects the overall intensity of the reflection. Diffuse reflection is greatest when the light strikes a vertex parallel to the vertex normal. As the angle increases, the effect of diffuse reflection diminishes. The amount of light reflected is the cosine of the angle between the incoming light and the vertex normal, as shown here.

Ambient reflection, like ambient light, is nondirectional. Ambient reflection has a lesser impact on the apparent color of a rendered object, but it does affect the overall color and is most noticeable when little or no diffuse light reflects off the material. A material's ambient reflection is affected by the ambient light set for a scene by calling the IDirect3DDevice9::SetRenderState method with the D3DRS_AMBIENT flag.

Diffuse and ambient reflection work together to determine the perceived color of an object, and are usually identical values. For example, to render a blue crystalline object, you create a material that reflects only the blue component of diffuse and ambient light. When placed in a room with a white light, the crystal appears to be blue. However, in a room that has only red light, the same crystal would appear to be black, because its material doesn't reflect red light.

Emission

Materials can be used to make a rendered object appear to be self-luminous. The Emissive member of the D3DMATERIAL9 structure is used to describe the color and transparency of the emitted light. Emission affects an object's color and can, for example, make a dark material brighter and take on part of the emitted color.

You can use a material's emissive property to add the illusion that an object is emitting light, without incurring the computational overhead of adding a light to the scene. In the case of the blue crystal, the emissive property is useful if you want to make the crystal appear to light up, but not cast light on other objects in the scene. Remember, materials with emissive properties don't emit light that can be reflected by other objects in a scene. To achieve this reflected light, you need to place an additional light within the scene.

Specular Reflection

Specular reflection creates highlights on objects, making them appear shiny. The D3DMATERIAL9 structure contains two members that describe the specular highlight color as well as the material's overall shininess. You establish the color of the specular highlights by setting the Specular member to the desired RGBA color—the most common colors are white or light gray. The values you set in the Power member control how sharp the specular effects are.

Specular highlights can create dramatic effects. Drawing again on the blue crystal analogy: a larger Power value creates sharper specular highlights, making the crystal appear to be quite shiny. Smaller values increase the area of the effect, creating a dull reflection that make the crystal look frosty. To make an object truly matte, set the Power member to zero and the color in Specular to black. Experiment with different levels of reflection to produce a realistic appearance for your needs. The following illustration shows two identical models. The one on the left uses a specular reflection power of 10; the model on the right has no specular reflection.

Specular reflection models

Setting Material Properties

Direct3D rendering devices can render with one set of material properties at a time.

In a C++ application, you set the material properties that the system uses by preparing a D3DMATERIAL9 structure, and then calling the IDirect3DDevice9::SetMaterial method.

To prepare the D3DMATERIAL9 structure for use, set the property information in the structure to create the desired effect during rendering. The following code example sets up the D3DMATERIAL9 structure for a purple material with sharp white specular highlights.

D3DMATERIAL9 mat;

// Set the RGBA for diffuse reflection.
mat.Diffuse.r = 0.5f;
mat.Diffuse.g = 0.0f;
mat.Diffuse.b = 0.5f;
mat.Diffuse.a = 1.0f;

// Set the RGBA for ambient reflection.
mat.Ambient.r = 0.5f;
mat.Ambient.g = 0.0f;
mat.Ambient.b = 0.5f;
mat.Ambient.a = 1.0f;

// Set the color and sharpness of specular highlights.
mat.Specular.r = 1.0f;
mat.Specular.g = 1.0f;
mat.Specular.b = 1.0f;
mat.Specular.a = 1.0f;
mat.Power = 50.0f;

// Set the RGBA for emissive color.
mat.Emissive.r = 0.0f;
mat.Emissive.g = 0.0f;
mat.Emissive.b = 0.0f;
mat.Emissive.a = 0.0f;

After preparing the D3DMATERIAL9 structure, you apply the properties by calling the IDirect3DDevice9::SetMaterial method of the rendering device. This method accepts the address of a prepared D3DMATERIAL9 structure as its only parameter. You can call IDirect3DDevice9::SetMaterial with new information as needed to update the material properties for the device. The following code example shows how this might look in code.

// This code example uses the material properties defined for
// the mat variable earlier in this topic. The pd3dDev is assumed
// to be a valid pointer to an IDirect3DDevice9 interface.
HRESULT hr;
hr = pd3dDev->SetMaterial(&mat);
if(FAILED(hr))
{
    // Code to handle the error goes here.
}

When you create a Direct3D device, the current material is automatically set to the default shown in the following table.

Member | Value
Diffuse | (R:1, G:1, B:1, A:0)
Specular | (R:0, G:0, B:0, A:0)
Ambient | (R:0, G:0, B:0, A:0)
Emissive | (R:0, G:0, B:0, A:0)
Power | (0.0)

Retrieving Material Properties

You retrieve the material properties that the rendering device is currently using by calling the IDirect3DDevice9::GetMaterial method for the device. Unlike the IDirect3DDevice9::SetMaterial method, IDirect3DDevice9::GetMaterial doesn't require preparation. The IDirect3DDevice9::GetMaterial method accepts the address of a D3DMATERIAL9 structure, and fills the provided structure with information describing the current material properties before returning.

// For this example, the pd3dDev variable is assumed to
// be a valid pointer to an IDirect3DDevice9 interface.
HRESULT hr;
D3DMATERIAL9 mat;

hr = pd3dDev->GetMaterial(&mat);
if(FAILED(hr))
{
    // Code to handle the error goes here.
}
Note If your application does not specify material properties for rendering, the system uses a default material. The default material reflects all diffuse light—white, for example—with no ambient or specular reflection, and no emissive color.


Direct3D Rendering
Microsoft DirectX 9.0 SDK Update (October 2004)

Direct3D Rendering

Applications use the DrawPrimitive family of methods to render a 3-D scene.

  • Shading
  • Presenting a Scene
  • Rendering Primitives
  • Depth Buffers
  • Fog
  • Alpha Blending
  • Line Drawing Support in D3DX


Shading
Microsoft DirectX 9.0 SDK Update (October 2004)

Shading

This section describes techniques used in Microsoft Direct3D to control the shading of 3-D polygons.

  • Shading Modes
  • Comparing Shading Modes
  • Setting the Shading Mode


Shading Modes
Microsoft DirectX 9.0 SDK Update (October 2004)

Shading Modes

The shading mode used to render a polygon has a profound effect on its appearance. Shading modes determine the intensity of color and lighting at any point on a polygon face. Microsoft Direct3D supports two shading modes.

  • Flat Shading
  • Gouraud Shading

Flat Shading

In the flat shading mode, the Direct3D rendering pipeline renders a polygon, using the color of the polygon material at its first vertex as the color for the entire polygon. 3-D objects that are rendered with flat shading have visibly sharp edges between polygons if they are not coplanar.

The following figure shows a teapot rendered with flat shading. The outline of each polygon is clearly visible. Flat shading is the fastest form of shading.

Rough image of teapot

Gouraud Shading

When Direct3D renders a polygon using Gouraud shading, it computes a color for each vertex by using the vertex normal and lighting parameters. Then, it interpolates the color across the face of the polygons The interpolation is done linearly. For example, if the red component of the color of vertex 1 is 0.8 and the red component of vertex 2 is 0.4, using the Gouraud shading mode and the RGB color model, the Direct3D lighting module assigns a red component of 0.6 to the pixel at the midpoint of the line between these vertices.

The following figure demonstrates Gouraud shading. This teapot is composed of many flat, triangular polygons. However, Gouraud shading makes the surface of the object appear curved and smooth.

Smooth imaage of teapot

Gouraud shading can also be used to display objects with sharp edges.

For more information, see Face and Vertex Normal Vectors.


Comparing Shading Modes
Microsoft DirectX 9.0 SDK Update (October 2004)

Comparing Shading Modes

In flat shading mode, the pyramid below is displayed with a sharp edge between adjoining faces. In Gouraud shading mode, however, shading values are interpolated across the edge, and the final appearance is of a curved surface.

Automatic face normals

Gouraud shading lights flat surfaces more realistically than flat shading. A face in the flat shading mode is a uniform color, but Gouraud shading enables light to fall across a face more correctly. This effect is particularly obvious if there is a nearby point source.

Gouraud shading smoothes the sharp edges between polygons that are visible with flat shading. However, it can result in Mach bands, which are bands of color or light that are not smoothly blended across adjacent polygons. Your application can reduce the appearance of Mach bands by increasing the number of polygons in an object, increasing screen resolution, or increasing the color depth of the application.

Gouraud shading can miss some details. One example is the case shown by the following illustration, in which a spotlight is completely contained within a polygon face.

In this case, Gouraud shading, which interpolates between vertices, would miss the spotlight altogether; the face would be rendered as though the spotlight did not exist.


Setting the Shading Mode
Microsoft DirectX 9.0 SDK Update (October 2004)

Setting the Shading Mode

Microsoft Direct3D enables one shading mode to be selected at a time. By default, Gouraud shading is selected. In C++, you can change the shading mode by calling the IDirect3DDevice9::SetRenderState method. Set the State parameter to D3DRS_SHADEMODE. The State parameter must be set to a member of the D3DSHADEMODE enumeration. The following sample code examples illustrate how the current shading mode of a Direct3D application can be set to flat or Gouraud shading mode.

// Set to flat shading.
// This code example assumes that pDev is a valid pointer to
// an IDirect3DDevice9 interface.
hr = pDev->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_FLAT);
if(FAILED(hr))
{
    // Code to handle the error goes here.
}

// Set to Gouraud shading. This is the default for Direct3D.
hr = pDev->SetRenderState(D3DRS_SHADEMODE,
                            D3DSHADE_GOURAUD);
if(FAILED(hr))
{
    // Code to handle the error goes here.
}


Presenting a Scene
Microsoft DirectX 9.0 SDK Update (October 2004)

Presenting a Scene

This section introduces the presentation application programming interfaces (APIs) and discusses the issues involved in presenting a scene to the display.

Information is divided into the following topics.

  • Introduction to Presenting a Scene
  • Multiple Views in Windowed Mode
  • Multiple-Monitor Operations
  • Manipulating the Depth Buffer
  • Accessing the Color Front Buffer


Introduction to Presenting a Scene
Microsoft DirectX 9.0 SDK Update (October 2004)

Introduction to Presenting a Scene

The presentation application programming interfaces (APIs) are a set of methods that control the state of the device that affects what the user sees on the monitor. These methods include setting display modes and once-per-frame methods that are used to present images to the user.

  • IDirect3DDevice9::Present
  • IDirect3DDevice9::Reset
  • IDirect3DDevice9::GetGammaRamp
  • IDirect3DDevice9::SetGammaRamp
  • IDirect3DDevice9::GetRasterStatus

Familiarity with the following terms is necessary to understand the presentation APIs.

  • front buffer. A rectangle of memory that is translated by the graphics adapter and displayed on the monitor or other output device.
  • back buffer. A surface whose contents can be promoted to the front buffer.
  • swap chain. A collection of back buffers that can be serially presented to the front buffer. Typically, a full-screen swap chain presents subsequent images with the flipping device driver interface (DDI), and a windowed swap chain presents images with the blitting DDI.

Because Microsoft Direct3D for Microsoft DirectX 9.0 has one swap chain as a property of the device, there is always at least one swap chain per device. The IDirect3DDevice9 interface has a set of methods that manipulate the implicit swap chain and are a copy of the swap chain's own interface. Applications can create additional swap chains; however, this is not necessary for the typical single window or full-screen application.

The front buffer is not directly exposed in the Direct3D API for DirectX 9.0. As a result, applications cannot lock or render to the front buffer. For details, see Accessing the Color Front Buffer.

Note DirectX 7.0 provided a number of presentation APIs that were called together. A good example of this is the IDirectDraw7::SetCooperativeLevel, IDirectDraw7::SetDisplayMode, and IDirectDraw7::CreateSurface sequence. Additionally, the IDirectDrawSurface7::Flip and IDirectDrawSurface7::Blt methods signaled the transport of rendered frames to the monitor. DirectX 9.0 collapses these groups of APIs into two main methods, Reset and Present. Reset subsumes SetCooperativeLevel, SetDisplayMode, CreateSurface, and some of the parameters to flip. Present subsumes flip and the presentation uses of blit.

A call to IDirect3D9::CreateDevice represents an implicit reset of the device. The DirectX 9.0 API has no notion of a primary surface; you cannot create an object that represents the primary surface. It is considered to be an internal property of the device.

Gamma ramps are associated with a swap chain and are manipulated with the IDirect3DDevice9::GetGammaRamp and IDirect3DDevice9::SetGammaRamp methods.


Multiple Views in Windowed Mode
Microsoft DirectX 9.0 SDK Update (October 2004)

Multiple Views in Windowed Mode

In addition to the swap chain that is owned and manipulated through the Direct3DDevice object, an application can use the IDirect3DDevice9::CreateAdditionalSwapChain method to create additional swap chains to present multiple views from the same device.

Typically, the application creates one swap chain per view, and it associates each swap chain with a particular view. The application renders images in the back buffers of each swap chain, and then uses the IDirect3DDevice9::Present method to present them individually. Note that only one swap chain at a time can be full-screen on each adapter.


Multiple-Monitor Operations
Microsoft DirectX 9.0 SDK Update (October 2004)

Multiple-Monitor Operations

When a device is successfully reset (IDirect3DDevice9::Reset) or created (IDirect3D9::CreateDevice) in full-screen operations, the Microsoft Direct3D object that created the device is marked as owning all adapters on that system. This state is known as exclusive mode, and the Direct3D object owns exclusive mode. Exclusive mode means that devices created by any other Direct3D object can neither assume full-screen operations nor allocate video memory. In addition, when a Direct3D object assumes exclusive mode, all devices other than the one that went full-screen are placed in lost state. For details, see Lost Devices.

Along with exclusive mode, the Direct3D object is informed of the focus window that the device will use. Exclusive mode is released when the final full-screen device owned by that Direct3D object is either reset to windowed mode or destroyed.

Devices can be divided into two categories when a Direct3D object owns exclusive mode. The first category of devices have the following characteristics.

  • They are created by the same Direct3D object that created the device that is full-screen.
  • They have the same focus window as the device that is full-screen.
  • They represent a different adapter from any full-screen device.

Devices in this category have no restrictions concerning their ability to be reset or created, and they are not placed in lost state. Devices in this category can even be put into full-screen mode.

Devices that do not fall in the first category—devices created by another Direct3D object, created with a different focus window, and created for an adapter with a device that is already full-screen—cannot be reset and remain in lost state until the exclusive mode is lost. As a result, a multiple-monitor application can place several devices in full-screen mode, but only if all these devices are for different adapters, were created by the same Direct3D object, and share the same focus window.


Manipulating the Depth Buffer
Microsoft DirectX 9.0 SDK Update (October 2004)

Manipulating the Depth Buffer

Depth buffers are associated with the device. Applications are required to move the depth buffers when they set render targets. The IDirect3DDevice9::GetDepthStencilSurface and IDirect3DDevice9::SetDepthStencilSurface methods are used to manipulate depth buffers.


Accessing the Color Front Buffer
Microsoft DirectX 9.0 SDK Update (October 2004)

Accessing the Color Front Buffer

Accessing the front buffer is allowed through the IDirect3DDevice9::GetFrontBufferData method. This method is the only way to get a screen shot of an anti-aliased scene.


Rendering Primitives
Microsoft DirectX 9.0 SDK Update (October 2004)

Rendering Primitives

The following topics provide information about drawing primitives in your application.

  • Vertex Data Streams
  • Setting the Stream Source
  • Rendering from Vertex and Index Buffers
  • Rendering from User Memory Pointers


Vertex Data Streams
Microsoft DirectX 9.0 SDK Update (October 2004)

Vertex Data Streams

The rendering interfaces for Microsoft Direct3D consist of methods that render primitives from vertex data stored in one or more data buffers. Vertex data consists of vertex elements combined to form vertex components. Vertex elements, the smallest unit of a vertex, represent entities such as position, normal, or color.

Vertex components are one or more vertex elements stored contiguously (interleaved per vertex) in a single memory buffer. A complete vertex consists of one or more components, where each component is in a separate memory buffer. To render a primitive, multiple vertex components are read and assembled so that complete vertices are available for vertex processing. The illustration below shows the process of rendering primitives using vertex components.

Rendering primitives consists of two steps. First, set up one or more vertex component streams; second, invoke a IDirect3DDevice9::DrawPrimitive method to render from those streams. Identification of vertex elements within these component streams is specified by the vertex shader.

The IDirect3DDevice9::DrawPrimitive methods specify an offset in the vertex data streams so that an arbitrary contiguous subset of the primitives within one set of vertex data can be rendered with each draw invocation. This enables you to change the device rendering state between groups of primitives that are rendered from the same vertex buffers.

Both indexed and nonindexed drawing methods are supported. For more information, see Rendering from Vertex and Index Buffers.


Setting the Stream Source
Microsoft DirectX 9.0 SDK Update (October 2004)

Setting the Stream Source

The IDirect3DDevice9::SetStreamSource method binds a vertex buffer to a device data stream, creating an association between the vertex data and one of several data stream ports that feed the primitive processing functions. The actual references to the stream data do not occur until a drawing method, such as IDirect3DDevice9::DrawPrimitive, is called.

A stream is defined as a uniform array of component data, where each component consists of one or more elements representing a single entity such as position, normal, color, and so on. The Stride parameter specifies the size of the component, in bytes.


Rendering from Vertex and Index Buffers
Microsoft DirectX 9.0 SDK Update (October 2004)

Rendering from Vertex and Index Buffers

Both indexed and nonindexed drawing methods are supported by Microsoft Direct3D. The indexed methods use a single set of indices for all vertex components. Vertex data is stored in vertex buffers, and index data is stored in index buffers. Listed below are a few common scenarios for drawing primitives using vertex sand index buffers. These examples compare the use of IDirect3DDevice9::DrawPrimitive and IDirect3DDevice9::DrawIndexedPrimitive

Scenario 1: Drawing Two Triangles without Indexing

Let's say you want to draw this quad:

If you use the Triangle List primitive type to render the two triangles, each triangle will be stored as 3 individual vertices, resulting in a similar vertex buffer to this:

The drawing call is very straight-forward; starting at location 0 within the vertex buffer, draw two triangles. If culling is enabled, the order of the vertices will be important. This example assumes the default counter-clockwise culling state, so visible triangles must be drawn in clockwise order. The Triangle List primitive type simply reads three vertices in linear order from the buffer for each triangle, so this call will draw triangles (0, 1, 2) and (3, 4, 5):

DrawPrimitive( D3DPT_TRIANGLELIST, // PrimitiveType
               0,                  // StartVertex
               2 );                // PrimitiveCount

Scenario 2: Drawing Two Triangles with Indexing

As you'll notice, the vertex buffer contains duplicate data in locations 0 and 4, 2 and 5. That makes sense because the two triangles share two common vertices. This duplicate data is wasteful, and the vertex buffer can be compressed by using an index buffer. A smaller vertex buffer reduces the amount of vertex data that has to be sent to the graphics adapter. Even more importantly, using an index buffer allows the adapter to store vertices in a vertex cache; if the primitive being drawn contains a recently-used vertex, that vertex can be fetched from the cache instead of reading it from the vertex buffer, which results in a big performance increase.

An index buffer 'indexes' into the vertex buffer so each unique vertex needs to be stored only once in the vertex buffer. Here is an indexed approach to the drawing scenario above:

The index buffer stores VB Index values, which reference a particular vertex within the vertex buffer. A vertex buffer can be thought of as an array of vertices, so the VB Index is simply the index into the vertex buffer for the target vertex. Similarly, an IB Index is an index into the index buffer. This can get very confusing very quickly if you're not careful, so make sure you're clear on the vocabulary being used: VB Index values index into the vertex buffer, IB Index values index into the index buffer, and the index buffer itself stores VB Index values.

The drawing call is shown below. The meanings of all the arguments are discussed at length for the next drawing scenario; for now, just note that this call is again instructing Direct3D to render a triangle list containing two triangles, starting at location 0 within the index buffer. This call will draw the same two triangles in the exact same order as before, ensuring a proper clockwise orientation:

DrawIndexPrimitive( D3DPT_TRIANGLELIST, // PrimitiveType
                    0,                  // BaseVertexIndex
                    0,                  // MinIndex
                    4,                  // NumVertices
                    0,                  // StartIndex
                    2 );                // PrimitiveCount

Scenario 3: Drawing One Triangle with Indexing

Pretend now that you only want to draw the second triangle, but you want to use the same vertex buffer and index buffer used when drawing the entire quad:

For this drawing call, the first IB Index used is 3; this value is called the StartIndex. The lowest VB Index used is 0; this value is called the MinIndex. Even though only three vertices are required to draw the triangle, those three vertices are spread across four adjacent locations in the vertex buffer; the number of locations within the contiguous block of vertex buffer memory required for the drawing call is called NumVertices, and will be set to 4 in this call. The MinIndex and NumVertices values are really just hints to help Direct3D optimize memory access during software vertex processing, and could simply be set to include the entire vertex buffer at the price of performance.

Here is the drawing call for the single triangle case; the meaning of the BaseVertexIndex argument will be explained next:

DrawIndexPrimitive( D3DPT_TRIANGLELIST, // PrimitiveType
                    0,                  // BaseVertexIndex
                    0,                  // MinIndex
                    4,                  // NumVertices
                    3,                  // StartIndex
                    1 );                // PrimitiveCount

Scenario 4: Drawing One Triangle with Offset Indexing

BaseVertexIndex is a value that's effectively added to every VB Index stored in the index buffer. For example, if we had passed in a value of 50 for BaseVertexIndex during the previous call, that would functionally be the same as using the following index buffer for the duration of the DrawIndexedPrimitive call:

This value is rarely set to anything other than 0, but can be useful if you want to decouple the index buffer from the vertex buffer: If when filling in the index buffer for a particular mesh the location of the mesh within the vertex buffer isn't yet known, you can simply pretend the mesh vertices will be located at the start of the vertex buffer; when it comes time to make the draw call, simply pass the actual starting location as the BaseVertexIndex.

This technique can also be used when drawing multiple instances of a mesh using a single index buffer; for example, if the vertex buffer contained two meshes with identical draw order but slightly different vertices (perhaps different diffuse colors or texture coordinates), both meshes could be drawn by using different values for BaseVertexIndex. Taking this concept one step further, you could use one index buffer to draw multiple instances of a mesh, each contained in a different vertex buffer, simply by cycling which vertex buffer is active and adjusting the BaseVertexIndex as needed. Note that the BaseVertexIndex value is also automatically added to the MinIndex argument, which makes sense when you see how it's used:

Pretend now that we again want to draw only the second triangle of the quad using the same index buffer as before; however, a different vertex buffer is being used in which the quad is located at VB Index 50. The relative order of the quad vertices remains unchanged, only the starting location within the vertex buffer is different. The index buffer and vertex buffer would look like this:

Here is the appropriate draw call; note that BaseVertexIndex is the only value which has changed from the previous scenario:

DrawIndexPrimitive( D3DPT_TRIANGLELIST, // PrimitiveType
                    50,                 // BaseVertexIndex
                    0,                  // MinIndex
                    4,                  // NumVertices
                    3,                  // StartIndex
                    1 );                // PrimitiveCount


Rendering from User Memory Pointers
Microsoft DirectX 9.0 SDK Update (October 2004)

Rendering from User Memory Pointers

A secondary set of rendering interfaces supports passing vertex and index data directly from user memory pointers. These interfaces support a single stream of vertex data only. For more information, see the following reference topics.

  • IDirect3DDevice9::DrawPrimitiveUP
  • IDirect3DDevice9::DrawIndexedPrimitiveUP

These methods render with data specified by user memory pointers, instead of vertex and index buffers.


Depth Buffers
Microsoft DirectX 9.0 SDK Update (October 2004)

Depth Buffers

A depth buffer, often called a z-buffer or a w-buffer, is a property of the device that stores depth information to be used by Microsoft Direct3D. When Direct3D renders a scene to a target surface, it can use the memory in an associated depth-buffer surface as a workspace to determine how the pixels of rasterized polygons occlude one another. Direct3D uses an off-screen Direct3D surface as the target to which final color values are written. The depth-buffer surface that is associated with the render-target surface is used to store depth information that tells Direct3D how deep each visible pixel is in the scene.

When a scene is rasterized with depth buffering enabled, each point on the rendering surface is tested. The values in the depth buffer can be a point's z-coordinate or its homogeneous w-coordinate—from the point's (x,y,z,w) location in projection space. A depth buffer that uses z values is often called a z-buffer, and one that uses w values is called a w-buffer. Each type of depth buffer has advantages and disadvantages, which are discussed later.

At the beginning of the test, the depth value in the depth buffer is set to the largest possible value for the scene. The color value on the rendering surface is set to either the background color value or the color value of the background texture at that point. Each polygon in the scene is tested to see if it intersects with the current coordinate (x,y) on the rendering surface. If it does, the depth value—which will be the z coordinate in a z-buffer, and the w coordinate in a w-buffer—at the current point is tested to see if it is smaller than the depth value stored in the depth buffer. If the depth of the polygon value is smaller, it is stored in the depth buffer and the color value from the polygon is written to the current point on the rendering surface. If the depth value of the polygon at that point is larger, the next polygon in the list is tested. This process is shown in the following illustration.

Note Although most applications don't use this feature, you can change the comparison that Direct3D uses to determine which values are placed in the depth buffer and subsequently the render-target surface. To do so, change the value for the D3DRS_ZFUNC render state. On some hardware, changing the compare function may disable hierarchical z testing.

Nearly all accelerators on the market support z-buffering, making z-buffers the most common type of depth buffer today. However ubiquitous, z-buffers have their drawbacks. Due to the mathematics involved, the generated z values in a z-buffer tend not to be distributed evenly across the z-buffer range (typically 0.0 to 1.0, inclusive). Specifically, the ratio between the far and near clipping planes strongly affects how unevenly z values are distributed. Using a far-plane distance to near-plane distance ratio of 100, 90 percent of the depth buffer range is spent on the first 10 percent of the scene depth range. Typical applications for entertainment or visual simulations with exterior scenes often require far-plane/near-plane ratios of anywhere between 1,000 to 10,000. At a ratio of 1,000, 98 percent of the range is spent on the first 2 percent of the depth range, and the distribution becomes worse with higher ratios. This can cause hidden surface artifacts in distant objects, especially when using 16-bit depth buffers, the most commonly supported bit-depth.

A w-based depth buffer, on the other hand, is often more evenly distributed between the near and far clip planes than a z-buffer. The key benefit is that the ratio of distances for the far and near clipping planes is no longer an issue. This allows applications to support large maximum ranges, while still getting relatively accurate depth buffering close to the eye point. A w-based depth buffer isn't perfect, and can sometimes exhibit hidden surface artifacts for near objects. Another drawback to the w-buffered approach is related to hardware support: w-buffering isn't supported as widely in hardware as z-buffering.

Using a z-buffer requires overhead during rendering. Various techniques can be used to optimize rendering when using z-buffers. For details, see Z-Buffer Performance.

Note The actual interpretation of a depth value is specific to the renderer.

This section presents information about using depth buffers for hidden line and hidden surface removal.

  • Querying for Depth Buffer Support
  • Creating a Depth Buffer
  • Enabling Depth Buffering
  • Retrieving a Depth Buffer
  • Clearing Depth Buffers
  • Changing Depth Buffer Write Access
  • Changing Depth Buffer Comparison Functions


Querying for Depth Buffer Support
Microsoft DirectX 9.0 SDK Update (October 2004)

Querying for Depth Buffer Support

As with any feature, the driver that your application uses might not support all types of depth buffering. Always check the driver's capabilities. Although most drivers support z-based depth buffering, not all will support w-based depth buffering. Drivers do not fail if you attempt to enable an unsupported scheme. They fall back on another depth buffering method instead, or sometimes disable depth buffering altogether, which can result in scenes rendered with extreme depth-sorting artifacts.

You can check for general support for depth buffers by querying Microsoft Direct3D for the display device that your application will use before you create a Direct3D device. If the Direct3D object reports that it supports depth buffering, any hardware devices you create from this Direct3D object will support z-buffering.

To query for depth buffering support, you can use the IDirect3D9::CheckDeviceFormat method, as shown in the following code example.

// The following example assumes that pCaps is a valid pointer to an
// initialized D3DCAPS9 structure
if(FAILED(m_pD3D->CheckDeviceFormat(pCaps->AdapterOrdinal,
                                           pCaps->DeviceType,
                                           AdapterFormat,
                                           D3DUSAGE_DEPTHSTENCIL,
                                           D3DRTYPE_SURFACE,
                                           D3DFMT_D16)))
    return E_FAIL;

IDirect3D9::CheckDeviceFormat allows you to choose a device to create based on the capabilities of that device. In this case, devices that do not support 16-bit depth buffers are rejected.

Using IDirect3D9::CheckDepthStencilMatch to determine depth-stencil compatibility with a render target is illustrated in the following code example.

// Reject devices that cannot create a render target of RTFormat while
// the back buffer is of RTFormat and the depth-stencil buffer is
// at least 8 bits of stencil
if(FAILED(m_pD3D->CheckDepthStencilMatch(pCaps->AdapterOrdinal,
                                            pCaps->DeviceType,
                                            AdapterFormat,
                                            RTFormat,
                                            D3DFMT_D24S8)))
    return E_FAIL;

When you know that the driver supports depth buffers, you can verify w-buffer support. Although depth buffers are supported for all software rasterizers, w-buffers are supported only by the reference rasterizer, which is not suited for use by real-world applications. Regardless of the type of device your application uses, verify support for w-buffers before you attempt to enable w-based depth buffering.

  1. After creating your device, call the IDirect3DDevice9::GetDeviceCaps method, passing an initialized D3DCAPS9 structure.
  2. After the call, the LineCaps member contains information about the driver's support for rendering primitives.
  3. If the RasterCaps member of this structure contains the D3DPRASTERCAPS_WBUFFER flag, then the driver supports w-based depth buffering for that primitive type.


Creating a Depth Buffer
Microsoft DirectX 9.0 SDK Update (October 2004)

Creating a Depth Buffer

A depth buffer is a property of the device. To create a depth buffer that is managed by Microsoft Direct3D, set the appropriate members of the D3DPRESENT_PARAMETERS structure as shown in the following code example.

D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory( &d3dpp, sizeof(d3dpp) );
d3dpp.Windowed               = TRUE;
d3dpp.SwapEffect             = D3DSWAPEFFECT_COPY;
d3dpp.EnableAutoDepthStencil = TRUE;
d3dpp.AutoDepthStencilFormat = D3DFMT_D16;

By setting the EnableAutoDepthStencil member to TRUE, you instruct Direct3D to manage depth buffers for the application. Note that AutoDepthStencilFormat must be set to a valid depth buffer format. The D3DFMT_D16 flag specifies a 16-bit depth buffer, if one is available.

The following call to the IDirect3D9::CreateDevice method creates a device that then creates a depth buffer.

if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                                    D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                    &d3dpp, &d3dDevice ) ) )
return E_FAIL;

The depth buffer is automatically set as the render target of the device. When the device is reset, the depth buffer is automatically destroyed and re-created in the new size.

To create a new depth buffer surface, use the IDirect3DDevice9::CreateDepthStencilSurface method.

To set a new depth-buffer surface for the device, use the IDirect3DDevice9::SetDepthStencilSurface method.

To use the depth buffer in your application, you need to enable the depth buffer. For details, see Enabling Depth Buffering.


Enabling Depth Buffering
Microsoft DirectX 9.0 SDK Update (October 2004)

Enabling Depth Buffering

After you create a depth buffer, as described in Creating a Depth Buffer, you enable depth buffering by calling the IDirect3DDevice9::SetRenderState method. Set the D3DRS_ZENABLE render state to enable depth-buffering. Use the D3DZB_TRUE member of the D3DZBUFFERTYPE enumerated type (or TRUE) to enable z-buffering, D3DZB_USEW to enable w-buffering, or D3DZB_FALSE(or FALSE) to disable depth buffering.

Note To use w-buffering, your application must set a compliant projection matrix even if it doesn't use the Microsoft Direct3D transformation pipeline. For information about providing an appropriate projection matrix, see A W-Friendly Projection Matrix


Retrieving a Depth Buffer
Microsoft DirectX 9.0 SDK Update (October 2004)

Retrieving a Depth Buffer

The following code example shows how to use the IDirect3DDevice9::GetDepthStencilSurface method to retrieve a pointer to the depth-buffer surface owned by the device.

LPDIRECT3DSURFACE9 pZBuffer;

m_d3dDevice->GetDepthStencilSurface( &pZBuffer );


Clearing Depth Buffers
Microsoft DirectX 9.0 SDK Update (October 2004)

Clearing Depth Buffers

Many C++ applications clear the depth buffer before rendering each new frame. You can explicitly clear the depth buffer through Microsoft Direct3D by calling IDirect3DDevice9::Clear and specifying D3DCLEAR_ZBUFFER for the Flags parameter. The IDirect3DDevice9::Clear method allows you to specify an arbitrary depth value in the Z parameter.


Changing Depth Buffer Write Access
Microsoft DirectX 9.0 SDK Update (October 2004)

Changing Depth Buffer Write Access

By default, the Microsoft Direct3D system is allowed to write to the depth buffer. Most applications leave writing to the depth buffer enabled, but you can achieve some special effects by not allowing the Direct3D system to write to the depth buffer.

You can disable depth buffer writes in C++ by calling the IDirect3DDevice9::SetRenderState method with the State parameter set to D3DRS_ZWRITEENABLE and the Value parameter set to 0.


Changing Depth Buffer Comparison Functions
Microsoft DirectX 9.0 SDK Update (October 2004)

Changing Depth Buffer Comparison Functions

By default, when depth-testing is performed on a rendering surface, the Microsoft Direct3D system updates the render-target surface if the corresponding depth value (z or w) for each point is less than the value in the depth buffer. In a C++ application, you change how the system performs comparisons on depth values by calling the IDirect3DDevice9::SetRenderState method with the State parameter set to D3DRS_ZFUNC. The Value parameter should be set to a value in the D3DCMPFUNC enumerated type.


Fog
Microsoft DirectX 9.0 SDK Update (October 2004)

Fog

Adding fog to a 3-D scene can enhance realism, provide ambiance or set a mood, and obscure artifacts sometimes caused when distant geometry comes into view. Microsoft Direct3D supports two fog models, pixel fog and vertex fog, each with its own features and programming interface.

Essentially, fog is implemented by blending the color of objects in a scene with a chosen fog color based on the depth of an object in a scene or its distance from the viewpoint. As objects grow more distant, their original color blends more and more with the chosen fog color, creating the illusion that the object is being increasingly obscured by tiny particles floating in the scene. The following illustration shows a scene rendered without fog, and a similar scene rendered with fog enabled.

In this illustration, the scene on the left has a clear horizon, beyond which no scenery is visible, even though it would be visible in the real world. The scene on the right obscures the horizon by using a fog color identical to the background color, making polygons appear to fade into the distance. By combining discrete fog effects with creative scene design you can add mood and soften the color of objects in a scene.

Direct3D provides two ways to add fog to a scene: pixel fog and vertex fog, named for how the fog effects are applied. For details, see Pixel Fog and Vertex Fog. In short, pixel fog - also called table fog - is implemented in the device driver and vertex fog is implemented in the Direct3D lighting engine. An application can implement fog with a vertex shader, and pixel fog simultaneously if desired.

Note Regardless of whether you use pixel or vertex fog, your application must provide a compliant projection matrix to ensure that fog effects are properly applied. This restriction applies even to applications that do not use the Direct3D transformation and lighting engine. For additional details about how you can provide an appropriate matrix, see A W-Friendly Projection Matrix.

The following topics introduce fog and present information about using various fog features in Direct3D applications.

  • Fog Formulas
  • Fog Parameters
  • Fog Blending
  • Fog Color
  • Vertex Fog
  • Pixel Fog

Fog blending is controlled by render states; it is not part of the programmable pixel pipeline.


Alpha Blending
Microsoft DirectX 9.0 SDK Update (October 2004)

Alpha Blending

Alpha blending is used to display an image that has transparent or semi-transparent pixels. In addition to a red, green, and blue color channel, each pixel in an alpha bitmap has a transparency component known as its alpha channel. The alpha channel typically contains as many bits as a color channel. For example, an 8-bit alpha channel can represent 256 levels of transparency, from 0 (the entire pixel is transparent) to 255 (the entire pixel is opaque). The list below shows some special effects you can create using alpha blending.

Color can be defined with or without alpha values. Color without alpha is RGB; color with alpha is stored as ARGB. Vertex data, material data and texture data can be used to give object's transparency. The frame buffer can also be used to generate transparency effects.

  • Vertex Alpha
  • Material Alpha
  • Texture Alpha
  • Frame Buffer Alpha
  • Render Target Alpha

Samples that demonstrate alpha include:

  • Billboarding
  • Clouds, Smoke, and Vapor Trails
  • Fire, Flares, and Explosions


Vertex Alpha
Microsoft DirectX 9.0 SDK Update (October 2004)

Vertex Alpha

Alpha data can be supplied in the vertex data. To enable vertex alpha, set the D3DRS_DIFFUSEMATERIALSOURCE to D3DMCS_COLOR1 so that the Microsoft Direct3D runtime takes the diffuse value from the diffuse color rather than the material.

m_pd3dDevice->SetRenderState( D3DRS_DIFFUSEMATERIALSOURCE,
                              D3DMCS_COLOR1 );

Then, provide alpha values in the diffuse color. The AddAlphaToASphere function, adds alpha to the vertices of a sphere. Here's an example of how to provide the alpha information to the function.

AddAlphaToASphere( m_pObstacleVertices, 12,
           D3DRGBA(light.dcvDiffuse.r, light.dcvDiffuse.g,
                   light.dcvDiffuse.b, vAlpha ));

This is what the function looks like.

void AddAlphaToASphere(D3DLVERTEX* pVertices, DWORD dwNumRings, D3DCOLOR lightcolor)
{
 WORD x, y;
 // rings around
    for( y=0; y < dwNumRings; y++ )
        for( x=0; x < (dwNumRings*2)+1; x++ )
            (pVertices++)->color = lightcolor;

 // top and bottom
    (pVertices++)->color = lightcolor;
    (pVertices++)->color = lightcolor;
}

AddAlphaToASphere simply modifies the color member of each vertex, which are of type D3DLVERTEX, to include the alpha information.

D3DLVERTEX looks like this.

// Lit vertex
typedef struct {
 D3DVALUE x, y, z;
 DWORD dwReserved;
 D3DCOLOR color, specular;
 D3DVALUE tu, tv;
} D3DLVERTEX, *LPD3DLVERTEX;

Drawing the sphere,

 #define D3DFVF_LVERTEX ( D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_SPECULAR | \
                          D3DFVF_TEX0 )

 //...

 // Draw the lit sphere
 m_pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, D3DFVF_LVERTEX,
                              m_pObstacleVertices, m_dwNumObstacleVertices,
                              m_pObstacleIndices,  m_dwNumObstacleIndices, 0 );

results in a transparent sphere using vertex alpha.


Material Alpha
Microsoft DirectX 9.0 SDK Update (October 2004)

Material Alpha

Alpha can also be supplied in a material. To enable material alpha, set the diffuse material render state so that the runtime will use the material diffuse color components rather than the vertex diffuse color components.

   m_pd3dDevice->SetRenderState( D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_MATERIAL );

Initialize the material with an alpha value, and set the material before drawing.

D3DMATERIAL9 mtrl;
mtrl.Diffuse = mtrl.Ambient = mtrl.Specular = mtrl.Emissive =
    D3DCOLORVALUE(255,0,0,0.5f)

m_pd3dDevice->SetMaterial(&mtrl);


Texture Alpha
Microsoft DirectX 9.0 SDK Update (October 2004)

Texture Alpha

Alpha values can also be provided by textures. First, the texture must be created. Second, the alpha values must be added to the texture. To render with the texture, set the texture to a texture stage and select the appropriate texture stage operation and operands. When draw is called, the primitive will be rendered with transparency. This example creates a texture resource, and then loads the alpha channel.

LPDIRECT3DTEXTURE9 m_pTexture;

// Create an alpha texture
D3DXCreateTexture(m_d3dDevice, 128, 128, 0, D3DUSAGE_RENDERTARGET,
    D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &m_pTexture);

// Initialize the alpha channel
int  yGrad, xGrad;
D3DLOCKED_RECT lockedRect;

if(SUCCEEDED(pTexture->LockRect(0, &lockedRect, NULL, D3DLOCK_DISCARD ))
{
    m_pRGBAData = new DWORD[128*128];
    if( m_pRGBAData != NULL )
    {
        for( DWORD y=0; y < m_dwHeight; y++ )
        {
            DWORD dwOffset = y*m_dwWidth;
            yGrad = (int)(((float)y/(float)m_dwWidth) * 255.0f);

            for( DWORD x=0; x < m_dwWidth; x )
            {
                xGrad = (int)(((float)x/(float)m_dwWidth) * 255.0f);

                DWORD b = (DWORD)(xGrad + (255 - yGrad))/2 & 0xFF;
                DWORD g = (DWORD)((255 - xGrad) + yGrad)/2 & 0xFF;
                DWORD r = (DWORD)(xGrad + yGrad)/2 & 0xFF;
                DWORD a = (DWORD)(xGrad + yGrad)/2 & 0xFF;

                lockedRect.pBits[dwOffset+x] = ((a<<24L)+(r<<16L)+(g<<8L)+(b));
                x++;
            }

            pTexture->UnLockRect(&lockedRect);
        }
    }
}

The alpha value is calculated based on the current pixel's relative x/y position within the texture size. Next, assign the texture to a texture stage and set up the texture stage.

 #define D3DFVF_LVERTEX ( D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_SPECULAR | \
                          D3DFVF_TEX0 )

 // Assign texture
m_pd3dDevice->SetTexture(0, m_pTexture);

// Texture stage states
m_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
m_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);

m_pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);

m_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
m_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE);

m_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);

This results in a primitive with a transparency gradient. The gradient is transparent where x = 0, and opaque where x is its maximum value.


Frame Buffer Alpha
Microsoft DirectX 9.0 SDK Update (October 2004)

Frame Buffer Alpha

Frame buffer alpha-blending is a bit different than vertex alpha, material alpha, and texture alpha. Vertex, material, and texture alpha set transparency values that are used only for the current primitive, and by themselves have no effect on other primitives. Frame buffer alpha-blending controls how the current primitive is combined with existing pixels in the frame buffer to yield a final pixel color.

When performing alpha blending, two colors are being combined: a source color and a destination color. The source color is from the transparent object, the destination color is the color already at the pixel location. The destination color is the result of rendering some other object that is behind the transparent object, that is, the object that will be visible through the transparent object. Alpha blending uses a formula to control the ratio between the source and destination objects.

Final Color = ObjectColor * SourceBlendFactor + PixelColor * DestinationBlendFactor

ObjectColor is the contribution from the primitive being rendered at the current pixel location. PixelColor is the contribution from the frame buffer at the current pixel location.

The set of alpha blend factors that can be used are listed below.

Blend mode factor | Description
D3DBLEND_ZERO | (0, 0, 0, 0)
D3DBLEND_ONE | (1, 1, 1, 1)
D3DBLEND_SRCCOLOR | (Rs, Gs, Bs, As)
D3DBLEND_INVSRCCOLOR | (1-Rs, 1-Gs, 1-Bs, 1-As)
D3DBLEND_SRCALPHA | (As, As, As, As)
D3DBLEND_INVSRCALPHA | (1-As, 1-As, 1-As, 1-As)
D3DBLEND_DESTALPHA | (Ad, Ad, Ad, Ad)
D3DBLEND_INVDESTALPHA | (1-Ad, 1-Ad, 1-Ad, 1-Ad)
D3DBLEND_DESTCOLOR | (Rd, Gd, Bd, Ad)
D3DBLEND_INVDESTCOLOR | (1-Rd, 1-Gd, 1-Bd, 1-Ad)
D3DBLEND_SRCALPHASAT | (f, f, f, 1); f = min(As, 1-Ad)
D3DBLEND_BOTHSRCALPHA | Obsolete for Microsoft DirectX 6.0 and later. You can achieve the same effect by setting the source and destination blend factors to D3DBLEND_SRCALPHA and D3DBLEND_INVSRCALPHA in separate calls.
D3DBLEND_BOTHINVSRCALPHA | Obsolete for DirectX 6.0. You can achieve the same effect by setting the source and destination blend factors to D3DBLEND_INVSRCALPHA and D3DBLEND_SRCALPHA in separate calls.
D3DBLEND_BLENDFACTOR | Use color.r, color.g, color.b, and color.a obtained from the D3DRS_BLENDFACTOR setting.
D3DBLEND_INVBLENDFACTOR | Use 1-color.r, 1-color.g, 1-color.b, and 1-color.a obtained from the D3DRS_BLENDFACTOR setting.

Microsoft Direct3D uses the D3DRS_ALPHABLENDENABLE render state to enable alpha transparency blending. The type of alpha blending that is done depends on the D3DRS_SRCBLEND and D3DRS_DESTBLEND render states. Source and destination blend states are used in pairs. The following code fragment sets the source blend state to D3DBLEND_SRCCOLOR and the destination blend state to D3DBLEND_INVSRCCOLOR.

// This code fragment assumes that lpD3DDevice is a
//   valid pointer to a device.

// Enable alpha blending.
lpD3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE,
                            TRUE);

// Set the source blend state.
lpD3DDevice->SetRenderState(D3DRS_SRCBLEND,
                            D3DBLEND_SRCCOLOR);

// Set the destination blend state.
lpD3DDevice->SetRenderState(D3DRS_DESTBLEND,
                            D3DBLEND_INVSRCCOLOR);

This code performs a linear blend between the source color (the color of the primitive being rendered at the current location) and the destination color (the color at the current location in the frame buffer). The resulting appearance is similar to tinted glass in that some of the color of the destination object seems to be transmitted through the source object; the rest of it appears to be absorbed.

Many of these blend factors require alpha values in the texture to operate correctly. Thus, when using vertex or material alpha, the application is restricted as to which modes will produce interesting results.


Render Target Alpha
Microsoft DirectX 9.0 SDK Update (October 2004)

Render Target Alpha

The frame buffer blender can now blend alpha channels independent from color-channel blending on render targets. This control is enabled with a new render state, D3DRS_SEPARATEALPHABLENDENABLE.

When D3DRS_SEPARATEALPHABLENDENABLE is set to FALSE (which is the default condition), the render-target blending factors and operations applied to alpha are the same as those defined for blending color channels. A driver needs to set the D3DPMISCCAPS_SEPARATEALPHABLEND cap to indicate that it can support render-target alpha blending. Be sure to enable D3DRS_ALPHABLEND to tell the pipeline that alpha blending is needed.

To control the factors in the alpha channel of the render-target blenders, two new render states are defined as follows:

D3DRS_SRCBLENDALPHA
D3DRS_DESTBLENDALPHA

Like the D3DRS_SRCBLEND and D3DRS_DESTBLEND, these can be set to one of the values in the D3DBLEND enumeration. The source and destination blend settings can be combined in several ways, depending on the settings in the SrcBlendCaps and DestBlendCaps members of D3DCAPS9.

The alpha blending is done as follows:

renderTargetAlpha = (alphain* srcBlendOp) BlendOp (alphart* destBlendOp)

Where:

  • alphain is the input alpha value.
  • srcBlendOp is one of the blend factors in D3DBLEND.
  • BlendOp is one of the blend factors in D3DBLEND.
  • alphart is the render-target alpha value.
  • destBlendOp is one of the blend factors in D3DBLEND.
  • renderTargetAlpha is the final blended alpha value.


Direct3D Surfaces
Microsoft DirectX 9.0 SDK Update (October 2004)

Direct3D Surfaces

A surface represents a linear area of display memory and usually resides in the display memory of the display card, although surfaces can exist in system memory. Surfaces are managed by the IDirect3DSurface9 interface.

  • Front Buffer. A rectangle of memory that is translated by the graphics adapter and displayed on the monitor. In Microsoft Direct3D an application never writes directly to the front buffer.
  • Back Buffer. A rectangle of memory that an application can directly write to. The back buffer is never directly displayed on the monitor.
  • Flipping surfaces. The process of moving the back buffer to the front buffer.
  • Swap chain. A collection of one or more back buffers that can be serially presented to the front buffer.

Getting a Surface

Create a surface by calling any of these methods:

  • IDirect3DDevice9::CreateDepthStencilSurface
  • IDirect3DDevice9::CreateOffscreenPlainSurface
  • IDirect3DDevice9::CreateRenderTarget

Surface formats determine how data for each pixel in surface memory is interpreted. Direct3D uses the D3DFORMAT member of the D3DSURFACE_DESC structure to describe the surface format. You can retrieve the format of an existing surface by calling the IDirect3DSurface9::GetDesc method.

Once a surface is created, you can get a pointer to it by calling any of these methods:

  • IDirect3DCubeTexture9::GetCubeMapSurface
  • IDirect3DDevice9::GetBackBuffer
  • IDirect3DDevice9::GetDepthStencilSurface
  • IDirect3DDevice9::GetFrontBufferData
  • IDirect3DDevice9::GetRenderTarget
  • IDirect3DSwapChain9::GetBackBuffer
  • IDirect3DTexture9::GetSurfaceLevel

The IDirect3DSurface9 interface enables you to indirectly access memory through the IDirect3DDevice9::UpdateSurface method. This method allows you to copy a rectangular region of pixels from one IDirect3DSurface9 interface to another IDirect3DSurface9 interface. The surface interface also has methods to directly access display memory. For example, you can use the IDirect3DSurface9::LockRect method to lock a rectangular region of display memory. It is important to call IDirect3DSurface9::UnlockRect after you are done working with the locked rectangular region on the surface.

Additional Surface Topics

Find out more about how to use surfaces with any of these topics:

  • Surface Formats
  • What Is A Swap Chain?
  • Width vs. Pitch
  • Flipping Surfaces
  • Page Flipping and Back Buffering
  • Copying to Surfaces
  • Copying Surfaces
  • Accessing Surface Memory Directly
  • Private Surface Data
  • Gamma Controls


Surface Formats
Microsoft DirectX 9.0 SDK Update (October 2004)

Surface Formats

In Microsoft Direct3D, all two-dimensional (2-D) images are represented by a linear range of memory called a surface. A surface can be thought of as a 2-D array where each element holds a color value representing a small section of the image, called a pixel. An image's detail level is defined by both the number of pixels needed to represent the image, and the number of bits needed for the image's color spectrum. For example, an image that is 800 pixels wide by 600 pixels high with 32 bits of color for each pixel (written as 800x600x32) will be more detailed than an image that is 640 pixels wide by 480 pixels tall with 16 bits of color for each pixel (written as 640x480x16). Likewise, the more detailed image will require a larger surface to store the data. For an 800x600x32 image, the surface's array dimensions will be 800x600, and each element will hold a 32-bit value to represent its color.

All surfaces have a size and store a specific number of bits that represent color. The bits that represent color are separated into individual color elements: red, green, and blue. In Direct3D all color elements are defined by the D3DFORMAT enumerated type. A Direct3D color format is broken down into the number of byes reserved for each color. For example, a 16-bit color format in Direct3D is defined as D3DFMT_R5G6B5, where 5 bits are reserved for red (R), 6 bits for green (G), and 5 bits for blue (B).


What Is a Swap Chain?
Microsoft DirectX 9.0 SDK Update (October 2004)

What Is a Swap Chain?

A graphics adapter holds a pointer to a surface that represents the image being displayed on the monitor, called a front buffer. As the monitor is refreshed, the graphics card sends the contents of the front buffer to the monitor to be displayed. However, this leads to a problem when rendering real-time graphics. The heart of the problem is that monitor refresh rates are very slow in comparison to the rest of the computer. Common refresh rates range from 60 Hz (60 times per second) to 100 Hz. If your application is updating the front buffer while the monitor is in the middle of a refresh, the image that is displayed will be cut in half with the upper half of the display containing the old image and the lower half containing the new image. This problem is referred to as tearing.

Microsoft Direct3D implements two options to avoid tearing:

  • An option to only allow updates of the monitor on the vertical retrace (or vertical sync) operation. A monitor typically refreshes its image by moving a light pin horizontally, zigzagging from the top left of the monitor and ending at the bottom right. When the light pin reaches the bottom, the monitor recalibrates the light pin by moving it back to the upper left so that the process can start again. This recalibration is called a vertical sync. During a vertical sync, the monitor is not drawing anything, so any update to the front buffer will not be seen until the monitor starts to draw again. The vertical sync is relatively slow; however, not slow enough to render a complex scene while waiting. What is needed to avoid tearing and be able to render complex scenes is a process called back buffering.
  • An option to use a technique called back buffering. Back buffering is the process of drawing a scene to an off-screen surface, called a back buffer. Note that any surface other than the front buffer is called an off-screen surface because it is never directly viewed by the monitor. By using a back buffer, an application has the freedom to render a scene whenever the system is idle (that is, no windows messages are waiting) without having to consider the monitor's refresh rate. Back buffering brings in an additional complication of how and when to move the back buffer to the front buffer.

The process of moving the back buffer to the front buffer is called surface flipping. Because the graphics card simply uses a pointer to a surface to represent the front buffer, a simple pointer change is all that is needed to set the back buffer to the front buffer. When an application asks Direct3D to present the back buffer to the front buffer, Direct3D simply "flips" the two surface pointers. The result is that the back buffer is now the new front buffer, and the old front buffer is the new back buffer. A surface flip is invoked whenever an application asks the Direct3D device to present the back buffer; however, Direct3D can be set up to queue the requests until a vertical sync occurs. This option is referred to as the Direct3D device's presentation interval. Note that the data in the new back buffer may not be reusable, depending on how an application specifies how Direct3D should handle surface flipping. Surface flipping is key in multimedia, animation, and game software; it is equivalent to the way you can do animation with a pad of paper. On each page, the artist changes the figures slightly, so that when you flip rapidly between sheets, the drawing appears animated.

Related Topics

  • Flipping Surfaces


Width vs. Pitch
Microsoft DirectX 9.0 SDK Update (October 2004)

Width vs. Pitch

Although the terms width and pitch are often used informally, they have very important, and distinctly different, meanings. As a result, you should understand the meanings for each, and how to interpret the values that Microsoft Direct3D uses to describe them.

Direct3D uses the D3DSURFACE_DESC structure to carry information describing a surface. Among other things, this structure is defined to contain information about a surface's dimensions, as well as how those dimensions are represented in memory. The structure uses the Height and Width members to describe the logical dimensions of the surface. Both members are measured in pixels. Therefore, the Height and Width values for a 640×480 surface are the same whether it is an 8-bit surface or a 24-bit RGB surface.

When you lock a surface using the IDirect3DSurface9::LockRect method, the method fills in a D3DLOCKED_RECT structure that contains the pitch of the surface and a pointer to the locked bits. The value in the Pitch member describes the surface's memory pitch, also called stride. Pitch is the distance, in bytes, between two memory addresses that represent the beginning of one bitmap line and the beginning of the next bitmap line. Because pitch is measured in bytes rather than pixels, a 640x480x8 surface has a very different pitch value than a surface with the same dimensions but a different pixel format. Additionally, the pitch value sometimes reflects bytes that Direct3D has reserved as a cache, so it is not safe to assume that pitch is just the width multiplied by the number of bytes per pixel. Rather, visualize the difference between width and pitch as shown in the following illustration.

Pitch and width difference

In this figure, the front buffer and back buffer are both 640x480x8, and the cache is 384x480x8.

When accessing surfaces directly, take care to stay within the memory allocated for the dimensions of the surface and stay out of any memory reserved for cache. Additionally, when you lock only a portion of a surface, you must stay within the rectangle you specify when locking the surface. Failing to follow these guidelines will have unpredictable results. When rendering directly into surface memory, always use the pitch returned by the IDirect3DSurface9::LockRect method. Do not assume a pitch based solely on the display mode. If your application works on some display adapters but looks garbled on others, this may be the cause of the problem.

For more information, see Accessing Surface Memory Directly.


Flipping Surfaces
Microsoft DirectX 9.0 SDK Update (October 2004)

Flipping Surfaces

A Microsoft Direct3D application typically displays an animated sequence by generating the frames of the animation in back buffers and presenting them in sequence. Back buffers are organized into swap chains. A swap chain is a series of buffers that "flip" to the screen one after another. This can be used to render one scene in memory and then flip the scene to the screen when rendering is complete. This avoids the phenomenon known as tearing and allows for smoother animation.

Each device created in Direct3D has at least one swap chain. When you initialize the first Direct3D device, you set the BackBufferCount member of the D3DPRESENT_PARAMETERS structure, which tells Direct3D the number of back buffers that will be in the swap chain. The call to IDirect3D9::CreateDevice then creates the Direct3D device and corresponding swap chain.

When you use the IDirect3DDevice9::Present method to request a surface flip operation, the pointers to surface memory for the front buffer and back buffers are swapped. Flipping is performed by switching pointers that the display device uses for referencing memory, not by copying surface memory. When a flipping chain contains a front buffer and more than one back buffer, the pointers are switched in a circular pattern, as shown in the following illustration.

You can create addition swap chains for a device by calling IDirect3DDevice9::CreateAdditionalSwapChain. An application can create one swap chain per view and associate each swap chain with a particular window. The application renders images in the back buffers of each swap chain, and then presents them individually. The two parameters that IDirect3DDevice9::CreateAdditionalSwapChain takes are a pointer to a D3DPRESENT_PARAMETERS structure and the address of a pointer to an IDirect3DSwapChain9 interface. You can then use IDirect3DSwapChain9::Present to display the contents of the next back buffer to the front buffer. Note that a device can only have one full-screen swap chain.

You can gain access to a specific back buffer by calling the IDirect3DDevice9::GetBackBuffer or IDirect3DSwapChain9::GetBackBuffer methods, which return a pointer to an IDirect3DSurface9 interface that represents the returned back buffer surface. Note that calling this method increases the internal reference count on the IDirect3DDevice9 interface so be sure to call IUnknown::Release when you are done using this surface or you will have a memory leak.

Remember, Direct3D flips surfaces by swapping surface memory pointers within the swap chain, not by swapping the surfaces themselves. This means that you will always render to the back buffer that will be displayed next.

It is important to note the distinction between a "flipping operation," as performed by a display adapter driver, and a "Present" operation applied to a swap chain created with D3DSWAPEFFECT_FLIP.

The term "flip" conventionally denotes an operation that alters the range of video memory addresses that a display adapter uses to generate its output signal, thus causing the contents of a previously hidden back buffer to be displayed. In Microsoft DirectX 9.0, the term is often used more generally to describe the presentation of a back buffer in any swap chain created with the D3DSWAPEFFECT_FLIP swap effect.

While such "Present" operations are almost invariably implemented by flip operations when the swap chain is a full-screen one, they are necessarily implemented by copy operations when the swap chain is windowed. Furthermore, a display adapter driver may use flipping to implement Present operations against full-screen swap chains based on the D3DSWAPEFFECT_DISCARD and D3DSWAPEFFECT_COPY.

The discussion above applies to the commonly used case of a full-screen swap chain created with D3DSWAPEFFECT_FLIP.

For a more general discussion of the different swap effects for both windowed and full-screen swap chains, see D3DSWAPEFFECT.


Page Flipping and Back Buffering
Microsoft DirectX 9.0 SDK Update (October 2004)

Page Flipping and Back Buffering

Page flipping is key in multimedia, animation, and game software; it is analogous to the way you can do animation with a pad of paper. On each page, the artist changes the figure slightly, so that when you flip rapidly between sheets, the drawing appears animated.

Page flipping in software is similar to this process. Microsoft Direct3D implements page flipping functionality through a swap chain, which is a property of the device. Initially, you set up a series of Direct3D buffers that flip to the screen in the way that the artist's paper flips to the next page. The first buffer is referred to as the color front buffer. The buffers behind it are called back buffers. Your application writes to a back buffer and then flips the color front buffer so that the back buffer appears on screen. While the system displays the image, your software is again writing to a back buffer. The process continues as long as you are animating, enabling you to animate images efficiently.

Direct3D makes it easy to set up page flipping schemes—from a simple double-buffered scheme (a color front buffer with one back buffer) to more sophisticated schemes with additional back buffers.

Related Topics

  • What Is A Swap Chain?


Copying to Surfaces
Microsoft DirectX 9.0 SDK Update (October 2004)

Copying to Surfaces

When using IDirect3DDevice9::UpdateSurface, pass a rectangle on the source surface, or use NULL to specify the entire surface. You also pass a point on the destination surface to which the upper left position of the rectangle on the source image is copied. This method does not support clipping. The operation will fail unless the source rectangle and the corresponding destination rectangle are completely contained within the source and destination surfaces respectively. This method does not support alpha blending, color keys, or format conversion. Note that the destination and source surfaces must be distinct.

For other restrictions when using UpdateSurface, see IDirect3DDevice9::UpdateSurface.

The following methods are also available in C++/C for copying images to a Microsoft Direct3D surface.

  • D3DXLoadSurfaceFromFile
  • D3DXLoadSurfaceFromFileInMemory
  • D3DXLoadSurfaceFromMemory
  • D3DXLoadSurfaceFromResource
  • D3DXLoadSurfaceFromSurface
  • IDirect3DDevice9::UpdateSurface

Related Topics

  • IDirect3DDevice9::StretchRect


Copying Surfaces
Microsoft DirectX 9.0 SDK Update (October 2004)

Copying Surfaces

The term blit is shorthand for "bit block transfer," which is the process of transferring blocks of data from one place in memory to another. The blitting device driver interface (DDI) continues to be used in Microsoft DirectX 9.0 as the primary mechanism for moving large rectangles of pixels on a per-frame basis, the mechanism behind the copy-oriented IDirect3DDevice9::Present method. The transportation of artwork in the blit operation is performed by the IDirect3DDevice9::UpdateTexture method. Artwork can also be copied in DirectX 9.0 by using the IDirect3DDevice9::UpdateSurface method, which copies a rectangular subset of pixels.

Note DirectX 9.0 provides D3DX functions that enable you to load artwork from files, apply color conversion, and resize artwork. For more information about the available functions see Texturing Functions.

Related Topics

  • IDirect3DDevice9::StretchRect


Accessing Surface Memory Directly
Microsoft DirectX 9.0 SDK Update (October 2004)

Accessing Surface Memory Directly

You can directly access the surface memory by using the IDirect3DSurface9::LockRect method. When you call this method, the pRect parameter is a pointer to a RECT World Wide Web link structure that describes the rectangle on the surface to access directly. To request that the entire surface be locked, set pRect to NULL. Also, you can specify a RECT that covers only a portion of the surface. Providing that no two rectangles overlap, two threads or processes can simultaneously lock multiple rectangles in a surface. Note that a multisample back buffer cannot be locked.

The IDirect3DSurface9::LockRect method fills a D3DLOCKED_RECT structure with all the information to properly access the surface memory. The structure includes information about the pitch and has a pointer to the locked bits. When you finish accessing the surface memory, call the IDirect3DSurface9::UnlockRect method to unlock it.

While you have a surface locked, you can directly manipulate the contents. The following list describes some tips for avoiding common problems with directly rendering surface memory.

  • Never assume a constant display pitch. Always examine the pitch information returned by the IDirect3DSurface9::LockRect method. This pitch can vary for a number of reasons, including the location of the surface memory, the display card type, or even the version of the Microsoft Direct3D driver. For more information, see Width vs. Pitch.
  • Make certain you copy to unlocked surfaces. Direct3D copy methods will fail if called on a locked surface.
  • Limit your application's activity while a surface is locked.
  • Always copy data aligned to display memory. Microsoft Windows 98 uses a page fault handler, Vflatd.386, to implement a virtual flat-frame buffer for display cards with bank-switched memory. The handler allows these display devices to present a linear frame buffer to Direct3D. Copying data unaligned to display memory can cause the system to suspend operations if the copy spans memory banks.
  • A surface may not be locked if it belongs to a resource assigned to the D3DPOOL_DEFAULT memory pool unless it is a dynamic texture or a surface created using IDirect3DDevice9::CreateOffscreenPlainSurface. Back buffer surfaces, which may be accessed using the IDirect3DDevice9::GetBackBuffer and IDirect3DSwapChain9::GetBackBuffer methods, may be locked only if the swap chain was created with the Flags member of the D3DPRESENT_PARAMETERS structure set to include D3DPRESENTFLAG_LOCKABLE_BACKBUFFER.


Private Surface Data
Microsoft DirectX 9.0 SDK Update (October 2004)

Private Surface Data

You can store any kind of application-specific data with a surface. For example, a surface representing a map in a game might contain information about terrain.

A surface can have more than one private data buffer. Each buffer is identified by a globally unique identifier (GUID) that you supply when attaching the data to the surface.

To store private surface data, use SetPrivateData, passing a pointer to the source buffer, the size of the data, and an application-defined GUID for the data. Optionally, the source data can exist in the form of a Component Object Model (COM) object; in this case, you pass a pointer to the object's IUnknown interface pointer and you set the D3DSPD_IUNKNOWNPOINTER flag.

SetPrivateData allocates an internal buffer for the data and copies it. You can then safely free the source buffer or object. The internal buffer or interface reference is released when FreePrivateData is called. This happens automatically when the surface is freed.

To retrieve private data for a surface, you must allocate a buffer of the correct size and then call the GetPrivateData method, passing the GUID that was assigned to the data. You are responsible for freeing any dynamic memory you use for this buffer. If the data is a COM object, this method retrieves the IUnknown pointer.

If you don't know how big a buffer to allocate, first call GetPrivateData with zero in pSizeOfData. If the method fails with D3DERR_MOREDATA, it returns the necessary number of bytes for the buffer.


Gamma Controls
Microsoft DirectX 9.0 SDK Update (October 2004)

Gamma Controls

Gamma controls allow you to change how the system displays the contents of the surface, without affecting the contents of the surface itself. Think of these controls as very simple filters that Microsoft Direct3D applies to data as it leaves a surface and before it is rendered on the screen.

Gamma controls are a property of a swap chain. Gamma controls make it possible to dynamically change how a surface's red, green, and blue levels map to the actual levels that the system displays. By setting gamma levels, you can cause the user's screen to flash colors—red when the user's character is shot, green when the character picks up a new item, and so on—without copying new images to the frame buffer to achieve the effect. Or, you might adjust color levels to apply a color bias to the images in the back buffer.

There is always at least one swap chain (the implicit swap chain) for each device because Direct3D for Microsoft DirectX 9.0 has one swap chain as a property of the device. Because the gamma ramp is a property of the swap chain, the gamma ramp can be applied when the swap chain is windowed. The gamma ramp takes effect immediately. There is no waiting for a vertical sync operation.

The IDirect3DDevice9::SetGammaRamp and IDirect3DDevice9::GetGammaRamp methods allow you to manipulate ramp levels that affect the red, green, and blue color components of pixels from the surface before they are sent to the digital-to-analog converter (DAC) for display.

Gamma Ramp Levels

In Direct3D, the term gamma ramp describes a set of values that map the level of a particular color component—red, green, blue—for all pixels in the frame buffer to new levels that are received by the DAC for display. The remapping is performed by way of three look-up tables, one for each color component.

Here's how it works: Direct3D takes a pixel from the frame buffer and evaluates its individual red, green, and blue color components. Each component is represented by a value from 0 to 65535. Direct3D takes the original value and uses it to index a 256-element array (the ramp), where each element contains a value that replaces the original one. Direct3D performs this look-up and replace process for each color component of each pixel in the frame buffer, thereby changing the final colors for all the on-screen pixels.

It's handy to visualize the ramp values by graphing them. The left graph of the two following graphs shows a ramp that doesn't modify colors at all. The right graph shows a ramp that imposes a negative bias to the color component to which it is applied.

The array elements for the graph on the left contain values identical to their index—0 in the element at index 0, and 65535 at index 255. This type of ramp is the default, as it doesn't change the input values before they're displayed. The right graph provides more variation; its ramp contains values that range from 0 in the first element to 32768 in the last element, with values ranging uniformly in between. The effect is that the color component that uses this ramp appears muted on the display. You are not limited to using linear graphs; if your application can assign arbitrary mapping if needed. You can even set the entries to all zeroes to remove a color component completely from the display.

Setting and Retrieving Gamma Ramp Levels

Gamma ramp levels are effectively look-up tables that Direct3D uses to map the frame buffer color components to new levels that will be displayed. You can set and retrieve ramp levels for the primary surface by calling the IDirect3DDevice9::SetGammaRamp and IDirect3DDevice9::GetGammaRamp methods. IDirect3DDevice9::SetGammaRamp accepts two parameters and IDirect3DDevice9::GetGammaRamp accepts one parameter. For IDirect3DDevice9::SetGammaRamp, the first parameter is either D3DSGR_CALIBRATE or D3DSGR_NO_CALIBRATION. The second parameter, pRamp, is a pointer to a D3DGAMMARAMP structure. The D3DGAMMARAMP structure contains three 256-element arrays of WORDs, one array each to contain the red, green, and blue gamma ramps. IDirect3DDevice9::GetGammaRamp has one parameter that takes a pointer to a D3DGAMMARAMP type that will be filled with the current gamma ramp.

You can include the DDSGR_CALIBRATE value for the first parameter of IDirect3DDevice9::SetGammaRamp to invoke the calibrator when setting new gamma levels. Calibrating gamma ramps incurs some processing overhead, and should not be used frequently. Setting a calibrated gamma ramp provides a consistent and absolute gamma value for the user, regardless of the display adapter and monitor.

Not all systems support gamma calibration. To determine if gamma calibration is supported, call IDirect3DDevice9::GetDeviceCaps, and examine the Caps2 member of the associated D3DCAPS9 structure after the method returns. If the D3DCAPS2_CANCALIBRATEGAMMA capability flag is present, then gamma calibration is supported.

When setting new ramp levels, keep in mind that that the levels you set in the arrays are only used when your application is in full-screen, exclusive mode. Whenever your application changes to normal mode, the ramp levels are set aside, taking effect again when the application reinstates full-screen mode.

If the device does not support gamma ramps in the swap chain's current presentation mode (full-screen or windowed), no error value is returned. Applications can check the D3DCAPS2_FULLSCREENGAMMA and D3DCAPS2_CANCALIBRATEGAMMA capability bits in the Caps2 member of the D3DCAPS9 type to determine the capabilities of the device and whether a calibrator is installed.


Direct3D Textures
Microsoft DirectX 9.0 SDK Update (October 2004)

Direct3D Textures

Textures are a powerful tool in creating realism in computer-generated 3-D images. Microsoft Direct3D supports an extensive texturing feature set, providing developers with easy access to advanced texturing techniques.

This section will get you started using textures.

  • Basic Texturing Concepts
  • Texture Coordinates
  • Texture Filtering
  • Texture Resources
  • Texture Wrapping
  • Texture Blending

These topics will go into more detail about additional texturing functionality.

  • Automatic Generation of Mipmaps
  • Automatic Texture Management
  • Compressed Texture Resources
  • Hardware Considerations for Texturing
  • Volume Texture Resources

For improved performance, consider using dynamic textures. A dynamic texture can be locked, written to, and unlocked each frame. See Using Dynamic Textures.


Basic Texturing Concepts
Microsoft DirectX 9.0 SDK Update (October 2004)

Basic Texturing Concepts

Early computer-generated 3-D images, although generally advanced for their time, tended to have a shiny plastic look. They lacked the types of markings—such as scuffs, cracks, fingerprints, and smudges—that give 3-D objects realistic visual complexity. In recent years, textures have gained popularity among developers as a tool for enhancing the realism of computer-generated 3-D images.

In its everyday use, the word texture refers to an object's smoothness or roughness. In computer graphics, however, a texture is a bitmap of pixel colors that give an object the appearance of texture.

Because Direct3D textures are bitmaps, any bitmap can be applied to a Direct3D primitive. For instance, applications can create and manipulate objects that appear to have a wood grain pattern in them. Grass, dirt, and rocks can be applied to a set of 3-D primitives that form a hill. The result is a realistic-looking hillside. You can also use texturing to create effects such as signs along a roadside, rock strata in a cliff, or the appearance of marble on a floor.

In addition, Direct3D supports more advanced texturing techniques such as texture blending—with or without transparency—and light mapping. For more information, see Texture Blending and Light Mapping with Textures.

If your application creates a hardware abstraction layer (HAL) device or a software device, it can use 8, 16, 24, 32, 64, or 128-bit textures.

Additional information is contained in the following topics.

  • Texture Addressing Modes
  • Texture Dirty Regions
  • Texture Palettes
  • Loading a Texture with D3DX


Texture Addressing Modes
Microsoft DirectX 9.0 SDK Update (October 2004)

Texture Addressing Modes

Your Microsoft Direct3D application can assign texture coordinates to any vertex of any primitive. For details, see Texture Coordinates. Typically, the u- and v-texture coordinates that you assign to a vertex are in the range of 0.0 to 1.0 inclusive. However, by assigning texture coordinates outside that range, you can create certain special texturing effects.

You control what Direct3D does with texture coordinates that are outside the [0.0, 1.0] range by setting the texture addressing mode. For instance, you can have your application set the texture addressing mode so that a texture is tiled across a primitive.

Direct3D enables applications to perform texture wrapping. It is important to note that setting the texture addressing mode to D3DTADDRESS_WRAP is not the same as performing texture wrapping. Setting the texture addressing mode to D3DTADDRESS_WRAP results in multiple copies of the source texture being applied to the current primitive, and enabling texture wrapping changes how the system rasterizes textured polygons. For details, see Texture Wrapping.

Enabling texture wrapping effectively makes texture coordinates outside the [0.0, 1.0] range invalid, and the behavior for rasterizing such delinquent texture coordinates is undefined in this case. When texture wrapping is enabled, texture addressing modes are not used. Take care that your application does not specify texture coordinates lower than 0.0 or higher than 1.0 when texture wrapping is enabled.

Setting the Addressing Mode

You can set texture addressing modes for individual texture stages by calling the IDirect3DDevice9::SetSamplerState method. Specify the desired texture stage identifier in the first parameter. Set the second parameter to D3DSAMP_ADDRESSU, D3DSAMP_ADDRESSV, or D3DSAMP_ADDRESSW values to update the u-, v-, or w-addressing modes individually. The third parameter you pass to IDirect3DDevice9::SetSamplerState determines which mode is being set. This can be any member of the D3DTEXTUREADDRESS enumerated type. To retrieve the current texture address mode for a texture stage, call IDirect3DDevice9::GetSamplerState, using the D3DSAMP_ADDRESSU, D3DSAMP_ADDRESSV, or D3DSAMP_ADDRESSW members of the D3DSAMPLERSTATETYPE enumeration to identify the address mode about which you want information.

Device Limitations

Although the system generally allows texture coordinates outside the range of 0.0 and 1.0, inclusive, hardware limitations often affect how far outside that range texture coordinates can be. A rendering device communicates this limit in the MaxTextureRepeat member of the D3DCAPS9 structure when you retrieve device capabilities. The value in this member describes the full range of texture coordinates allowed by the device. For instance, if this value is 128, then the input texture coordinates must be kept in the range -128.0 to +128.0. Passing vertices with texture coordinates outside this range is invalid. The same restriction applies to the texture coordinates generated as a result of automatic texture coordinate generation and texture coordinate transformations.

The interpretation of MaxTextureRepeat is also affected by the D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE capability bit. When this bit is set, the value in the MaxTextureRepeat member of D3DCAPS9 is used precisely as described. However, when D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE is not set, texture repeating limitations depend on the size of the texture indexed by the texture coordinates. In this case, MaxTextureRepeat must be scaled by the current texture size at the largest level of detail to compute the valid texture coordinate range. For example, given a texture dimension of 32 and MaxTextureRepeat value of 512, the actual valid texture coordinate range is 512/32 = 16, so the texture coordinates for this device must be within the range of -16.0 to +16.0.

Additional information about the texture addressing modes is contained in the following topics.

  • Wrap Texture Address Mode
  • Mirror Texture Address Mode
  • Clamp Texture Address Mode
  • Border Color Texture Address Mode


Wrap Texture Address Mode
Microsoft DirectX 9.0 SDK Update (October 2004)

Wrap Texture Address Mode

The wrap texture address mode, identified by the D3DTADDRESS_WRAP member of the D3DTEXTUREADDRESS enumerated type, makes Microsoft Direct3D repeat the texture on every integer junction. Suppose, for example, your application creates a square primitive and specifies texture coordinates of (0.0,0.0), (0.0,3.0), (3.0,3.0), and (3.0,0.0). Setting the texture addressing mode to D3DTADDRESS_WRAP results in the texture being applied three times in both the u-and v-directions.

The effects of this texture address mode are similar to, but distinct from, those of the mirror mode. For more information, see Mirror Texture Address Mode.


Mirror Texture Address Mode
Microsoft DirectX 9.0 SDK Update (October 2004)

Mirror Texture Address Mode

The mirror texture address mode, identified by the D3DTADDRESS_MIRROR member of the D3DTEXTUREADDRESS enumerated type, causes Microsoft Direct3D to mirror the texture at every integer boundary. Suppose, for example, your application creates a square primitive and specifies texture coordinates of (0.0,0.0), (0.0,3.0), (3.0,3.0), and (3.0,0.0). Setting the texture addressing mode to D3DTADDRESS_MIRROR results in the texture being applied three times in both the u- and v-directions. Every other row and column that it is applied to is a mirror image of the preceding row or column.

The effects of this texture address mode are similar to, but distinct from, those of the wrap mode. For more information, see Wrap Texture Address Mode.


Clamp Texture Address Mode
Microsoft DirectX 9.0 SDK Update (October 2004)

Clamp Texture Address Mode

The clamp texture address mode, identified by the D3DTADDRESS_CLAMP member of the D3DTEXTUREADDRESS enumerated type, causes Microsoft Direct3D to clamp your texture coordinates to the [0.0, 1.0] range. That is, it applies the texture once, then smears the color of edge pixels. For example, suppose that your application creates a square primitive and assigns texture coordinates of (0.0,0.0), (0.0,3.0), (3.0,3.0), and (3.0,0.0) to the primitive's vertices. Setting the texture addressing mode to D3DTADDRESS_CLAMP results in the texture being applied once. The pixel colors at the top of the columns and the end of the rows are extended to the top and right of the primitive respectively.

This is illustrated in the following figure.


Border Color Texture Address Mode
Microsoft DirectX 9.0 SDK Update (October 2004)

Border Color Texture Address Mode

The border color texture address mode, identified by the D3DTADDRESS_BORDER member of the D3DTEXTUREADDRESS enumerated type, causes Microsoft Direct3D to use an arbitrary color, known as the border color, for any texture coordinates outside the range of 0.0 through 1.0, inclusive.

This is shown in the following figure in which the application specifies that the texture be applied to the primitive using a red border.

Applications set the border color by calling IDirect3DDevice9::SetSamplerState. Set the first parameter for the call to the desired texture stage identifier, the second parameter to the D3DSAMP_BORDERCOLOR stage state value, and the third parameter to the new RGBA border color.


Texture Dirty Regions
Microsoft DirectX 9.0 SDK Update (October 2004)

Texture Dirty Regions

Applications can optimize which subset of a texture is copied by specifying "dirty" regions on textures. Only those regions marked as dirty are copied by a call to IDirect3DDevice9::UpdateTexture. However, the dirty regions may be expanded to optimize alignment. When a texture is created, the entire texture is considered dirty. Only the following operations affect the dirty state of a texture:

  • Adding a dirty region to a texture.
  • Locking some buffer in the texture. This operation adds the locked region as a dirty region. The application can turn off this automatic dirty region update if it has better knowledge of the actual dirty regions.
  • Using a surface level of the texture as a destination in IDirect3DDevice9::UpdateSurface marks the entire texture as dirty.
  • Using the texture as a source in IDirect3DDevice9::UpdateTexture clears all the dirty regions on the source texture.
  • Using IDirect3DSurface9::GetDC to return a device context.
  • Calling IDirect3DBaseTexture9::GenerateMipSubLevels marks the entire texture as dirty.
  • Calling IDirect3DBaseTexture9::SetAutoGenFilterType marks the entire texture as dirty.

Dirty regions are set on the top level of a mipmapped texture, and IDirect3DDevice9::UpdateTexture can expand the dirty region down the mip chain in order to minimize the number of bytes copied for each sublevel. Note that the sublevel dirty region coordinates are rounded outward, that is, their fractional parts are rounded toward the nearest edge of the texture.

Because each type of texture has different types of dirty regions, there are methods on each texture type. 2-D textures use dirty rectangle, and volume textures use boxes.

  • IDirect3DCubeTexture9::AddDirtyRect
  • IDirect3DTexture9::AddDirtyRect
  • IDirect3DVolumeTexture9::AddDirtyBox

Passing NULL for the pDirtyRect or pDirtyBox parameters for the above methods expands the dirty region to cover the entire texture.

Each lock method can take D3DLOCK_NO_DIRTY_UPDATE, which prevents any changes to the dirty state of the texture. For more information, see Locking Resources.

When more information about the true set of regions that are changed during a lock operation is available, applications should use D3DLOCK_NO_DIRTY_UPDATE. Note that a lock or a copy to a texture sublevel only (that is, without locking or copying to the top level) does not update the dirty regions for that texture. Applications assume the same responsibility for updating dirty regions when they lock lower levels without locking the topmost level.


Texture Palettes
Microsoft DirectX 9.0 SDK Update (October 2004)

Texture Palettes

Microsoft Direct3D for Microsoft DirectX 9.0 supports paletted textures through a set of 256 entry palettes associated with the IDirect3DDevice9 object. A palette is made current by calling the IDirect3DDevice9::SetCurrentTexturePalette method. The current palette is used for translating all paletted textures for all active texture stages. IDirect3DDevice9::SetPaletteEntries updates all of a palette's 256 entries. Each entry is a PALETTEENTRY structure of the format D3DFMT_A8R8G8B8. All entries default to 0xFFFFFFFF.

The IDirect3DDevice9 palettes contain an alpha channel. This alpha channel can be used when the D3DPTEXTURECAPS_ALPHAPALETTE device capability flag is set, indicating that the device supports alpha from the palette. The palette alpha channel is used when the texture format does not have an alpha channel. If the device does not support alpha from the palette and the texture format does not have an alpha channel, then a value of 0xFF is used for alpha.

There is a maximum of 65,536 (0x0000FFFF) palettes. Because memory resources associated with the set of palettes are proportional to the maximum palette number that an application references, use contiguous palette numbers starting at zero.


Loading a Texture with D3DX
Microsoft DirectX 9.0 SDK Update (October 2004)

Loading a Texture with D3DX

With D3DX, it is relatively simple to load a texture. Here's an example that does just that. In order to access D3DX, you will need to create a Microsoft Direct3D object and a Direct3D device.

// Create Direct3D object
IDirect3D9 *pd3d = Direct3DCreate9(D3D_SDK_VERSION);

// Create a device
IDirect3DDevice9 *pdevice;
D3DPRESENT_PARAMETERS present;

memset(&present, 0, sizeof(present));
present.BackBufferFormat = D3DFMT_UNKNOWN;
present.Windowed = TRUE;

pd3d->CreateDevice(0, D3DDEVTYPE_REF, hwnd /* from your app */,
    0, &present, &pdevice);

// Load the texture in as uncompressed
IDirect3DTexture9 *ptexture;

D3DXCreateTextureFromFileEx(pdevice, "myfile.tga",
    D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0,
    D3DFMT_A8R8G8B8, D3DPOOL_SCRATCH,
    D3DX_DEFAULT, D3DX_DEFAULT, 0, 0, 0,
    &ptexture);

// Get a pointer to the raw data
D3DLOCKED_RECT rect;
ptexture->LockRect(0, &rect, D3DLOCK_READONLY);

// Access the raw texture data with the rect.pBits pointer
...

// Clean up
ptexture->UnlockRect(0);
ptexture->Release();
pdevice->Release();


Texture Coordinates
Microsoft DirectX 9.0 SDK Update (October 2004)

Texture Coordinates

Most textures, like bitmaps, are a two-dimensional array of color values. Cubic environment map textures are an exception. For details, see Cubic Environment Mapping. The individual color values are called a texture element, or texel. Each texel has a unique address in the texture. The address can be thought of as a column and row number, which are labeled u and v respectively.

Texture coordinates are in texture space. That is, they are relative to the location (0,0) in the texture. When a texture is applied to a primitive in 3-D space, its texel addresses must be mapped into object coordinates. They must then be translated into screen coordinates, or pixel locations.

Mapping Texels to Screen Space

Microsoft Direct3D maps texels in texture space directly to pixels in screen space, skipping the intermediate step for greater efficiency. This mapping process is actually an inverse mapping. That is, for each pixel in screen space, the corresponding texel position in texture space is calculated. The texture color at or around that point is sampled. The sampling process is called texture filtering. For more information, see Texture Filtering.

Each texel in a texture can be specified by its texel coordinate. However, in order to map texels onto primitives, Direct3D requires a uniform address range for all texels in all textures. Therefore, it uses a generic addressing scheme in which all texel addresses are in the range of 0.0 to 1.0 inclusive. Direct3D applications specify texture coordinates in terms of u,v values, much like 2-D Cartesian coordinates are specified in terms of x,y coordinates. Technically, the system can actually process texture coordinates outside the range of 0.0 and 1.0, and does so by using the parameters you set for texture addressing. For more information, see Texture Addressing Modes.

A result of this is that identical texture addresses can map to different texel coordinates in different textures. In the following illustration, the texture address being used is (0.5,1.0). However, because the textures are different sizes, the texture address maps to different texels. Texture 1, on the left, is 5x5. The texture address (0.5,1.0) maps to texel (2,4). Texture 2, on the right, is 7x7. The texture address (0.5,1.0) maps to texel (3,6).

A simplified version of the texel mapping process is shown in the following diagram.

Pixel idealized into a square of color

For this example, a pixel, shown at the left of the illustration, is idealized into a square of color. The addresses of the four corners of the pixel are mapped into the 3-D primitive in object space. The shape of the pixel is often distorted because of the shape of the primitive in 3-D space and because of the viewing angle. The corners of the surface area on the primitive that correspond the corners of the pixel are then mapped into texture space. The mapping process distorts the pixel's shape again, which is common. The final color value of the pixel is computed from the texels in the region to which the pixel maps. You determine the method that Direct3D uses to arrive at the pixel color when you set the texture filtering method. For more information, see Texture Filtering.

Your application can assign texture coordinates directly to vertices. This capability gives you control over which portion of a texture is mapped into a primitive. For instance, suppose you create a rectangular primitive that is exactly the same size as the texture in the following illustration. In this example, you want your application to map the whole texture onto the whole wall. The texture coordinates your application assigns to the vertices of the primitive are (0.0,0.0), (1.0,0.0), (1.0,1.0), and (0.0,1.0).

If you decide to decrease the height of the wall by one-half, you can distort the texture to fit onto the smaller wall, or you can assign texture coordinates that cause Direct3D to use the lower half of the texture.

If you decide to distort or scale the texture to fit the smaller wall, the texture filtering method that you use will influence the quality of the image. For more information, see Texture Filtering.

If, instead, you decide to assign texture coordinates to make Direct3D use the lower half of the texture for the smaller wall, the texture coordinates your application assigns to the vertices of the primitive in this example are (0.0,0.5), (1.0,0.5), (1.0,1.0), and (0.0,1.0). Direct3D applies the lower half of the texture to the wall.

It is possible for texture coordinates of a vertex to be greater than 1.0. When you assign texture coordinates to a vertex that are not in the range of 0.0 to 1.0 inclusive, you should also set the texture addressing mode. For more information, see Texture Addressing Modes.

Texture Coordinates and Texture Stages

Texture coordinates are associated with textures by way of texture stages. Textures get assigned to texture stages with SetTexture(stageIndex, pTexture). See IDirect3DDevice9::SetTexture.

A flexible vertex format (FVF) code can define up to eight sets of texture coordinates. The texture coordinate data is furnished by the user in the vertex data. The data is referred to with a zero based index: 0 - 7. There are up to eight texture blending stages. A texture is associated with a particular stage using SetTexture( stageIndex, pTexture).

Once this is done, any set of texture coordinates can be used by any stage. Each set of coordinates is associated with a stage using SetTextureStageState( stageIndex, D3DTSS_TEXCOORDINDEX, textureCoordinateIndex ). See IDirect3DDevice9::SetTextureStageState. This way, the blending stages can be set up to use any texture and any texture coordinates. More than one stage can use the same textures, or texture coordinates.

Additional information is contained in the following topics.

  • Texture Coordinate Formats
  • Texture Coordinate Processing


Texture Coordinate Formats
Microsoft DirectX 9.0 SDK Update (October 2004)

Texture Coordinate Formats

Texture coordinates in Microsoft Direct3D can include one, two, three, or four floating point elements to address textures with varying levels of dimension. A 1-D texture—a texture surface with dimensions of 1-by-n texels—is addressed by one texture coordinate. The most common case, 2-D textures, are addressed with two texture coordinates commonly called u and v. Direct3D supports two types of 3-D textures, cubic-environment maps and volume textures. Cubic environment maps aren't truly 3-D, but they are addressed with a 3-element vector. For details, see Cubic Environment Mapping.

As described in Fixed Function FVF Codes, applications encode texture coordinates in the vertex format. The vertex format can include multiple sets of texture coordinates. Use the D3DFVF_TEX0 through D3DFVF_TEX8 D3DFVF to describe a vertex format that includes no texture coordinates, or as many as eight sets.

Each texture coordinate set can have between one and four elements. The D3DFVF_TEXTUREFORMAT1 through D3DFVF_TEXTUREFORMAT4 flags describe the number of elements in a texture coordinate in a set, but these flags aren't used by themselves. Rather, the D3DFVF_TEXCOORDSIZEn set of macros use these flags to create bit patterns that describe the number of elements used by a particular set of texture coordinates in the vertex format. These macros accept a single parameter that identifies the index of the coordinate set whose number of elements is being defined. The following example illustrates how these macros are used.

// This vertex format contains two sets of texture coordinates.
// The first set (index 0) has 2 elements, and the second set
// has 1 element. The description for this vertex format would be:
//     dwFVF = D3DFVF_XYZ  | D3DFVF_NORMAL | D3DFVF_DIFFUSE | D3DFVF_TEX2 |
//             D3DFVF_TEXCOORDSIZE2(0) | D3DFVF_TEXCOORDSIZE1(1);
//
typedef struct CVF
{
    D3DVECTOR position;
    D3DVECTOR normal;
    D3DCOLOR  diffuse;
    float     u, v;   // 1st set, 2-D
    float     t;      // 2nd set, 1-D
} CustomVertexFormat;
Note With the exception of cubic-environment maps and volume textures, rasterizers cannot address textures by using any more than two elements. Applications can supply up to three elements for a texture coordinate, but only if the texture is a cube map, a volume texture, or the D3DTTFF_PROJECTED texture transform flag is used. The D3DTTFF_PROJECTED flag causes the rasterizer to divide the first two elements by the third (or n) element. For more information, see Texture Coordinate Transformations.


Texture Coordinate Processing
Microsoft DirectX 9.0 SDK Update (October 2004)

Texture Coordinate Processing

The following figure shows the path taken by the texture coordinates from their source, through processing, and to the rasterizer.

Texture coordinate path

There are two sources from which the system can draw texture coordinates. For a given texture stage, you can use texture coordinates included in the vertex format (D3DFVF_TEX1 through D3DFVF_TEX8), or you can use texture coordinates automatically generated by Microsoft Direct3D. For details about the latter case, see Automatically Generated Texture Coordinates. If the D3DTSS_TEXTURETRANSFORMFLAGS texture stage state for the current texture stage is set to D3DTTFF_DISABLE (the default setting), input coordinates are not transformed. If D3DTSS_TEXTURETRANSFORMFLAGS is set to any other value, the transformation matrix for that stage is applied to the input coordinates.

The D3DTEXTURETRANSFORMFLAGS enumerated type defines valid values for the D3DTSS_TEXTURETRANSFORMFLAGS texture-stage state. With the exception of the D3DTTFF_DISABLE flag, which bypasses texture coordinate transformation, the values defined in this enumeration configure the number of output coordinates that the system passes to the rasterizer. The D3DTTFF_COUNT1 through D3DTTFF_COUNT4 flags instruct the system to pass one, two, three, or four elements from the output coordinates to the rasterizer.

The D3DTTFF_PROJECTED flag is special: it tells the system that the texture coordinates are for a projected texture. Combine the D3DTTFF_PROJECTED flag with another member of D3DTEXTURETRANSFORMFLAGS to instruct the rasterizer to divide all the elements by the last element before rasterization takes place. For example, when explicitly using three-element texture coordinates, or when transformation results in a three-element texture coordinate, you can combine the D3DTTFF_COUNT3 and D3DTTFF_PROJECTED flags to cause the rasterizer to divide the first two elements by the last, producing 2-D texture coordinates required to address a 2-D texture.

Note With the exception of cubic-environment maps and volume textures, rasterizers cannot address textures by using texture coordinates with more than two elements. If you specify more elements than can be used to address the current texture for that stage, the extraneous elements are ignored. This also applies when using 2-D texture coordinates for a 1-D texture.

Additional information is contained in the following topics.

  • Automatically Generated Texture Coordinates
  • Texture Coordinate Transformations
  • Special Effects


Automatically Generated Texture Coordinates
Microsoft DirectX 9.0 SDK Update (October 2004)

Automatically Generated Texture Coordinates

The system can use the transformed camera-space position or the normal from a vertex as texture coordinates, or it can compute the three element vectors used to address a cubic environment map. Like texture coordinates that you explicitly specify in a vertex, you can use automatically generated texture coordinates as input for texture coordinate transformations.

Automatically generated texture coordinates can significantly reduce the bandwidth required for geometry data by eliminating the need for explicit texture coordinates in the vertex format. In many cases, the texture coordinates that the system generates can be used with transformations to produce special effects. Of course, this is a special-purpose feature, and you will use explicit texture coordinates for many occasions.

Configuring Automatically Generated Texture Coordinates

In C++, the D3DTSS_TEXCOORDINDEX texture-stage state (from the D3DTEXTURESTAGESTATETYPE enumerated type) controls how the system generates texture coordinates.

Normally, this state instructs the system to use a particular set of texture coordinates encoded in the vertex format. When you include the D3DTSS_TCI_CAMERASPACENORMAL, D3DTSS_TCI_CAMERASPACEPOSITION, or D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR flags in the value that you assign to this state, the system behavior is quite different. If any of these flags are present, the texture stage ignores the texture coordinates within the vertex format in favor of coordinates that the system generates. The meanings for each flag are shown in the following list.

  • D3DTSS_TCI_CAMERASPACENORMAL

    Use the vertex normal, transformed to camera space, as input texture coordinates.

  • D3DTSS_TCI_CAMERASPACEPOSITION

    Use the vertex position, transformed to camera space, as input texture coordinates.

  • D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR

    Use the reflection vector, transformed to camera space, as input texture coordinates. The reflection vector is computed from the input vertex position and normal vector.

The texture coordinate index flags are mutually exclusive. This example uses:

  • The vertex position (in camera-space) as the input texture coordinates for this texture stage
  • The wrap mode set in the D3DRENDERSTATE_WRAP1 render state
// Assume d3dDevice is a valid pointer to an IDirect3DDevice9 interface
d3dDevice->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX,
                                   D3DTSS_TCI_CAMERASPACEPOSITION | 1);

Automatically generated texture coordinates are most useful as input values for a texture coordinate transformation, or to eliminate the need for your application to compute three-element vectors for cubic-environment maps.

Sphere-mapping uses a precomputed (at model time) texture map that contains the entire environment as reflected by a chrome sphere. Microsoft Direct3D has a texture-coordinate generation feature using render state D3DTSS_TCI_CAMERASPACENORMAL, which takes the normal of the vertex in camera space and puts it through a texture transform to generate texture coordinates.

Related Topics

  • Texture Coordinate Transformations
  • Cubic Environment Mapping


Texture Coordinate Transformations
Microsoft DirectX 9.0 SDK Update (October 2004)

Texture Coordinate Transformations

Microsoft Direct3D devices can transform the texture coordinates for vertices by applying a 4x4 matrix. The system applies transformations to texture coordinates in the same manner as geometry. Any transformation (scale, rotation, translation, projection, shear, or any combination of these) can be done with a 4x4 matrix.

Note Direct3D does not modify transformed and lit vertices. As a result, an application using transformed and lit vertices cannot use Direct3D to transform the texture coordinates of the vertices.

Devices that support hardware-accelerated transformation and lighting operations (TnLHAL Device) also accelerate the transformation of texture coordinates. When hardware acceleration of transformations isn't available, platform-specific optimizations in the Direct3D geometry pipeline apply to texture coordinate transformations.

Texture coordinate transformations are useful for producing special effects while avoiding the need to directly modify the texture coordinates of your geometry. You could use simple translation or rotation matrices to animate textures on an object, or you can transform texture coordinates that are automatically generated by Direct3D to simplify and perhaps accelerate advanced effects such as projected textures and dynamic light-mapping. Additionally, you might use texture coordinate transforms to reuse a single set of texture coordinates for multiple purposes, in multiple texture stages.

Setting and Retrieving Texture Coordinate Transformations

Like the matrices that your application uses for geometry, you set and retrieve texture coordinate transformations by calling the IDirect3DDevice9::SetTransform and IDirect3DDevice9::GetTransform methods. These methods accept the D3DTS_TEXTURE0 through D3DTS_TEXTURE7 members of the D3DTRANSFORMSTATETYPE enumerated type to identify the transformation matrices for texture stages 0 through 7, respectively.

The following code sets a matrix to apply to the texture coordinates for texture stage 0.

// For this example, assume the d3dDevice variable contains a
//   valid pointer to an IDirect3DDevice9 interface.

D3DMATRIX matTrans = D3DXMatrixIdentity( NULL );

// Set up the matrix for the desired transformation.
d3dDevice->SetTransform( D3DTS_TEXTURE0, &matTrans );

Enabling Texture Coordinate Transformations

The D3DTSS_TEXTURETRANSFORMFLAGS texture stage state controls the application of texture coordinate transformations. Values for this texture stage state are defined by the D3DTEXTURETRANSFORMFLAGS enumerated type.

Texture coordinate transformations are disabled when D3DTSS_TEXTURETRANSFORMFLAGS is set to D3DTTFF_DISABLE (the default value). Assuming that texture coordinate transformations were enabled for stage 0, the following code disables them.

// For this example, assume the d3dDevice variable contains a
// valid pointer to an IDirect3DDevice9 interface.

d3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS,
                                 D3DTTFF_DISABLE );

The other values defined in D3DTEXTURETRANSFORMFLAGS are used to enable texture coordinate transformations, and to control how many resulting texture coordinate elements are passed to the rasterizer. For example, take the following code.

// For this example, assume the d3dDevice variable contains a
//   valid pointer to an IDirect3DDevice9 interface.

d3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS,
                                 D3DTTFF_COUNT2 );

The D3DTTFF_COUNT2 value instructs the system to apply the transformation matrix set for texture stage 0, and then pass the first two elements of the modified texture coordinates to the rasterizer.

The D3DTTFF_PROJECTED texture transformation flag indicates coordinates for a projected texture. When this flag is specified, the rasterizer divides the elements passed-in by the last element. Take the following code, for example.

// For this example, assume the d3dDevice variable contains a
//   valid pointer to an IDirect3DDevice9 interface.

d3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS,
                                 D3DTTFF_COUNT3 | D3DTTFF_PROJECTED );

This example informs the system to pass three texture coordinate elements to the rasterizer. The rasterizer divides the first two elements by the third, producing the 2-D texture coordinates needed to address the texture.


Special Effects
Microsoft DirectX 9.0 SDK Update (October 2004)

Special Effects

This topic contains examples of special effects accomplished with texture coordinate processing.

  • Animating textures (by translation or rotation) on a model
  • Creating texture coordinates as a linear function of a model's camera-space position
  • Performing environment mapping with a cubic environment map
  • Performing projective texturing

Animating textures (by translation or rotation) on a model

  • Define 2-D texture coordinates in your vertex format.
    // Use a single texture, with 2-D texture coordinates. This
// bit-pattern should be expanded to include position, normal,
// and color information as needed.
DWORD dwFVFTex = D3FVF_TEX1 | D3DFVF_TEXCOORDSIZE2(0);
  • Configure the rasterizer to use 2-D texture coordinates.
    SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2);
  • Define and set an appropriate texture coordinate transformation matrix.
    // M is a D3DMATRIX being set to translate texture
// coordinates in the U and V directions.
//      1   0  0  0
//      0   1  0  0
//      du dv  1  0 (du and dv change each frame)
//      0   0  0  1

D3DMATRIX M = D3DXMatrixIdentity(); // declared in d3dutil.h
M._31 = du;
M._32 = dv;

Creating texture coordinates as a linear function of a model's camera-space position

  • Use the D3DTSS_TCI_CAMERASPACEPOSITION flag to instruct the system to pass the vertex position, in camera space, as input to a texture transformation.
    // The input vertices have no texture coordinates, saving
// bandwidth. Three texture coordinates are generated by
// using vertex position in camera space (x, y, z).
SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION);
  • Instruct the rasterizer to expect 2-D texture coordinates.
    // Two output coordinates are used.
SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2);
  • Define and set a matrix that applies a linear function.
    // Generate texture coordinates as linear functions
// so that:
//      u = Ux*x + Uy*y + Uz*z + Uw
//      v = Vx*x + Vy*y + Vz*z + Vw
// The matrix M for this case is:
//      Ux  Vx  0  0
//      Uy  Vy  0  0
//      Uz  Vz  0  0
//      Uw  Vw  0  0

SetTransform(D3DTS_TEXTURE0, &M);

Performing environment mapping with a cubic environment map

  • Use the D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR flag to instruct the system to automatically generate texture coordinates as reflection vectors for cubic mapping.
    SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR);
  • Instruct the rasterizer to expect texture coordinates with three elements.
    SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT3);

Performing projective texturing

  • Use the D3DTSS_TCI_CAMERASPACEPOSITION flag to instruct the system to pass the vertex position as input to a texture transformation matrix.
    SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION);
  • Create and apply the texture projection matrix. This is beyond the scope of this documentation, and is the topic of several industry articles.
  • Instruct the rasterizer to expect three-element projected texture coordinates.
    // Two output coordinates are used.

SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTF_PROJECTED | D3DTTFF_COUNT3);


Texture Filtering
Microsoft DirectX 9.0 SDK Update (October 2004)

Texture Filtering

When Microsoft Direct3D renders a primitive, it maps the 3-D primitive onto a 2-D screen. If the primitive has a texture, Direct3D must use that texture to produce a color for each pixel in the primitive's 2-D rendered image. For every pixel in the primitive's on-screen image, it must obtain a color value from the texture. This process is called texture filtering.

When a texture filter operation is performed, the texture being used is typically also being magnified or minified. In other words, it is being mapped into a primitive image that is larger or smaller than itself. Magnification of a texture can result in many pixels being mapped to one texel. The result can be a chunky appearance. Minification of a texture often means that a single pixel is mapped to many texels. The resulting image can be blurry or aliased. To resolve these problems, some blending of the texel colors must be performed to arrive at a color for the pixel.

Direct3D simplifies the complex process of texture filtering. It provides you with three types of texture filtering - linear filtering, anisotropic filtering, and mipmap filtering. If you select no texture filtering, Direct3D uses a technique called nearest-point sampling.

Each type of texture filtering has advantages and disadvantages. For instance, linear texture filtering can produce jagged edges or a chunky appearance in the final image. However, it is a computationally low-overhead method of texture filtering. Filtering with mipmaps usually produces the best results, especially when combined with anisotropic filtering. However, it requires the most memory of the techniques that Direct3D supports.

Applications that use texture interface pointers should set the current texture filtering method by calling the IDirect3DDevice9::SetSamplerState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are selecting a texture filtering method. Pass D3DSAMP_MAGFILTER, D3DSAMP_MINFILTER, or D3DSAMP_MIPFILTER for the second parameter to set the magnification, minification, or mipmapping filter. Pass a member of the D3DTEXTUREFILTERTYPE enumerated type as the value in the third parameter.

This section presents the texture filtering methods that Direct3D supports. It is organized into the following topics.

  • Nearest-Point Sampling
  • Linear Texture Filtering
  • Bilinear Texture Filtering
  • Anisotropic Texture Filtering
  • Texture Filtering with Mipmaps
Note Although the texture-filtering render states present in the D3DRENDERSTATETYPE enumerated type are superseded by texture stage states, the IDirect3DDevice9::SetRenderState, as opposed to the IDirect3DDevice2 version, does not fail if you attempt to use them. Rather, the system maps the effects of these render states to the first stage in the multitexture cascade, stage 0. Applications should not mix the legacy render states with their corresponding texture stage states, as unpredictable results can occur.


Nearest-Point Sampling
Microsoft DirectX 9.0 SDK Update (October 2004)

Nearest-Point Sampling

Applications are not required to use texture filtering. Microsoft Direct3D can be set so that it computes the texel address, which often does not evaluate to integers, and copies the color of the texel with the closest integer address. This process is called nearest-point sampling. This can be a fast and efficient way to process textures if the size of the texture is similar to the size of the primitive's image on the screen. If not, the texture must be magnified or minified. The result can be a chunky, aliased, or blurred image.

Your C++ application can select nearest-point sampling by calling the IDirect3DDevice9::SetSamplerState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are selecting a texture filtering method. Pass D3DSAMP_MAGFILTER, D3DSAMP_MINFILTER, or D3DSAMP_MIPFILTER for the second parameter to set the magnification, minification, or mipmapping filter. Pass D3DTEXF_POINT in the third parameter.

You should use nearest-point sampling carefully, because it can sometimes cause graphic artifacts when the texture is sampled at the boundary between two texels. This boundary is the position along the texture (u or v) at which the sampled texel transitions from one texel to the next. When point sampling is used, the system chooses one sample texel or the other, and the result can change abruptly from one texel to the next texel as the boundary is crossed. This effect can appear as undesired graphic artifacts in the displayed texture. When linear filtering is used, the resulting texel is computed from both adjacent texels and smoothly blends between them as the texture index moves through the boundary.

This effect can be seen when mapping a very small texture onto a very large polygon: an operation often called magnification. For example, when using a texture that looks like a checkerboard, nearest-point sampling results in a larger checkerboard that shows distinct edges. By contrast, linear texture filtering results in an image where the checkerboard colors vary smoothly across the polygon.

In most cases, applications receive the best results by avoiding nearest-point sample wherever possible. The majority of hardware today is optimized for linear filtering, so your application should not suffer degraded performance. If the effect you desire absolutely requires the use of the nearest-point sampling - such as when using textures to display readable text characters - then your application should be extremely careful to avoid sampling at the texel boundaries, which might result in undesired effects. The following image shows what these artifacts can look like.

Six-sectioned box with noncontinuous red horizontal lines in the two upper-right squares

Notice that the two squares in the upper right of the group appear different than their neighbors, with diagonal offsets running through them. To avoid graphic artifacts like these, you must be familiar with Direct3D texture sampling rules for nearest-point filtering. Direct3D maps a floating-point texture coordinate ranging from [0.0, 1.0] (0.0 to 1.0, inclusive) to an integer texel space value ranging from [–0.5, n – 0.5], where n is the number of texels in a given dimension on the texture. The resulting texture index is rounded to the nearest integer. This mapping can introduce sampling inaccuracies at texel boundaries.

For a simple example, imagine an application that renders polygons with the D3DTADDRESS_WRAP texture addressing mode. Using the mapping employed by Direct3D, the u texture index maps as follows for a texture with a width of 4 texels.

Texture coordinates 0.0 and 1.0 at the boundary between texels

Notice that the texture coordinates, 0.0 and 1.0 for this illustration, are exactly at the boundary between texels. Using the method by which Direct3D maps values, the texture coordinates range from [–0.5, 4 – 0.5], where 4 is the width of the texture. For this case, the sampled texel is the 0 texel for a texture index of 1.0. However, if the texture coordinate was only slightly less than 1.0, the sampled texel would be the n texel instead of the 0 texel.

The implication of this is that magnifying a small texture using texture coordinates of exactly 0.0 and 1.0 with nearest-point filtering on a screen-space aligned triangle results in pixels for which the texture map is sampled at the boundary between texels. Any inaccuracies in the computation of texture coordinates, however small, results in artifacts along the areas in the rendered image which correspond to the texel edges of the texture map.

Performing this mapping of floating point texture coordinates to integer texels with perfect accuracy is difficult, computationally time-consuming, and generally not necessary. Most hardware implementations use an iterative approach for computing texture coordinates at each pixel location within a triangle. Iterative approaches tend to hide these inaccuracies because the errors are accumulated evenly during iteration.

The Direct3D reference rasterizer uses a direct-evaluation approach for computing texture indexes at each pixel location. Direct evaluation differs from the iterative approach in that any inaccuracy in the operation exhibits a more random error distribution. The result of this is that the sampling errors that occur at the boundaries can be more noticeable because the reference rasterizer does not perform this operation with perfect accuracy.

The best approach is to use nearest-point filtering only when necessary. When you must use it, it is recommended that you offset texture coordinates slightly from the boundary positions to avoid artifacts.


Linear Texture Filtering
Microsoft DirectX 9.0 SDK Update (October 2004)

Linear Texture Filtering

Microsoft Direct3D uses a form of linear texture filtering called bilinear filtering. Like Nearest-Point Sampling, bilinear texture filtering first computes a texel address, which is usually not an integer address. Bilinear filtering then finds the texel whose integer address is closest to the computed address. In addition, the Direct3D rendering module computes a weighted average of the texels that are immediately above, below, to the left of, and to the right of the nearest sample point.

Select bilinear texture filtering by invoking the IDirect3DDevice9::SetSamplerState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are selecting a texture filtering method. Pass D3DSAMP_MAGFILTER, D3DSAMP_MINFILTER, or D3DSAMP_MIPFILTER for the second parameter to set the magnification, minification, or mipmapping filter. Pass D3DTEXF_LINEAR in the third parameter.


Bilinear Texture Filtering
Microsoft DirectX 9.0 SDK Update (October 2004)

Bilinear Texture Filtering

Textures are always linearly addressed from (0.0, 0.0) at the top-left corner to (1.0, 1.0) at the bottom-right corner as shown in Figure 7a:

Textures are usually represented as if they were composed of solid blocks of color, but it's actually more correct to think of textures the same way you should think of the raster display: Each texel is defined at the exact center of a grid cell, as shown in Figure 7b:

If you ask the texture sampler for this texture's color at UV coordinates (0.375, 0.375) you'll get solid red (255, 0, 0). That makes perfect sense because the exact center of the red texel cell is at UV (0.375, 0.375). What if you ask the sampler for the texture's color at UV (0.25, 0.25)? That's not quite as easy, because the point at UV (0.25, 0.25) lies at the exact corner of 4 texels.

The simplest scheme is simply to have the sampler return the color of the closest texel; this is called Point filtering (see Nearest-Point Sampling), and is usually undesirable due to grainy or blocky results. Point-sampling our texture at UV (0.25, 0.25) shows another subtle problem with nearest-point filtering: there are four texels equidistant from the sampling point, so there's no single nearest texel. One of those four texels will be chosen as the returned color, but the selection depends on how the coordinate is rounded, which may introduce tearing artifacts (see the Nearest-Point Sampling article in the software development kit (SDK)).

A slightly more accurate and more common filtering scheme is to calculate the weighted average of the 4 texels closest to the sampling point; this is called Bilinear filtering, and the extra computational cost is usually negligible because this routine is implemented in modern graphics hardware. Here are the colors we get at a few different sample points using bilinear filtering:

UV: (0.5, 0.5)

This point is at the exact border between red, green, blue, and white texels. The color the sampler returns is gray:

  0.25 * (255, 0, 0)
  0.25 * (0, 255, 0)
  0.25 * (0, 0, 255)
+ 0.25 * (255, 255, 255)
------------------------
= (128, 128, 128)

UV: (0.5, 0.375)

This point is at the midpoint of the border between red and green texels. The color the sampler returns is yellow-gray (note that the contributions of the blue and white texels are scaled to 0):

  0.5 * (255, 0, 0)
  0.5 * (0, 255, 0)
  0.0 * (0, 0, 255)
+ 0.0 * (255, 255, 255)
------------------------
= (128, 128, 0)

UV: (0.375, 0.375)

This is the address of the red texel, which is the returned color (all other texels in the filtering calculation are weighted to 0):

  1.0 * (255, 0, 0)
  0.0 * (0, 255, 0)
  0.0 * (0, 0, 255)
+ 0.0 * (255, 255, 255)
------------------------
= (255, 0, 0)

Compare these calculations against Figure 7c, which shows what we'll get if we perform the bilinear filtering calculation at every texture address across the 4x4 texture:


Anisotropic Texture Filtering
Microsoft DirectX 9.0 SDK Update (October 2004)

Anisotropic Texture Filtering

The distortion visible in the texels of a 3-D object whose surface is oriented at an angle with respect to the plane of the screen is called anisotropy. When a pixel from an anisotropic primitive is mapped to texels, its shape is distorted. Microsoft Direct3D measures the anisotropy of a pixel as the elongation - that is, length divided by width - of a screen pixel that is inverse-mapped into texture space.

You can use anisotropic texture filtering in conjunction with linear texture filtering or mipmap texture filtering to improve rendering results. Your application enables anisotropic texture filtering by calling the IDirect3DDevice9::SetSamplerState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are selecting a texture filtering method. Pass D3DSAMP_MAGFILTER, D3DSAMP_MINFILTER, or D3DSAMP_MIPFILTER for the second parameter to set the magnification, minification, or mipmapping filter. Set the third parameter to Pass D3DTEXF_ANISOTROPIC.

Your application must also set the degree of anisotropy to a value greater than one. Do this by calling the IDirect3DDevice9::SetSamplerState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are setting the degree of isotropy. Pass D3DSAMP_MAXANISOTROPY as the value of the second parameter. The final parameter should be the degree of isotropy.

You can disable isotropic filtering by setting the degree of isotropy to one; any value larger than one enables it. Check the MaxAnisotropy flag in the D3DCAPS9 structure to determine the possible range of values for the degree of anisotropy.


Texture Filtering with Mipmaps
Microsoft DirectX 9.0 SDK Update (October 2004)

Texture Filtering with Mipmaps

A mipmap is a sequence of textures, each of which is a progressively lower resolution representation of the same image. The height and width of each image, or level, in the mipmap is a power of two smaller than the previous level. Mipmaps do not have to be square.

A high-resolution mipmap image is used for objects that are close to the user. Lower-resolution images are used as the object appears farther away. Mipmapping improves the quality of rendered textures at the expense of using more memory.

Microsoft Direct3D represents mipmaps as a chain of attached surfaces. The highest resolution texture is at the head of the chain and has the next level of the mipmap as an attachment. In turn, that level has an attachment that is the next level in the mipmap, and so on, down to the lowest resolution level of the mipmap.

The following illustrations shows an example of these levels. The bitmap textures represent a sign on a container in a 3-D first-person game. When created as a mipmap, the highest resolution texture is first in the set. Each succeeding texture in the mipmap set is smaller in height and width by a power of 2. In this case, the maximum-resolution mipmap is 256 pixels by 256 pixels. The next, texture is 128x128. The last texture in the chain is 64x64.

This sign has a maximum distance from which it is visible. If the user begins far away from the sign, the game displays the smallest texture in the mipmap chain, which in this case the 64x64 texture.

As the user moves the point of view closer to the sign, progressively higher-resolution textures in the mipmap chain are used. The resolution in the following illustration is 128x128.

The highest resolution texture is used when the user's point of view is at the minimum allowable distance from the sign.

This is a more efficient way of simulating perspective for textures. Rather than render a single texture at many resolutions, it is faster to use multiple textures at varying resolutions.

Direct3D can assess which texture in a mipmap set is the closest resolution to the desired output, and it can map pixels into its texel space. If the resolution of the final image is between the resolutions of the textures in the mipmap set, Direct3D can examine texels in both mipmaps and blend their color values together.

To use mipmaps, your application must build a set of mipmaps. Applications apply mipmaps by selecting the mipmap set as the first texture in the set of current textures. For more information, see Texture Blending.

Next, your application must set the filtering method that Direct3D uses to sample texels. The fastest method of mipmap filtering is to have Direct3D select the nearest texel. Use the D3DTEXF_POINT enumerated value to select this. Direct3D can produce better filtering results if your application uses the D3DTEXF_LINEAR enumerated value. This selects the nearest mipmap, and then computes a weighted average of the texels surrounding the location in the texture to which the current pixel maps.

Mipmap textures are used in 3-D scenes to decrease the time required to render a scene. They also improve the scene's realism. However, they often require large amounts of memory.

Creating a Set of Mipmaps

The following example shows how your application can call the IDirect3DDevice9::CreateTexture method to build a chain of five mipmap levels: 256x256, 128x128, 64x64, 32x32, and 16x16.

// This code example assumes that m_d3dDevice is a
// valid pointer to a IDirect3DDevice9 interface

IDirect3DTexture9 * pMipMap;
m_pD3DDevice->CreateTexture(256, 256, 5, 0, D3DFMT_R8G8B8,
    D3DPOOL_MANAGED, &pMipMap);

The first two parameters that are accepted by IDirect3DDevice9::CreateTexture are the size and width of the top-level texture. The third parameter specifies the number of levels in the texture. If you set this to zero, Direct3D creates a chain of surfaces, each a power of two smaller than the previous one, down to the smallest possible size of 1x1. The fourth parameter specifies the usage for this resource; in this case, 0 is specified to indicate no specific usage for the resource. The fifth parameter specifies the surface format for the texture. Use a value from the D3DFORMAT enumerated type for this parameter. The sixth parameter specifies a member of the D3DPOOL enumerated type indicating the memory class into which to place the created resource. Unless you are using dynamic textures, D3DPOOL_MANAGED is recommended. The final parameter takes the address of a pointer to an IDirect3DTexture9 interface.

Note Each surface in a mipmap chain has dimensions that are one-half that of the previous surface in the chain. If the top-level mipmap has dimensions of 256x128, the dimensions of the second-level mipmap are 128x64, the third-level are 64x32, and so on, down to 1x1. You cannot request a number of mipmap levels in Levels that would cause either the width or height of any mipmap in the chain to be smaller than 1. In the simple case of a 4x2 top-level mipmap surface, the maximum value allowed for Levels is three. The top-level dimensions are 4x2, the second-level dimensions are 2x1, and the dimensions for the third level are 1x1. A value larger than 3 in Levels results in a fractional value in the height of the second-level mipmap, and is therefore disallowed.

Selecting and Displaying a Mipmap

Call the IDirect3DDevice9::SetTexture method to set the mipmap texture set as the first texture in the list of current textures. For more information, see Texture Blending.

After your application selects the mipmap texture set, it must assign values from the D3DTEXTUREFILTERTYPE enumerated type to the D3DSAMP_MIPFILTER sampler state. Direct3D then automatically performs mipmap texture filtering. Enabling mipmap texture filtering is demonstrated in the following code example.

m_pD3DDevice->SetTexture(0, pMipMap);
m_pD3DDevice->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_POINT);

Your application can also manually traverse a chain of mipmap surfaces by using the IDirect3DTexture9::GetSurfaceLevel method and specifying the mipmap level to retrieve. The following example traverses a mipmap chain from highest to lowest resolutions.

IDirect3DSurface9 * pSurfaceLevel;
for (int iLevel = 0; iLevel < pMipMap->GetLevelCount(); iLevel++)
{
    pMipMap->GetSurfaceLevel(iLevel, &pSurfaceLevel);
    // Process this level
    pSurfaceLevel->Release();
}

Applications need to manually traverse a mipmap chain to load bitmap data into each surface in the chain. This is typically the only reason to traverse the chain. An application can retrieve the number of levels in a mipmap by calling IDirect3DBaseTexture9::GetLevelCount.


Texture Resources
Microsoft DirectX 9.0 SDK Update (October 2004)

Texture Resources

Texture resources are implemented in the IDirect3DTexture9 interface. To obtain a pointer to a texture interface, call the IDirect3DDevice9::CreateTexture method or any of the following D3DX functions.

  • D3DXCreateTexture
  • D3DXCreateTextureFromFile
  • D3DXCreateTextureFromFileEx
  • D3DXCreateTextureFromFileInMemory
  • D3DXCreateTextureFromFileInMemoryEx
  • D3DXCreateTextureFromResource
  • D3DXCreateTextureFromResourceEx

The following code example uses D3DXCreateTextureFromFile to load a texture from Tiger.bmp.

// The following code example assumes that D3dDevice
// is a valid pointer to an IDirect3DDevice9 interface.

LPDIRECT3DTEXTURE9 pTexture;

D3DXCreateTextureFromFile( d3dDevice, "tiger.bmp", &pTexture);

The first parameter that D3DXCreateTextureFromFile accepts is a pointer to an IDirect3DDevice9 interface. The second parameter tells Microsoft Direct3D the name of the file from which to load the texture. The third parameter takes the address of a pointer to an IDirect3DTexture9 interface, representing the created texture object.

Rendering with Texture Resources

Direct3D supports multiple texture blending through the concept of texture stages. Each texture stage contains a texture and operations that can be performed on the texture. The textures in the texture stages form the set of current textures. For more information, see Texture Blending. The state of each texture is encapsulated in its texture stage.

In a C++ application, the state of each texture must be set with the IDirect3DDevice9::SetTextureStageState method. Pass the stage number (0-7) as the value of the first parameter. Set the value of the second parameter to a member of the D3DTEXTURESTAGESTATETYPE enumerated type. The final parameter is the state value for the particular texture state.

Using texture interface pointers, your application can render a blend of up to eight textures. Set the current textures by invoking the IDirect3DDevice9::SetTexture method. Direct3D blends all current textures onto the primitives that it renders.

Note The IDirect3DDevice9::SetTexture method increments the reference count of the texture surface being assigned. When the texture is no longer needed, you should set the texture at the appropriate stage to NULL. If you fail to do this, the surface will not be released, resulting in a memory leak.

Your application can set the texture wrapping state for the current textures by calling the IDirect3DDevice9::SetRenderState method. Pass a value from D3DRS_WRAP0 through D3DRS_WRAP7 as the value of the first parameter, and use a combination of the D3DWRAPCOORD_0, D3DWRAPCOORD_1, D3DWRAPCOORD_2, and D3DWRAPCOORD_3 flags to enable wrapping in the u, v, or w directions.

Your application can also set the texture perspective and texture filtering states. See Texture Filtering.


Texture Wrapping
Microsoft DirectX 9.0 SDK Update (October 2004)

Texture Wrapping

In short, texture wrapping changes the basic way that Microsoft Direct3D rasterizes textured polygons using the texture coordinates specified for each vertex. While rasterizing a polygon, the system interpolates between the texture coordinates at each of the polygon's vertices to determine the texels that should be used for every pixel of the polygon. Normally, the system treats the texture as a 2-D plane, interpolating new texels by taking the shortest route from point A within a texture to point B. If point A represents the u, v position (0.8, 0.1), and point B is at (0.1,0.1), the line of interpolation looks like the following illustration.

Line of interpolation

Note that the shortest distance between A and B in this illustration runs roughly through the middle of the texture. Enabling u-texture or v-texture coordinate wrapping changes how Direct3D perceives the shortest route between texture coordinates in the u-direction and v-direction. By definition, texture wrapping causes the rasterizer to take the shortest route between texture coordinate sets, assuming that 0.0 and 1.0 are coincident. The last bit is the tricky part: You can imagine that enabling texture wrapping in one direction causes the system to treat a texture as though it were wrapped around a cylinder. For example, consider the following illustration.

This diagram shows how wrapping in the u - direction affects how the system interpolates texture coordinates. Using the same points as in the example for normal, or nonwrapped, textures, you can see that the shortest route between points A and B is no longer across the middle of the texture; it's now across the border where 0.0 and 1.0 exist together. Wrapping in the v-direction is similar, except that it wraps the texture around a cylinder that is lying on its side. Wrapping in both the u-direction and v-direction is more complex. In this situation, you can envision the texture as a torus, or doughnut.

The most common practical application for texture wrapping is to perform environment mapping. Usually, an object textured with an environment map appears very reflective, showing a mirrored image of the object's surroundings in the scene. For the sake of this discussion, picture a room with four walls, each one painted with a letter R, G, B, Y and the corresponding colors: red, green, blue, and yellow. The environment map for such a simple room might look like the following illustration.

Vertical stripes of red, green, blue, and yellow

Imagine that the room's ceiling is held up by a perfectly reflective, four-sided, pillar. Mapping the environment map texture to the pillar is simple; making the pillar look as though it is reflecting the letters and colors is not as easy. The following diagram shows a wire frame of the pillar with the applicable texture coordinates listed near the top vertices. The seam where wrapping will cross the edges of the texture is shown with a dotted line.

Rectangle with bisecting dotted line

With wrapping enabled in the u-direction, the textured pillar shows the colors and symbols from the environment map appropriately and, at the seam in the front of the texture, the rasterizer properly chooses the shortest route between the texture coordinates, assuming that u-coordinates 0.0 and 1.0 share the same location. The textured pillar looks like the following illustration.

Rectangle made up of red, green, blue, and yellow quadrants

If texture wrapping isn't enabled, the rasterizer does not interpolate in the direction needed to generate a believable, reflected image. Rather, the area at the front of the pillar contains a horizontally compressed version of the texels between u-coordinates 0.175 and 0.875, as they pass through the center of the texture. The wrap effect is ruined.

Using Texture Wrapping

To enable texture wrapping, call the IDirect3DDevice9::SetRenderState method as shown in the code example below.

d3dDevice->SetRenderState(D3DRS_WRAP0, D3DWRAPCOORD_0);

The first parameter accepted by IDirect3DDevice9::SetRenderState is a render state to set. Specify one of the D3DRS_WRAP0 through D3DRS_WRAP7 enumerated values which specify which texture level to set the wrapping for. Specify the D3DWRAPCOORD_0 through D3DWRAPCOORD_3 flags in the second parameter to enable texture wrapping in the corresponding direction, or combine them to enable wrapping in multiple directions. If you omit a flag, texture wrapping in the corresponding direction is disabled. To disable texture wrapping for a set of texture coordinates, set the value for the corresponding render state to 0.

Do not confuse texture wrapping with the similarly named texture addressing modes. Texture wrapping is performed before texture addressing. Be sure the texture wrapping data does not contain any texture coordinates outside of the range of [0.0, 1.0] because this will produce undefined results. For more information about texture addressing, see Texture Addressing Modes.

Displacement Map Wrapping

Displacement maps are interpolated by the tesselation engine. Because the wrap mode cannot be specified for the tessellation engine, texture wrapping cannot be performed with displacement maps. An application is able to use a set of vertices that forces the interpolation to wrap in any direction. The application can also specify the interpolation to be done as a simple linear interpolation.


Texture Blending
Microsoft DirectX 9.0 SDK Update (October 2004)

Texture Blending

Microsoft Direct3D can blend as many as eight textures onto primitives in a single pass. The use of multiple texture blending can profoundly increase the frame rate of a Direct3D application. An application employs multiple texture blending to apply textures, shadows, specular lighting, diffuse lighting, and other special effects in a single pass.

To use texture blending, your application should first check if the user's hardware supports it. This information is found in the TextureCaps member of the D3DCAPS9 structure. For details on how to query the user's hardware for texture blending capabilities, see IDirect3DDevice9::GetDeviceCaps.

Texture Stages and the Texture Blending Cascade

Direct3D supports single-pass multiple texture blending through the use of texture stages. A texture stage takes two arguments and performs a blending operation on them, passing on the result for further processing or for rasterization. You can visualize a texture stage as shown in the following illustration.

As the preceding illustration shows, texture stages blend two arguments by using a specified operator. Common operations include simple modulation or addition of the color or alpha components of the arguments, but more than two dozen operations are supported. The arguments for a stage can be an associated texture, the iterated color or alpha (iterated during Gouraud shading), arbitrary color and alpha, or the result from the previous texture stage. For more information, see Texture Blending Operations and Arguments.

Note Direct3D distinguishes color blending from alpha blending. Applications set blending operations and arguments for color and alpha individually, and the results of those settings are independent of one another.

The combination of arguments and operations used by multiple blending stages define a simple flow-based blending language. The results from one stage flow down to another stage, from that stage to the next, and so on. The concept of results flowing from stage to stage to eventually be rasterized on a polygon is often called the texture blending cascade. The following illustration shows how individual texture stages make up the texture blending cascade.

Texture blending cascade

Each stage in a device has a zero-based index. Direct3D allows up to eight blending stages, although you should always check device capabilities to determine how many stages the current hardware supports. The first blending stage is at index 0, the second is at 1, and so on, up to index 7. The system blends stages in increasing index order.

Use only the number of stages you need; the unused blending stages are disabled by default. So, if your application only uses the first two stages, it need only set operations and arguments for stage 0 and 1. The system blends the two stages, and ignores the disabled stages.

Performance Note If your application varies the number of stages it uses for different situations - such as four stages for some objects, and only two for others - you don't need to explicitly disable all previously used stages. One option is to disable the color operation for the first unused stage, then all stages with a higher index will not be applied. Another option is to disable texture mapping altogether by setting the color operation for the first texture stage (stage 0). A third option is When a texture stage has D3DTSS_COLORARG1 equal to D3DTA_TEXTURE and the texture pointer for the stage is NULL, this stage and all stages after it are not processed.

Additional information is contained in the following topics.

  • Texture Blending Operations and Arguments
  • Assigning the Current Textures
  • Creating Blending Stages
  • Alpha Texture Blending
  • Multipass Texture Blending
  • Light Mapping with Textures


Texture Blending Operations and Arguments
Microsoft DirectX 9.0 SDK Update (October 2004)

Texture Blending Operations and Arguments

Applications associate a blending stage with each texture in the set of current textures. Microsoft Direct3D evaluates each blending stage in order, beginning with the first texture in the set and ending with the eighth.

Direct3D applies the information from each texture in the set of current textures to the blending stage that is associated with it. Applications control what information from a texture stage is used by calling IDirect3DDevice9::SetTextureStageState. You can set separate operations for the color and alpha channels, and each operation uses two arguments. Specify color channel operations by using the D3DTSS_COLOROP stage state; specify alpha operations by using D3DTSS_ALPHAOP. Both stage states use values from the D3DTEXTUREOP enumerated type.

Texture blending arguments use the D3DTSS_COLORARG1, D3DTSS_COLORARG2, D3DTSS_ALPHARG1, and D3DTSS_ALPHARG2 members of the D3DTEXTURESTAGESTATETYPE enumerated type. The corresponding argument values are identified using D3DTA.

Note You can disable a texture stage—and any subsequent texture blending stages in the cascade—by setting the color operation for that stage to D3DTOP_DISABLE. Disabling the color operation effectively disables the alpha operation as well. Alpha operations cannot be disabled when color operations are enabled. Setting the alpha operation to D3DTOP_DISABLE when color blending is enabled causes undefined behavior.

To determine the supported texture blending operations of a device, query the TextureCaps member of the D3DCAPS9 structure.


Assigning the Current Textures
Microsoft DirectX 9.0 SDK Update (October 2004)

Assigning the Current Textures

Microsoft Direct3D maintains a list of up to eight current textures. It blends these textures onto all the primitive it renders. Only textures created as texture interface pointers can be used in the set of current textures.

Applications call the IDirect3DDevice9::SetTexture method to assign textures into the set of current textures. The first parameter must be from the a number in the range of 0-7, inclusive. Pass the texture interface pointer as the second parameter.

The following C++ code example demonstrates how a texture can be assigned to the set of current textures.

// This code example assumes that the variable lpd3dDev is a
// valid pointer to an IDirect3DDevice9 interface and pTexture
// is a valid pointer to an IDirect3DBaseTexture9 interface.

// Set the third texture.
d3dDevice->SetTexture(2, pTexture);
Note Software devices do not support assigning a texture to more than one texture stage at a time.


Creating Blending Stages
Microsoft DirectX 9.0 SDK Update (October 2004)

Creating Blending Stages

A blending stage is a set of texture operations and their arguments that define how textures are blended. When making a blending stage, C++ applications invoke the IDirect3DDevice9::SetTextureStageState method. The first call specifies the operation that is performed. Two additional invocations define the arguments to which the operation is applied. The following code example illustrates the creation of a blending stage.

// This example assumes that lpD3DDev is a valid pointer to an
// IDirect3DDevice9 interface.

// Set the operation for the first texture.
d3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_ADD);

// Set argument 1 to the texture color.
d3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);

// Set argument 2 to the iterated diffuse color.
d3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);

Texel data in textures contain color and alpha values. Applications can define separate operations for both color and alpha values in a single blending stage. Each operation, color, and alpha, has its own arguments. For details, see D3DTEXTURESTAGESTATETYPE.

Although not part of the Microsoft Direct3D application programming interface (API), you can insert the following macros into your application to abbreviate the code required for creating texture blending stages.

#define SetTextureColorStage( dev, i, arg1, op, arg2 )     \
   dev->SetTextureStageState( i, D3DTSS_COLOROP, op);      \
   dev->SetTextureStageState( i, D3DTSS_COLORARG1, arg1 ); \
   dev->SetTextureStageState( i, D3DTSS_COLORARG2, arg2 );

#define SetTextureAlphaStage( dev, i, arg1, op, arg2 )     \
   dev->SetTextureStageState( i, D3DTSS_ALPHAOP, op);      \
   dev->SetTextureStageState( i, D3DTSS_ALPHAARG1, arg1 );  \
   dev->SetTextureStageState( i  D3DTSS_ALPHAARG2, arg2 );


Alpha Texture Blending
Microsoft DirectX 9.0 SDK Update (October 2004)

Alpha Texture Blending

The lighting engine combines material color, vertex color, and lighting information to generate a per-vertex color. Once interpolated, this generates a per-pixel color that is written to the frame buffer. If an application enables texture blending, the pixel color will become a combination of the current pixel in the frame buffer and a texture color.

This formula determines the final blended pixel color:

Color = TexelColor x SourceBlend + CurrentPixelColor x DestBlend

Where:

  • Color is the output pixel color.
  • TexelColor is the input color after texture filtering.
  • SourceBlend is the percentage of the final pixel color that is made up of the source texel color.
  • CurrentPixelColor is the color of the current pixel.
  • DestBlend is the percentage of the final pixel color that is made up of the current pixel color.

The final blending equation is set by calling IDirect3DDevice9::SetRenderState and specifying the blend render state (D3DRS_BLENDXXX) with a corresponding blending factor (D3DBLEND). The values of SourceBlend and DestBlend range from 0.0 (transparent) to 1.0 (opaque) inclusive. In addition, an application can control the transparency of a pixel by setting the alpha value in a texture. In this case, use the following:

SourceBlend = D3DBLEND_ZERO
DestBlend = D3DBLEND_ONE

The blending equation will cause the rendered pixel to be transparent. The default values are:

SourceBlend = D3DBLEND_SRCALPHA
DestBlend = D3DBLEND_INVSRCALPHA

Related Topics

  • Texture Filtering
  • D3DRENDERSTATETYPE


Multipass Texture Blending
Microsoft DirectX 9.0 SDK Update (October 2004)

Multipass Texture Blending

Microsoft Direct3D applications can achieve numerous special effects by applying various textures to a primitive over the course of multiple rendering passes. The common term for this is multipass texture blending. A typical use for multipass texture blending is to emulate the effects of complex lighting and shading models by applying multiple colors from several different textures. One such application is called light mapping. For more information, see Light Mapping with Textures.

Note Some devices are capable of applying multiple textures to primitives in a single pass. For details, see Texture Blending.

If the user's hardware does not support multiple texture blending, your application can use multipass texture blending to achieve the same visual effects. However, the application cannot sustain the frame rates that are possible when using multiple texture blending.

To perform multipass texture blending in a C/C++ application.

  1. Set a texture in texture stage 0 by calling the IDirect3DDevice9::SetTexture method.
  2. Select the desired color and alpha blending arguments and operations with the IDirect3DDevice9::SetTextureStageState method. The default settings are well-suited for multipass texture blending.
  3. Render the appropriate objects in the scene.
  4. Set the next texture in texture stage 0.
  5. Set the D3DRS_SRCBLEND and D3DRS_DESTBLEND render states to adjust the source and destination blending factors as needed. The system blends the new textures with the existing pixels in the render-target surface according to these parameters.
  6. Repeat Steps 3, 4, and 5 with as many textures as needed.


Light Mapping with Textures
Microsoft DirectX 9.0 SDK Update (October 2004)

Light Mapping with Textures

For an application to realistically render a 3-D scene, it must take into account the effect that light sources have on the appearance of the scene. Although techniques such as flat and Gouraud shading are valuable tools in this respect, they can be insufficient for your needs. Microsoft Direct3D supports multipass and multiple texture blending. These capabilities enable your application to render scenes with a more realistic appearance than scenes rendered with shading techniques alone. By applying one or more light maps, your application can map areas of light and shadow onto its primitives.

A light map is a texture or group of textures that contains information about lighting in a 3-D scene. You can store the lighting information in the alpha values of the light map, in the color values, or in both.

If you implement light mapping using multipass texture blending, your application should render the light map onto its primitives on the first pass. It should use a second pass to render the base texture. The exception to this is specular light mapping. In that case, render the base texture first; then add the light map.

Multiple texture blending enables your application to render the light map and the base texture in one pass. If the user's hardware provides for multiple texture blending, your application should take advantage of it when performing light mapping. This significantly improves your application's performance.

Using light maps, a Direct3D application can achieve a variety of lighting effects when it renders primitives. It can map not only monochrome and colored lights in a scene, but it can also add details such as specular highlights and diffuse lighting.

Information on using Direct3D texture blending to perform light mapping is presented in the following topics.

  • Monochrome Light Maps
  • Color Light Maps
  • Specular Light Maps
  • Diffuse Light Maps


Monochrome Light Maps
Microsoft DirectX 9.0 SDK Update (October 2004)

Monochrome Light Maps

Some older 3-D accelerator boards do not support texture blending using the alpha value of the destination pixel. See Alpha Texture Blending for more information. These adapters also generally do not support multiple texture blending. If your application is running on an adapter such as this, it can use multipass texture blending to perform monochrome light mapping.

To perform monochrome light mapping, an application stores the lighting information in the alpha data of its light map textures. The application uses the texture filtering capabilities of Microsoft Direct3D to perform a mapping from each pixel in the primitive's image to a corresponding texel in the light map. It sets the source blending factor to the alpha value of the corresponding texel.

The following C++ code example illustrates how an application can use a texture as a monochrome light map.

// This example assumes that d3dDevice is a valid pointer to an
// IDirect3DDevice9 interface and that lptexLightMap is a valid
// pointer to a texture that contains monochrome light map data.

// Set the light map texture as the current texture.
d3dDevice->SetTexture(0, lptexLightMap);

// Set the color operation.
d3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);

// Set argument 1 to the color operation.
d3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1,
       D3DTA_TEXTURE | D3DTA_ALPHAREPLICATE);

Because display adapters that do not support destination alpha blending usually do not support multiple texture blending, this example sets the light map as the first texture, which is available on all 3-D accelerator cards. The sample code sets the color operation for the texture's blending stage to blend the texture data with the primitive's existing color. It then selects the first texture and the primitive's existing color as the input data.


Color Light Maps
Microsoft DirectX 9.0 SDK Update (October 2004)

Color Light Maps

Your application will usually render 3-D scenes more realistically if it uses colored light maps. A colored light map uses the RGB data in the light map for its lighting information.

The following C++ code example demonstrates light mapping with RGB color data.

// This example assumes that d3dDevice is a valid pointer to an
// IDirect3DDevice9 interface and that lptexLightMap is a valid
// pointer to a texture that contains RGB light map data.

// Set the light map texture as the first texture.
d3dDevice->SetTexture(0, lptexLightMap);

d3dDevice->SetTextureStageState( 0,D3DTSS_COLOROP, D3DTOP_MODULATE );
d3dDevice->SetTextureStageState( 0,D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState( 0,D3DTSS_COLORARG2, D3DTA_DIFFUSE );

This example sets the light map as the first texture. It then sets the state of the first blending stage to modulate the incoming texture data. It uses the first texture and the current color of the primitive as the arguments to the modulate operation.


Specular Light Maps
Microsoft DirectX 9.0 SDK Update (October 2004)

Specular Light Maps

When illuminated by a light source, shiny objects - those that use highly reflective materials - receive specular highlights. In some cases, the specular highlights produced by the lighting module is not accurate. To produce a more appealing highlight, many Microsoft Direct3D applications apply specular light maps to primitives.

To perform specular light mapping, add the specular light map to the primitive's texture, then modulate (multiply the result by) the RGB light map.

The following code example illustrates this process in C++.

// This example assumes that d3dDevice is a valid pointer to an
// IDirect3DDevice9 interface.
// lptexBaseTexture is a valid pointer to a texture.
// lptexSpecLightMap is a valid pointer to a texture that contains RGB
// specular light map data.
// lptexLightMap is a valid pointer to a texture that contains RGB
// light map data.

// Set the base texture.
d3dDevice->SetTexture(0, lptexBaseTexture );

// Set the base texture operation and arguments.
d3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE );
d3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );

// Set the specular light map.
d3dDevice->SetTexture(1, lptexSpecLightMap);

// Set the specular light map operation and args.
d3dDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_ADD );
d3dDevice->SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_CURRENT );

// Set the RGB light map.
d3dDevice->SetTexture(2, lptexLightMap);

// Set the RGB light map operation and arguments.
d3dDevice->SetTextureStageState(2,D3DTSS_COLOROP, D3DTOP_MODULATE);
d3dDevice->SetTextureStageState(2,D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState(2,D3DTSS_COLORARG2, D3DTA_CURRENT );


Diffuse Light Maps
Microsoft DirectX 9.0 SDK Update (October 2004)

Diffuse Light Maps

When illuminated by a light source, matte surfaces display diffuse light reflection. The brightness of diffuse light depends on the distance from the light source and the angle between the surface normal and the light source direction vector. The diffuse lighting effects simulated by lighting calculations produce only general effects.

Your application can simulate more complex diffuse lighting with texture light maps. Do this by adding the diffuse light map to the base texture, as shown in the following C++ code example.

// This example assumes that d3dDevice is a valid pointer to an
// IDirect3DDevice9 interface.
// lptexBaseTexture is a valid pointer to a texture.
// lptexDiffuseLightMap is a valid pointer to a texture that contains
// RGB diffuse light map data.

// Set the base texture.
d3dDevice->SetTexture(0,lptexBaseTexture );

// Set the base texture operation and args.
d3dDevice->SetTextureStageState(0,D3DTSS_COLOROP,
       D3DTOP_MODULATE );
d3dDevice->SetTextureStageState(0,D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState(0,D3DTSS_COLORARG2, D3DTA_DIFFUSE );

// Set the diffuse light map.
d3dDevice->SetTexture(1,lptexDiffuseLightMap );

// Set the blend stage.
d3dDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE );
d3dDevice->SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_CURRENT );


Automatic Generation of Mipmaps
Microsoft DirectX 9.0 SDK Update (October 2004)

Automatic Generation of Mipmaps

You can now automatically create a mipmap which is a series of textures, each filtered to a different resolution. Mipmaps are commonly used to provide different levels of detail when rendering. Automatically generating mipmaps at texture creation time takes advantage of hardware filtering because the mipmap resides in video memory.

To generate a mipmap automatically, set a new usage D3DUSAGE_AUTOGENMIPMAP before calling IDirect3DDevice9::CreateTexture. Sublevel generation from this point on is completely transparent to the application. Only the top texture level is accessible to the application; the texture sublevels are not accessible since they will be created only when needed by the driver. In cases where sublevel generation may take a lot of time, use IDirect3DBaseTexture9::GenerateMipSubLevels to hint to the driver that it should generate sublevels at a time appropriate for the application.

Mipmap Filtering

IDirect3DBaseTexture9::SetAutoGenFilterType controls the filtering quality during automatic generation. Changing the filter type dirties the mipmap sublevels and causes them to be regenerated. Use IDirect3DBaseTexture9::GetAutoGenFilterType to get the current filter type. The default filter type is D3DTEXF_LINEAR. If the driver doesn't support a linear filter, the filter type will be set to D3DTEXF_POINT.

These methods have no effect if the texture is not created with D3DUSAGE_AUTOGENMIPMAP and no failure is returned. All filter types supported by the driver for regular texture filtering are supported for autogenerated except D3DTEXF_NONE. For each resource type, drivers should support all the filter types reported in the corresponding texture, cubetexture, and volumetexture filter caps.

To check which filter types are supported, check to see which caps are supported by the TextureFilterCaps and/or CubeTextureFilterCaps members of D3DCAPS9.

Mipmap Support

D3DUSAGE_AUTOGENMIPMAP is only a hint, and specifying this during texture creation or when calling IDirect3D9::CheckDeviceFormat would not cause an error on any of the device driver interface (DDI) types.

Calling IDirect3DDevice9::UpdateTexture is illegal when the source is an automatically generated mipmap, but the destination is not. The source can be a non-automatically generated mipmap and the destination can be an automatically generated mipmap. In this case, only the topmost matching level is updated. All other source sublevels are ignored. Similarly, when both the source and destination are automatically generated, only the topmost matching level is updated. The sublevels from the source are ignored and the destination sublevels are regenerated.

To check for support for automatic generation of mipmaps, check to see that D3DCAPS2_CANAUTOGENMIPMAP is set. If it is, call IDirect3D9::CheckDeviceFormat with D3DUSAGE_AUTOGENMIPMAP. If the return value is D3D_OK, the mipmaps are guaranteed to be autogenerated. If the return value is D3DOK_NOAUTOGEN, this means that the create call will succeed, but there won't be any mipmaps generated.


Automatic Texture Management
Microsoft DirectX 9.0 SDK Update (October 2004)

Automatic Texture Management

Texture management is the process of determining which textures are needed for rendering at a given time and ensuring that those textures are loaded into video memory. As with any algorithm, texture management schemes vary in complexity, but any approach to texture management involves the following key tasks.

  • Tracking the amount of available texture memory.
  • Calculating which textures are needed for rendering, and which are not.
  • Determining which existing texture resources can be reloaded with another texture image, and which surfaces should be destroyed and replaced with new texture resources.

Microsoft Direct3D implements system-supported texture management to ensure that textures are loaded for optimal performance. Texture resources that Direct3D manages are referred to as managed textures.

The texture manager tracks textures with a time-stamp that identifies when the texture was last used. It then uses a least-recently-used algorithm to determine which textures should be removed. Texture priorities are used as tie breakers when two textures are targeted for removal from memory. If two textures have the same priority value, the least-recently-used texture is removed. However, if two textures have the same time-stamp, the texture that has a lower priority is removed first.

You request automatic texture management for texture surfaces when you create them. To retrieve a managed texture in a C++ application, create a texture resource by calling IDirect3DDevice9::CreateTexture and specifying the D3DPOOL_MANAGED for the Pool parameter. You are not allowed to specify where you want the texture created. You cannot use the D3DPOOL_DEFAULT or D3DPOOL_SYSTEMMEM flags when creating a managed texture. After creating the managed texture, you can call the IDirect3DDevice9::SetTexture method to set it to a stage in the rendering device's texture cascade.

You can assign a priority to managed textures by calling the IDirect3DResource9::SetPriority method for the texture surface.

Direct3D automatically downloads textures into video memory as needed. The system might cache managed textures in local or nonlocal video memory, depending on the availability of nonlocal video memory or other factors. The cache location of your managed textures is not communicated to your application, nor is this information required to use automatic texture management. If your application uses more textures than can fit in video memory, Direct3D removes older textures from video memory to make room for the new textures. If you use a removed texture again, the system uses the original system-memory texture surface to reload the texture in the video-memory cache. Although reloading the texture is necessary, it also decreases the application's performance.

You can dynamically modify the original system-memory copy of the texture by updating or locking the texture resource. When the system detects a dirty surface—after an update is completed, or when the surface is unlocked—the texture manager automatically updates the video-memory copy of the texture. The performance hit incurred is similar to reloading a removed texture.

When entering a new level in a game, your application might need to flush all managed textures from video memory (by calling IDirect3DDevice9::EvictManagedResources).

For more information about resource management, see Managing Resources.


Compressed Texture Resources
Microsoft DirectX 9.0 SDK Update (October 2004)

Compressed Texture Resources

Texture maps are digitized images drawn on three-dimensional shapes to add visual detail. They are mapped into these shapes during rasterization, and the process can consume large amounts of both the system bus and memory. To reduce the amount of memory consumed by textures, Microsoft Direct3D supports the compression of texture surfaces. Some Direct3D devices support compressed texture surfaces natively. On such devices, when you have created a compressed surface and loaded the data into it, the surface can be used in Direct3D like any other texture surface. Direct3D handles decompression when the texture is mapped to a 3-D object.

Storage Efficiency and Texture Compression

All texture compression formats are powers of two. While this does not mean that a texture is necessarily square, it does mean that both x and y are powers of two. For example, if a texture is originally 512 by 128 bytes, the next mipmapping would be 256 by 64 and so on, with each level decreasing by a power of two. At lower levels, where the texture is filtered to 16 by 2 and 8 by 1, there will be wasted bits because the compression block is always a 4 by 4 block of texels. Unused portions of the block are padded. Although there are wasted bits at the lowest levels, the overall gain is still significant. The worst case is, in theory, a 2K by 1 texture (20 power). Here, only a single row of pixels is encoded per block, while the rest of the block is unused.

Mixing Formats Within a Single Texture

It is important to note that any single texture must specify that its data is stored as 64 or 128 bits per group of 16 texels. If 64-bit blocks - that is, format DXT1 - are used for the texture, it is possible to mix the opaque and 1-bit alpha formats on a per-block basis within the same texture. In other words, the comparison of the unsigned integer magnitude of color_0 and color_1 is performed uniquely for each block of 16 texels.

Once the 128-bit blocks are used, the alpha channel must be specified in either explicit (format DXT2 and DXT3) or interpolated mode (format DXT4 and DXT5) for the entire texture. As with color, when interpolated mode (format DXT4 and DXT5) is selected, then either eight interpolated alphas or six interpolated alphas mode can be used on a block-by-block basis. Again the magnitude comparison of alpha_0 and alpha_1 is done uniquely on a block-by-block basis.

Direct3D provides services to compress surfaces that are used for texturing 3-D models. This section provides information about creating and manipulating the data in a compressed texture surface.

Information is contained in the following topics.

  • Opaque and 1-Bit Alpha Textures
  • Textures with Alpha Channels
  • Compressed Texture Formats
  • Using Compressed Textures


Opaque and 1-Bit Alpha Textures
Microsoft DirectX 9.0 SDK Update (October 2004)

Opaque and 1-Bit Alpha Textures

Texture format DXT1 is for textures that are opaque or have a single transparent color.

For each opaque or 1-bit alpha block, two 16-bit values (RGB 5:6:5 format) and a 4x4 bitmap with 2 bits per pixel are stored. This totals 64 bits for 16 texels, or four bits per texel. In the block bitmap, there are 2 bits per texel to select between the four colors, two of which are stored in the encoded data. The other two colors are derived from these stored colors by linear interpolation. This layout is shown in the following diagram.

The 1-bit alpha format is distinguished from the opaque format by comparing the two 16-bit color values stored in the block. They are treated as unsigned integers. If the first color is greater than the second, it implies that only opaque texels are defined. This means four colors are used to represent the texels. In four-color encoding, there are two derived colors and all four colors are equally distributed in RGB color space. This format is analogous to RGB 5:6:5 format. Otherwise, for 1-bit alpha transparency, three colors are used and the fourth is reserved to represent transparent texels.

In three-color encoding, there is one derived color and the fourth 2-bit code is reserved to indicate a transparent texel (alpha information). This format is analogous to RGBA 5:5:5:1, where the final bit is used for encoding the alpha mask.

The following code example illustrates the algorithm for deciding whether three- or four-color encoding is selected.

if (color_0 > color_1)
{
    // Four-color block: derive the other two colors.
    // 00 = color_0, 01 = color_1, 10 = color_2, 11 = color_3
    // These 2-bit codes correspond to the 2-bit fields
    // stored in the 64-bit block.
    color_2 = (2 * color_0 + color_1 + 1) / 3;
    color_3 = (color_0 + 2 * color_1 + 1) / 3;
}
else
{
    // Three-color block: derive the other color.
    // 00 = color_0,  01 = color_1,  10 = color_2,
    // 11 = transparent.
    // These 2-bit codes correspond to the 2-bit fields
    // stored in the 64-bit block.
     color_2 = (color_0 + color_1) / 2;
     color_3 = transparent;

}

It is recommended that you set the RGBA components of the transparency pixel to zero before blending.

The following tables show the memory layout for the 8-byte block. It is assumed that the first index corresponds to the y-coordinate and the second corresponds to the x-coordinate. For example, Texel[1][2] refers to the texture map pixel at (x,y) = (2,1).

This table contains the memory layout for the 8-byte (64-bit) block.

Word address | 16-bit word
0 | Color_0
1 | Color_1
2 | Bitmap Word_0
3 | Bitmap Word_1

Color_0 and Color_1, the colors at the two extremes, are laid out as follows:

Bits | Color
4:0 (LSB*) | Blue color component
10:5 | Green color component
15:11 | Red color component

*least significant bit (LSB)

Bitmap Word_0 is laid out as follows:

Bits | Texel
1:0 (LSB) | Texel[0][0]
3:2 | Texel[0][1]
5:4 | Texel[0][2]
7:6 | Texel[0][3]
9:8 | Texel[1][0]
11:10 | Texel[1][1]
13:12 | Texel[1][2]
15:14 (MSB*) | Texel[1][3]

*most significant bit (MSB)

Bitmap Word_1 is laid out as follows:

Bits | Texel
1:0 (LSB) | Texel[2][0]
3:2 | Texel[2][1]
5:4 | Texel[2][2]
7:6 | Texel[2][3]
9:8 | Texel[3][0]
11:10 | Texel[3][1]
13:12 | Texel[3][2]
15:14 (MSB) | Texel[3][3]

Example of Opaque Color Encoding

As an example of opaque encoding, assume that the colors red and black are at the extremes. Red is color_0, and black is color_1. There are four interpolated colors that form the uniformly distributed gradient between them. To determine the values for the 4x4 bitmap, the following calculations are used.

00 ? color_0
01 ? color_1
10 ? 2/3 color_0 + 1/3 color_1
11 ? 1/3 color_0 + 2/3 color_1

The bitmap then looks like the following graphic.

Expanded bitmap layout

This looks like the following series of colors.

Opaque encoded gradient

Example of 1-Bit Alpha Encoding

This format is selected when the unsigned 16-bit integer, color_0, is less than the unsigned 16-bit integer, color_1. An example of where this format can be used is leaves on a tree, shown against a blue sky. Some texels can be marked as transparent while three shades of green are still available for the leaves. Two colors fix the extremes, and the third is an interpolated color.

Here is an example of such a picture.

1-bit alpha example

Note that where the image is shown as white, the texel would be encoded as transparent. Also note that the RGBA components of the transparent texels should be set to zero before blending.

The bitmap encoding for the colors and the transparency is determined using the following calculations.

00 ? color_0
01 ? color_1
10 ? 1/2 color_0 + 1/2 color_1
11   ?   Transparent

The bitmap then looks like the following graphic.

Expanded bitmap layout


Textures with Alpha Channels
Microsoft DirectX 9.0 SDK Update (October 2004)

Textures with Alpha Channels

There are two ways to encode texture maps that exhibit more complex transparency. In each case, a block that describes the transparency precedes the 64-bit block already described. The transparency is either represented as a 4x4 bitmap with 4 bits per pixel (explicit encoding), or with fewer bits and linear interpolation that is analogous to what is used for color encoding.

The transparency block and the color block are arranged as shown in the following table.

Word address | 64-bit block
3:0 | Transparency block
7:4 | Previously described 64-bit block

Explicit Texture Encoding

For explicit texture encoding (DXT2 and DXT3 formats), the alpha components of the texels that describe transparency are encoded in a 4x4 bitmap with 4 bits per texel. These four bits can be achieved through a variety of means such as dithering or by using the four most significant bits of the alpha data. However they are produced, they are used just as they are, without any form of interpolation.

The following diagram shows a 64-bit transparency block.

64-bit transparency block

Note The compression method of Microsoft Direct3D uses the four most significant bits.

The following tables illustrate how the alpha information is laid out in memory, for each 16-bit word.

This table contains the layout for word 0.

Bits | Alpha
3:0 (LSB*) | [0][0]
7:4 | [0][1]
11:8 | [0][2]
15:12 (MSB*) | [0][3]

*least significant bit (LSB), most significant bit (MSB)

This table contains the layout for word 1.

Bits | Alpha
3:0 (LSB) | [1][0]
7:4 | [1][1]
11:8 | [1][2]
15:12 (MSB) | [1][3]

This table contains the layout for word 2.

Bits | Alpha
3:0 (LSB) | [2][0]
7:4 | [2][1]
11:8 | [2][2]
15:12 (MSB) | [2][3]

This table contains the layout for word 3.

Bits | Alpha
3:0 (LSB) | [3][0]
7:4 | [3][1]
11:8 | [3][2]
15:12 (MSB) | [3][3]

The difference between DXT2 and DXT3 are that, in the DXT2 format, it is assumed that the color data has been premultiplied by alpha. In the DXT3 format, it is assumed that the color is not premultiplied by alpha. These two formats are needed because, in most cases, by the time a texture is used, just examining the data is not sufficient to determine if the color values have been multiplied by alpha. Because this information is needed at run time, the two four-character code (FOURCC) codes are used to differentiate these cases. However, the data and interpolation method used for these two formats is identical.

The color compare used in DXT1 to determine if the texel is transparent is not used in this format. It is assumed that without the color compare the color data is always treated as if in 4-color mode. In other words, the if statement at the top of the DXT1 code should be the following:

if ((color_0 > color_1) OR !DXT1) {

Three-Bit Linear Alpha Interpolation

The encoding of transparency for the DXT4 and DXT5 formats is based on a concept similar to the linear encoding used for color. Two 8-bit alpha values and a 4x4 bitmap with three bits per pixel are stored in the first eight bytes of the block. The representative alpha values are used to interpolate intermediate alpha values. Additional information is available in the way the two alpha values are stored. If alpha_0 is greater than alpha_1, then six intermediate alpha values are created by the interpolation. Otherwise, four intermediate alpha values are interpolated between the specified alpha extremes. The two additional implicit alpha values are 0 (fully transparent) and 255 (fully opaque).

The following code example illustrates this algorithm.

// 8-alpha or 6-alpha block?
if (alpha_0 > alpha_1) {
    // 8-alpha block:  derive the other six alphas.
    // Bit code 000 = alpha_0, 001 = alpha_1, others are interpolated.
    alpha_2 = (6 * alpha_0 + 1 * alpha_1 + 3) / 7;    // bit code 010
    alpha_3 = (5 * alpha_0 + 2 * alpha_1 + 3) / 7;    // bit code 011
    alpha_4 = (4 * alpha_0 + 3 * alpha_1 + 3) / 7;    // bit code 100
    alpha_5 = (3 * alpha_0 + 4 * alpha_1 + 3) / 7;    // bit code 101
    alpha_6 = (2 * alpha_0 + 5 * alpha_1 + 3) / 7;    // bit code 110
    alpha_7 = (1 * alpha_0 + 6 * alpha_1 + 3) / 7;    // bit code 111
}
else {
    // 6-alpha block.
    // Bit code 000 = alpha_0, 001 = alpha_1, others are interpolated.
    alpha_2 = (4 * alpha_0 + 1 * alpha_1 + 2) / 5;    // Bit code 010
    alpha_3 = (3 * alpha_0 + 2 * alpha_1 + 2) / 5;    // Bit code 011
    alpha_4 = (2 * alpha_0 + 3 * alpha_1 + 2) / 5;    // Bit code 100
    alpha_5 = (1 * alpha_0 + 4 * alpha_1 + 2) / 5;    // Bit code 101
    alpha_6 = 0;                                      // Bit code 110
    alpha_7 = 255;                                    // Bit code 111
}

The memory layout of the alpha block is as follows:

Byte | Alpha
0 | Alpha_0
1 | Alpha_1
2 | [0][2] (2 LSBs), [0][1], [0][0]
3 | [1][1] (1 LSB), [1][0], [0][3], [0][2] (1 MSB)
4 | [1][3], [1][2], [1][1] (2 MSBs)
5 | [2][2] (2 LSBs), [2][1], [2][0]
6 | [3][1] (1 LSB), [3][0], [2][3], [2][2] (1 MSB)
7 | [3][3], [3][2], [3][1] (2 MSBs)

The difference between DXT4 and DXT5 is that in the DXT4 format it is assumed that the color data has been premultiplied by alpha. In the DXT5 format, it is assumed the color is not premultiplied by alpha. These two formats are needed because, in most cases, by the time a texture is used, just examining the data is not sufficient to determine if the color values have been multiplied by alpha. Because this information is needed at run time, the two FOURCC codes are used to differentiate these cases. However, the data and interpolation method used for these two formats is identical.

The color compare used in DXT1 to determine if the texel is transparent is not used with these formats. It is assumed that without the color compare the color data is always treated as if in 4-color mode. In other words, the if statement at the top of the DXT1 code should be:

if ((color_0 > color_1) OR !DXT1) {


Compressed Texture Formats
Microsoft DirectX 9.0 SDK Update (October 2004)

Compressed Texture Formats

This section contains information about the internal organization of compressed texture formats. You do not need these details to use compressed textures, because you can use D3DX functions for conversion to and from compressed formats. However, this information is useful if you want to operate on compressed surface data directly.

Microsoft Direct3D uses a compression format that divides texture maps into 4x4 texel blocks. If the texture contains no transparency—is opaque—or if the transparency is specified by a 1-bit alpha, an 8-byte block represents the texture map block. If the texture map does contain transparent texels, using an alpha channel, a 16-byte block represents it.

  • Opaque and 1-Bit Alpha Textures
  • Textures with Alpha Channels
Note Any single texture must specify that its data is stored as 64 or 128 bits per group of 16 texels. If 64-bit blocks—that is, format DXT1—are used for the texture, it is possible to mix the opaque and 1-bit alpha formats on a per-block basis within the same texture. In other words, the comparison of the unsigned integer magnitude of color_0 and color_1 is performed uniquely for each block of 16 texels.

When 128-bit blocks are used, the alpha channel must be specified in either explicit (format DXT2 or DXT3) or interpolated mode (format DXT4 or DXT5) for the entire texture. As with color, when interpolated mode is selected, either eight interpolated alphas or six interpolated alphas mode can be used on a block-by-block basis. Again the magnitude comparison of alpha_0 and alpha_1 is done uniquely on a block-by-block basis.

The pitch for DXTn formats is different from what was returned in Microsoft DirectX 7.0. It now refers the pitch of a row of blocks. For example, if you have a width of 16, then you will have a pitch of four blocks (4*8 for DXT1, 4*16 for DXT2-5.)


Using Compressed Textures
Microsoft DirectX 9.0 SDK Update (October 2004)

Using Compressed Textures

Determining Support for Compressed Textures

Before your application creates a rendering device, it can determine if the device supports texturing from compressed texture surfaces by calling the IDirect3D9::CheckDeviceFormat method. This method determines whether a surface format can be used as a texture on a device representing the adapter.

To test the adapter, specify any pixel format that uses the DXT1, DXT2, DXT3, DXT4, or DXT5 four-character codes (FOURCCs). If IDirect3D9::CheckDeviceFormat returns D3D_OK, the device can create texture directly from a compressed texture surface that uses that format. If so, you can use compressed texture surfaces directly with Microsoft Direct3D by calling the IDirect3DDevice9::SetTexture method. The following code example shows how to determine if the adapter supports a compressed texture format.

BOOL IsCompressedTextureFormatOk( D3DFORMAT TextureFormat,
                                  D3DFORMAT AdapterFormat )
{
    HRESULT hr = pD3D->CheckDeviceFormat( D3DADAPTER_DEFAULT,
                                          D3DDEVTYPE_HAL,
                                          AdapterFormat,
                                          0,
                                          D3DRTYPE_TEXTURE,
                                          TextureFormat);

    return SUCCEEDED( hr );
}

If the device does not support texturing from compressed texture surfaces, you can still store texture data in a compressed format surface, but you must convert any compressed textures to a supported format before they can be used for texturing.

Creating Compressed Textures

After creating a device that supports a compressed texture format on the adapter, you can create a compressed texture resource. Call IDirect3DDevice9::CreateTexture and specify a compressed texture format for the Format parameter.

Before loading an image into a texture object, retrieve a pointer to the texture surface by calling the IDirect3DTexture9::GetSurfaceLevel method.

Now you can use any D3DXLoadSurface xxx function to load an image to the surface that was retrieved by using IDirect3DTexture9::GetSurfaceLevel. These functions handle conversion to and from compressed texture formats.

You can create and convert compressed texture (DDS) files using the DXTex supplied with the software development kit (SDK).

The advantage of this behavior is that an application can copy the contents of a compressed surface to a file without calculating how much storage is required for a surface of a particular width and height in the specific format.

The following table shows the five types of compressed textures. For more information about how the data is stored, see Compressed Texture Formats. You only need this information if you are writing your own compression routines.

FOURCC | Description | Alpha premultiplied?
DXT1 | Opaque/1-bit alpha | N/A
DXT2 | Explicit alpha | Yes
DXT3 | Explicit alpha | No
DXT4 | Interpolated alpha | Yes
DXT5 | Interpolated alpha | No

When you transfer data from a nonpremultiplied format to a premultiplied format, Direct3D scales the colors based on the alpha values. Transferring data from a premultiplied format to a nonpremultiplied format is not supported. If you try to transfer data from a premultiplied alpha source to a nonpremultiplied alpha destination, the method returns D3DERR_INVALIDCALL. If you transfer data from a premultiplied alpha source to a destination that has no alpha, the source color components, which have been scaled by alpha, are copied as is.

Decompressing Compressed Texture Surfaces

As with compressing a texture surface, decompressing a compressed texture is performed through Direct3D copying services.

To copy a compressed texture surface to a uncompressed texture surface, use the function D3DXLoadSurfaceFromSurface. This functions handles compression to and from compressed and uncompressed surfaces.


Hardware Considerations for Texturing
Microsoft DirectX 9.0 SDK Update (October 2004)

Hardware Considerations for Texturing

Current hardware does not necessarily implement all the functionality that the Microsoft Direct3D interface enables. Your application must test user hardware and adjust its rendering strategies accordingly.

Many 3-D accelerator cards do not support diffuse iterated values as arguments to blending units. However, your application can introduce iterated color data when it performs texture blending.

Some 3-D hardware may not have a blending stage associated with the first texture. On these adapters, your application must perform blending in the second and third texture stages in the set of current textures.

Because of limitations in much of today's hardware, few display adapters can perform trilinear mipmap interpolation through the multiple texture blending interface offered by IDirect3DDevice9. Your application can use multipass texture blending to achieve the same effects, or degrade to the D3DTEXF_POINT mipmap filter mode, which is widely supported.


Volume Texture Resources
Microsoft DirectX 9.0 SDK Update (October 2004)

Volume Texture Resources

Volume textures are three-dimensional collections of pixels (texels) that can be used to paint a two-dimensional primitive such as a triangle or a line. Three-element texture coordinates are required for each vertex of a primitive that is to be textured with a volume. As the primitive is drawn, each contained pixel is filled with the color value from some pixel within the volume, in accordance with rules analogous to the two-dimensional texture case. Volumes are not rendered directly because there are no three-dimensional primitives that can be painted with them.

You can use volume textures for special effects such as patchy fog, explosions, and so on.

Volumes are organized into slices and can be thought of as width x height 2-D surfaces stacked to make a width x height x depth volume. Each slice is a single row. Volumes can have subsequent levels in which the dimensions of each level are truncated to half the dimensions of the previous level. The illustration below gives an idea of what a volume texture with multiple levels looks like.

Volume texture with 8x2x4, 4x1x2, and 2x1x1 cube representations

Creating a Volume Texture

The code examples below show the steps required to use a volume texture.

First, specify a custom vertex type that has three texture coordinates for each vertex, as shown in this code example.

struct VOLUMEVERTEX
{
    FLOAT x, y, z;
    DWORD color;
    FLOAT tu, tv, tw;
};

#define D3DFVF_VOLUMEVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|
                             D3DFVF_TEX1|D3DFVF_TEXCOORDSIZE3(0))

Next, fill the vertices with data.

VOLUMEVERTEX g_vVertices[4] =
{
    { 1.0f, 1.0f, 0.0f, 0xffffffff, 1.0f, 1.0f, 0.0f },
    {-1.0f, 1.0f, 0.0f, 0xffffffff, 0.0f, 1.0f, 0.0f },
    { 1.0f,-1.0f, 0.0f, 0xffffffff, 1.0f, 0.0f, 0.0f },
    {-1.0f,-1.0f, 0.0f, 0xffffffff, 0.0f, 0.0f, 0.0f }
};

Now, create a vertex buffer and fill it with data from the vertices.

The next step is to use the IDirect3DDevice9::CreateVolumeTexture method to create a volume texture, as shown in this code example.

LPDIRECT3DVOLUMETEXTURE9 pVolumeTexture;
d3dDevice->CreateVolumeTexture( 8, 4, 4, 1, 0, D3DFMT_R8G8B8,D3DPOOL_MANAGED,
                                &pVolumeTexture );

Before rendering the primitive, set the current texture to the volume texture created above. The code example below shows the entire rendering process for a strip of triangles.

if( SUCCEEDED( d3dDevice->BeginScene() ) )
{
    // Draw the quad, with the volume texture.
    d3dDevice->SetTexture( 0, pVolumeTexture );
    d3dDevice->SetFVF( D3DFVF_VOLUMEVERTEX );
    d3dDevice->SetStreamSource( 0, pVB, sizeof(VOLUMEVERTEX) );
    d3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 2);

   // End the scene.
   d3dDevice->EndScene();
}


D3DX Support
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DX Support

D3DX is a library of tools designed to provide additional graphics functionality on top of Microsoft Direct3D. D3DX is not part of the operating system (and could be implemented by any application). The D3DX library is statically linked to your application. Because it is a helper library, you should not assume it is thread-safe.

The D3DX library addresses these general areas of functionality:

  • Line Drawing Support in D3DX
  • Mesh Support in D3DX
  • Math Function Support in D3DX
  • Texture Support in D3DX

Overloading the New and Delete Operators

Be careful when overloading the new and delete operators. Because your application is statically linked with the D3DX libraries D3dx9.lib, D3dx9d.lib, and D3dx9dt.lib, incorrect overloading of the new and delete operators may cause problems when compiling shaders with functions such as D3DXCreateEffect.


Line Drawing Support in D3DX
Microsoft DirectX 9.0 SDK Update (October 2004)

Line Drawing Support in D3DX

D3DX is a utility library that provides helper services. It is a layer above the Microsoft Direct3D component.

D3DX supports single-pixel-wide antialiased lines. Line patterns are no longer supported.

The line drawing library emulates lines using texture triangles and assumes the following:

  • Hardware is available through the Microsoft DirectX 9.0 interfaces.
  • At least one texture stage is available.
  • 64x64 textures are used.
  • The following modes are available:
    • Bilinear filtering
    • Clamp address mode
    • Wrap address mode
    • Alpha op modulate
    • Alpha blending (SRCBLEND = SRC_ALPHA, DESTBLEND = INV_SRC_ALPHA)
    • Alpha test if alpha blending is not available; lower quality result

For antialiased line rendering in multisample render targets, use ID3DXLine which generates textured polygons. The pixel coverage values, generated by antialiased line rasterization, modulate the pixel's alpha value computed by the pixel shader. To draw an antialiased line, an application must enable alpha blending and then it must set the D3DRS_ANTIALIASEDLINEENABLE render state to TRUE.

Functionality Description

The library supports drawing colored line strips with the following line features, each of which is independent of any other:

  • Line width
  • Line pattern with repetition (the line pattern counter resets with each ID3DXLine::Draw or ID3DXLine::DrawTransform call. It does not reset with each segment of the line strip.)
  • Antialiasing
  • OpenGL-style lines
Note No mitering is supported.

The library uses native hardware line drawing support (if available in the device) only if:

  • Line width is 1.
  • No line pattern is enabled.

Single-pixel-wide antialiased lines are supported by some hardware, so the library uses that, if available. The LineCaps member of the D3DCAPS9 structure enumerates hardware capabilities for line-drawing primitives.

When the software line drawing is used, each line is expanded into a rectangle and four vertices are sent down to the driver.

Each line segment is drawn with two triangles. The width of the primitive is the specified width plus 1.0, which may result in an extra row or column of pixels. As the line gets wider, the antialias gradient in the texture becomes more coarse, and more fully-opaque texels are replicated around the middle. The gradient is encoded in the v-direction of the texture, and typically replicated along the u-direction. The texture addressing mode for v is clamp.

Each line segment in the list can be considered to be a separate line that happens to start from the previous end point.

Antialiasing quality along the edges parallel to the length of the original line suffers as the line gets wider. It is expected that line widths greater than 32.0 will start to exhibit artifacts along these edges.


Math Function Support in D3DX
Microsoft DirectX 9.0 SDK Update (October 2004)

Math Function Support in D3DX

D3DX is a utility library that provides helper services. It is a layer above the Microsoft Direct3D component.

Math

Math support, contained in a set of functions, is provided for:

  • Color calculations
  • Planes
  • Matrix manipulation
  • Quaternions
  • 2-D vectors
  • 3-D vectors
  • 4-D vectors

Please note that when coupled with the C++ overloads, the support for basic 3-D math types is extensive.

For more information about these functions, see Functions. To help find the function you need, they are broken up in several folders.

FLOAT16

When using the FLOAT16 data type, be sure to limit values to a maximum of D3DX_16F_MAX. Any FLOAT16 value that exceeds this will result in undefined behavior in the pipeline. See Other D3DX Constants.


Mesh Support in D3DX
Microsoft DirectX 9.0 SDK Update (October 2004)

Mesh Support in D3DX

D3DX is a utility library that provides helper services. It is a layer above the Microsoft Direct3D component.

Meshes

D3DX implements the mesh construct to load, manipulate, and render .x file contents. A mesh is basically a collection of vertices defining some geometry, and a set of indices defining the faces. There are several mesh types.

ID3DXBaseMesh provides the fundamentals. ID3DXMesh and ID3DXPMesh inherit from ID3DXBaseMesh, and add, respectively, mesh optimization using per-chip vertex cache and progressive meshes modeled after Hugues Hoppe's progressive mesh work. ID3DXSPMesh provides simplification meshes and ID3DXSkinInfo provides skinned mesh support.

ID3DXBaseMesh provides methods to manipulate and query ID3DXMesh and ID3DXPMesh progressive-mesh objects, which inherit from the base mesh. This includes adjacency operations, geometry buffer retrieval, lock/unlock operations (vertex and index), and copying, rendering, face, and vertex information.

Mesh Architecture

A mesh contains the data for a complex model. It is an abstract data container that contains resources such as textures and materials, and attributes such as position data and adjacency data. There are several mesh operations that improve drawing performance and the appearance of a surface. In addition, there are a number of other mesh concepts that will effect the functionality of mesh operations. Understanding these mesh concepts so you can apply them will improve mesh performance.

Mesh Object Data

A mesh contains a vertex buffer, an index buffer, and an attribute buffer.

  • The vertex buffer contains the vertex data, which are the mesh vertices.
  • The index buffer contains vertex indices for accessing the vertex buffer. This can reduce the vertex buffer size by reducing duplicate vertices. Only an indexed mesh uses the index buffer. If a mesh is made up of a triangle list, for example, it does not use the index buffer.
  • The attribute buffer contains attribute data. Attributes are properties of the mesh vertices, in no particular order. A D3DX mesh stores attributes in a group of DWORDS, for each face.

Attribute Tables

An attribute table is a concise representation of the contents of an attribute buffer. Attribute tables can be created by calling one of the Optimize methods with D3DXMESHOPT_ATTRSORT, by locking the attribute buffer and filling it with data, or by calling SetAttributeTable. A mesh contains an attribute table when the mesh is reordered into groups. This happens when Optimize is called, assuming an attribute sorting option (D3DXMESHOPT_ATTRSORT or higher) is supplied. D3DX Meshes use indexed triangle lists, and are therefore drawn with IDirect3DDevice9::DrawIndexedPrimitive.

Attribute tables are created as a result of calling Optimize. The faces don't have to be adjacent, because Optimize will reorder them to be adjacent. For example, the hands of a human mesh could use the same attribute. The attribute identifier (ID) helps sort the faces into groups. Meshes from .x files have automatically generated attributes for material and texture properties. You do need to call Optimize(ATTRSORT) or the more effective Optimize(VERTEXCACHE) to get good performance. The load functions try to present the data in the exact form it was saved out in. If you are using a vertex buffer/index buffer based mesh, the mesh application programming interface (API) provides optimization functions and skinning transformations with little overhead.

The optimization types are cumulative, starting from the least optimal (D3DXMESHOPT_COMPACT) to the most optimal (D3DXMESHOPT_IGNOREVERTS). D3DXMESHOPT_STRIPREORDER does a compaction and attribute sort. D3DXMESHOPT_VERTEXCACHE is always recommended, even on devices without a true vertex cache.

Application Data

Application data is mesh data that is managed by an application. There is a tight coupling between the mesh vertex data and the data managed by these buffers.

The materials buffer contains n materials. The materials are returned by the Load function when the .x file is loaded. Each subset can have its own materials and textures. The materials buffer is static.

The adjacency buffer contains information about edges, faces, and adjacent faces. Some mesh operations depend on knowing which faces are adjacent to each other. This information, called adjacency data, is kept in an adjacency buffer. It is not part of the mesh but is maintained by the application and must be supplied to the mesh methods when necessary.

The effects instance buffer contains a list of effect instances. An effect instance stores state. This state information is used to initialize the pipeline. An effect instance contains name-value pairs in an effect.

Advanced Mesh Topics

Optimized meshes build on the base mesh functionality and add vertex-cache optimization capability with two methods: Optimize, which creates a new mesh, and OptimizeInPlace, which modifies the original mesh.

Progressive meshes are based on Hugues Hoppe's SIGGRAPH papers (from the Association for Computing Machinery's Special Interest Group, Graphics), with updated error metrics. The ID3DXPMesh adds methods for copying, face and vertex manipulation, and optimization.

D3DXGeneratePMesh uses the D3DX simplification algorithm to generate a progressive mesh from the input mesh. D3DXSimplifyMesh generates a standard mesh of the given level of detail (LOD) from an input mesh using the same simplification algorithm. The user has control over the error metric used through the weights specified per-vertex component and weights specified per vertex. Per-component weights are multiplied against that components portion of error calculated per edge collapse. Per-vertex weights are multiplied against the error metric value determined for removal of that vertex. For example, if you never want a vertex to be removed, set that specific vertex's weight to a large value. Conversely, if you want it removed earlier, set it to a small value (less than 1).

ID3DXSkinInfo supports skinned characters. A skinned character is defined by a set of meshes and a set of bones that affect the vertices of the meshes. The bones are represented as a transform hierarchy. For each mesh, there is a matrix for every bone that affects it, which transforms the mesh into the local coordinate space of the bone. This matrix is the bone-space transform of the bone for the mesh. This is defined at the time the skeleton is associated with the mesh in the authoring process.

Skinning

Skinning is a technique for transforming mesh vertices using bones. Bones are typically arranged in a hierarchical skeleton, much like the bones in a human body. Object vertices are then associated with the bones, like attaching skin to the bones. When the bones get transformed, the skin is also transformed.

Skinned meshes use bones to influence a number of vertices. Bone transformation data is supplied by the user, to influence how to scale, rotate, and translate (SRT) the bones. The mesh uses the transformed bones to influence the vertices associated with the bones. Palettes are arrays of SRT transformations. Palettes are often implemented as matrices, but they can contain SRT values.

Progressive Mesh Trimming

Low detail areas can afford to lose vertices which don't change the rendered appearance of the surface. This is especially true of objects as they move farther from the camera. This is referred to as LOD. Users have API-level render controls for setting the LOD to maximize rendering efficiency.

Progressive mesh objects start with a high number of faces and use simplification to reduce the number of faces. A progressive mesh that is view independent is referred to as a view-independent progressive mesh (VIPM).

Another way to reduce the number of faces is by trimming. This actually removes vertices and faces from the mesh. Trimming can be done at the high end (to limit the max number of faces) or at the low end (to limit the minimum number of faces.) Trimming improves draw performance, however, care should be used to preserve the visual quality. Trimming is demonstrated in the Progressive Mesh software development kit (SDK) Sample.

For high visibility areas, the resolution can be increased using progressive level of detail (PLOD). This is a technique for breaking a single face into two faces.

Patch Meshes

Two specialized types of patch meshes are also supported: rectangle and triangle patches. The rectangle patch mesh is a patch mesh whose control points are laid out in a winding, rectangular sequence. Rectangle and triangle patches are used to create high-order surfaces. They are not as commonly used as triangle meshes.


Texture Support in D3DX
Microsoft DirectX 9.0 SDK Update (October 2004)

Texture Support in D3DX

D3DX is a utility library that provides helper services. It is a layer above the Microsoft Direct3D component.

Textures

Many different textures are supported in the following topics.

  • Standard mipmapped texture support. See Automatic Generation of Mipmaps.
  • Cube map support. See Cubic Environment Mapping.
  • Volume texture support. See Volume Texture Resources.
  • Environment mapping support. See Environment Mapping.
  • Bump mapping support. See Bump Mapping.

Texture Color Conversion

When using any of the D3DXLoadSurfacexxx, D3DXLoadVolumexxx, D3DXCreateTexturexxx, D3DXCreateCubeTexturexxx, or D3DXCreateVolumeTexturexxx functions, color conversion might need to be performed. For example, one surface might be type RGBA and the other might be UVWQ. For cases of dissimilar formats, the conversion sequence is as follows:

Mapping RGBA to UVWQ(L)

  • R <-> U, R channel is mapped to the U channel, or vice versa.
  • G <-> V, G channel is mapped to the V channel, or vice versa.
  • B <-> W, B channel is mapped to the W channel, or vice versa.
  • A <-> Q/L, A channel is mapped to either the Q or the L channel (depending on which one is available in the destination format), or vice versa.
R->U
G->V
B->W
A->Q or A->L

Mapping UV to RGBA

  • U <-> R, U channel is mapped to the R channel, or vice versa.
  • V <-> G, V channel is mapped to the G channel, or vice versa.
  • 1 <-> B, 1 is mapped to the B channel, or vice versa.
  • 1 <-> A, 1 is mapped to the A channel, or vice versa.

If a channel does not exist in the source, it is assumed to be 1 (with the exception of A8, where R,G,B are assumed to be 0). For example:

U -> R
V -> G
1 -> B
1 -> A


X Files (Legacy)
Microsoft DirectX 9.0 SDK Update (October 2004)

X Files (Legacy)

The X file format refers to files with the .x file name extension. X files were introduced with Microsoft DirectX 2.0. A binary version of this format was subsequently released with DirectX 3.0, which is also described in this documentation. DirectX 6.0 introduced interfaces and methods that enable reading from and writing to .x files.

X files provide a template-driven format that enables the storage of meshes, textures, animations, and user-definable objects. Support for animation sets enables you to store predefined paths for playback in real time. Instancing and hierarchies are also supported. Instancing enables multiple references to an object, such as a mesh, while storing its data only once per file. Hierarchies are used to express relationships between data records.

The .x file format provides low-level data primitives on which applications define higher-level primitives through templates.

Three-dimensional models created in Discreet's 3ds max or Alias|Wavefront's Maya applications can be converted to .x files by using plug-ins that ship with the DirectX software development kit (SDK). See X File Exporter for Discreet's 3ds max and Effect File Exporter (Maya Preview Pipeline).

This section describes the structure of .x files and how to use them in your applications. Information is divided into the following topics.

  • Loading an X File (Legacy)
  • Saving to an X File (Legacy)
  • Defining a Simple Cube
  • Adding Textures
  • Adding Frames and Animations

For more information about the .x file format, see X File Reference (Legacy).

For more information about the .x file API that is new with the DirectX 9.0 SDK Update (Summer 2004), see X File Reference.


Loading an X File (Legacy)
Microsoft DirectX 9.0 SDK Update (October 2004)

Loading an X File (Legacy)

Use the following procedure in legacy applications to load a .x file.

  1. Use the DirectXFileCreate function to create an IDirectXFile object.
  2. If templates are present in the Microsoft DirectX file that you will load, use the IDirectXFile::RegisterTemplates method to register those templates.
  3. Use the IDirectXFile::CreateEnumObject method to create an IDirectXFileEnumObject enumerator object.
  4. Loop through the objects in the file. For each object, perform the following steps.
    1. Use the IDirectXFileEnumObject::GetNextDataObject method to retrieve each IDirectXFileData object.
    2. Use the IDirectXFileData::GetType method to retrieve the data's type.
    3. Load the data using the IDirectXFileData::GetData method.
    4. If the object has optional members, retrieve the optional members by calling the IDirectXFileData::GetNextObject method.
    5. Release the IDirectXFileData object.
  5. Release the IDirectXFileEnumObject object.
  6. Release the IDirectXFile object.


Saving to an X File (Legacy)
Microsoft DirectX 9.0 SDK Update (October 2004)

Saving to an X File (Legacy)

Use the following procedure in legacy applications to save .x file templates and data to a .x file.

  1. Use the DirectXFileCreate function to create an IDirectXFile object.
  2. Use the IDirectXFile::RegisterTemplates method to inform the Microsoft DirectX file system about any templates that you will use.
  3. Use the IDirectXFile::CreateSaveObject method to create an IDirectXFileSaveObject object.
  4. Use the IDirectXFileSaveObject::SaveTemplates method to save templates, if desired.
  5. Loop through the objects to save. For each top-level object, perform the following steps.
    • Use the IDirectXFileSaveObject::CreateDataObject method to create an IDirectXFileData object as a top-level object in the file. If the top-level data object has optional child objects, add them to the object by using the appropriate method from the next step.
    • Each IDirectXFileData object can have optional child objects if its template allows it. The child objects can be any of the three types of objects: IDirectXFileData, IDirectXFileDataReference, or IDirectXFileBinary. Loop through the objects you need to save, adding each optional child member to the object list in the manner appropriate to its type, as illustrated in the following steps. Then, if the object type is Data, call the IDirectXFileSaveObject::CreateDataObject method to create an IDirectXFileData object, and then call the IDirectXFileData::AddDataObject method to add it as a child of the object. If the object type is Data Reference, call the IDirectXFileData::AddDataReference method to create and add the data reference object as a child of the object. Or, if the object type is Binary, call the IDirectXFileData::AddBinaryObject method to create and add the binary object as a child of the object.
    • Call the IDirectXFileSaveObject::SaveData method to save the data object and its children.
    • Release the IDirectXFileData object.
  6. Release the IDirectXFileSaveObject object.
  7. Release the IDirectXFile object.

Related Topics

  • X File Exporter for Discreet's 3ds max


Defining a Simple Cube
Microsoft DirectX 9.0 SDK Update (October 2004)

Defining a Simple Cube

The following file defines a simple cube that has four red sides and two green sides. In this file, optional information is used to add information to the data object defined by the Mesh template.

Material RedMaterial {
1.000000;0.000000;0.000000;1.000000;;    // R = 1.0, G = 0.0, B = 0.0
0.000000;
0.000000;0.000000;0.000000;;
0.000000;0.000000;0.000000;;
}

Material GreenMaterial {
0.000000;1.000000;0.000000;1.000000;;     // R = 0.0, G = 1.0, B = 0.0
0.000000;
0.000000;0.000000;0.000000;;
0.000000;0.000000;0.000000;;
}

// Define a mesh with 8 vertices and 12 faces (triangles). Use
// optional data objects in the mesh to specify materials, normals,
// and texture coordinates.
Mesh CubeMesh {
8;                                // 8 vertices.
1.000000;1.000000;-1.000000;,     // Vertex 0.
-1.000000;1.000000;-1.000000;,    // Vertex 1.
-1.000000;1.000000;1.000000;,     // And so on.
1.000000;1.000000;1.000000;,
1.000000;-1.000000;-1.000000;,
-1.000000;-1.000000;-1.000000;,
-1.000000;-1.000000;1.000000;,
1.000000;-1.000000;1.000000;;

12;                      // 12 faces.
3;0,1,2;,                // Face 0 has three vertices.
3;0,2,3;,                // And so on.
3;0,4,5;,
3;0,5,1;,
3;1,5,6;,
3;1,6,2;,
3;2,6,7;,
3;2,7,3;,
3;3,7,4;,
3;3,4,0;,
3;4,7,6;,
3;4,6,5;;

// All required data has been defined. Now define optional data
// using the hierarchical nature of the file format.
MeshMaterialList {
2;                    // Number of materials used.
12;                   // A material for each face.
0,                    // Face 0 uses the first material.
0,
0,
0,
0,
0,
0,
0,
1,                    // Face 8 uses the second material.
1,
1,
1;;
{RedMaterial}         // References to the definitions
{GreenMaterial}       // of material 0 and 1.
}
MeshNormals {
8;                    // Define 8 normals.
0.333333;0.666667;-0.666667;,
-0.816497;0.408248;-0.408248;,
-0.333333;0.666667;0.666667;,
0.816497;0.408248;0.408248;,
0.666667;-0.666667;-0.333333;,
-0.408248;-0.408248;-0.816497;,
-0.666667;-0.666667;0.333333;,
0.408248;-0.408248;0.816497;;
12;                   // For the 12 faces, define the normals.
3;0,1,2;,
3;0,2,3;,
3;0,4,5;,
3;0,5,1;,
3;1,5,6;,
3;1,6,2;,
3;2,6,7;,
3;2,7,3;,
3;3,7,4;,
3;3,4,0;,
3;4,7,6;,
3;4,6,5;;
}
MeshTextureCoords {
8;                        // Define texture coords for each vertex.
0.000000;1.000000;
1.000000;1.000000;
0.000000;1.000000;
1.000000;1.000000;
0.000000;0.000000;
1.000000;0.000000;
0.000000;0.000000;
1.000000;0.000000;;
}


Adding Textures
Microsoft DirectX 9.0 SDK Update (October 2004)

Adding Textures

To add textures, use the hierarchical nature of the file format and add an optional TextureFilename data object to the Material data objects. The Material objects now read as follows:

Material RedMaterial {
1.000000;0.000000;0.000000;1.000000;;    // R = 1.0, G = 0.0, B = 0.0
0.000000;
0.000000;0.000000;0.000000;;
0.000000;0.000000;0.000000;;
TextureFilename { "tex1.ppm"; }
}

Material GreenMaterial {
0.000000;1.000000;0.000000;1.000000;;     // R = 0.0, G = 1.0, B = 0.0
0.000000;
0.000000;0.000000;0.000000;;
0.000000;0.000000;0.000000;;
TextureFilename { "win95.ppm"; }
}


Adding Frames and Animations
Microsoft DirectX 9.0 SDK Update (October 2004)

Adding Frames and Animations

This section shows how to add frames and animations to a simple cube.

Working with Frames

A frame is expected to take the following structure.

Frame Aframe {        // The frame name is chosen for convenience.
FrameTransformMatrix {
...transform data...
}
[ Meshes ] and/or [ More frames]
}

Place the defined cube mesh inside a frame with an identity transform. Then apply an animation to this frame.

Frame CubeFrame {
FrameTransformMatrix {
1.000000, 0.000000, 0.000000, 0.000000,
0.000000, 1.000000, 0.000000, 0.000000,
0.000000, 0.000000, 1.000000, 0.000000,
0.000000, 0.000000, 0.000000, 1.000000;;
}
{CubeMesh}        // You could have the mesh inline, but this
                  // uses an object reference instead.
}

Working with Animations

An animation is defined by a set of keys. A key is a time value associated with a scaling operation, an orientation, or a position.

Animation Animation0 {        // The name is chosen for convenience.
{ Frame that it applies to - normally a reference }
AnimationKey {
...animation key data...
}
{ ...more animation keys... }
}

Animations are then grouped into AnimationSets:

AnimationSet AnimationSet0 { // The name is chosen for convenience.
{ an animation - could be inline or a reference }
{ ... more animations ... }
}

Now take the cube through an animation.

AnimationSet AnimationSet0 {
Animation Animation0 {
{CubeFrame}    // Use the frame containing the cube.
AnimationKey {
2;             // Position keys
9;             // 9 keys
10; 3; -100.000000, 0.000000, 0.000000;;,
20; 3; -75.000000, 0.000000, 0.000000;;,
30; 3; -50.000000, 0.000000, 0.000000;;,
40; 3; -25.500000, 0.000000, 0.000000;;,
50; 3; 0.000000, 0.000000, 0.000000;;,
60; 3; 25.500000, 0.000000, 0.000000;;,
70; 3; 50.000000, 0.000000, 0.000000;;,
80; 3; 75.500000, 0.000000, 0.000000;;,
90; 3; 100.000000, 0.000000, 0.000000;;;
}
}
}

For more information, see the Animation and AnimationSet templates.


The Sample Framework
Microsoft DirectX 9.0 SDK Update (October 2004)

The Sample Framework

The sample framework is a layer used by most of the Microsoft Direct3D tutorials and samples and is built on top of the Microsoft Windows application programming interface (API) and the Direct3D API. Its goal is to make Direct3D samples, prototypes, and tools as well as professional games more robust and easier to build. It simplifies the Windows and Direct3D APIs for typical usage and is designed to help make simple to moderately complex Direct3D applications.

Use of the framework is covered in the following topics:

  • Sample Framework Overview
  • Initializing the Sample Framework
  • Using Application Windows with the Sample Framework
  • Using Devices with the Sample Framework
  • Using the Main Loop with the Sample Framework
  • Error Handling with the Sample Framework
  • Advanced Device Selection with the Sample Framework
  • Additional Sample Framework Functions

For documentation on the API elements provided by the framework, see Sample Framework Reference.


Sample Framework Overview
Microsoft DirectX 9.0 SDK Update (October 2004)

Sample Framework Overview

This topic gives a high-level introduction to the Microsoft Direct3D Sample Framework.

  • Overview
  • Features
  • Limitations
  • Starting a New Project
  • Changes from the Previous Sample Framework

Overview

The framework is designed to help the programmer spend less time worrying about how to create a window, how to create a device, or when to handle device events. Here is an example main function of an application using the framework:

INT WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, INT )
{
    // Set the callback functions. These functions allow the sample framework
    // to notify the application about device changes, user input, and window
    // messages. The callback functions are optional, so you need only set
    // them for events you are interested in.
    DXUTSetCallbackDeviceCreated( OnCreateDevice );
    DXUTSetCallbackDeviceReset( OnResetDevice );
    DXUTSetCallbackDeviceLost( OnLostDevice );
    DXUTSetCallbackDeviceDestroyed( OnDestroyDevice );

    DXUTSetCallbackFrameRender( OnFrameRender );
    DXUTSetCallbackFrameMove( OnFrameMove );

    // Initialize the sample framework and create the desired Win32 window and
    // Direct3D device for the application. Calling each of these functions is
    // optional, but they allow you to set several options which control the
    // behavior of the framework.
    DXUTInit( TRUE, TRUE, TRUE );
    DXUTCreateWindow( L"BasicHLSL" );
    DXUTCreateDevice( D3DADAPTER_DEFAULT, TRUE, 640, 480 );

    // Pass control to the sample framework for handling the message pump and
    // dispatching render calls. The framework will call your OnFrameMove and
    // OnFrameRender callback functions when there is idle time between
    // handling window messages.
    DXUTMainLoop();

    return DXUTGetExitCode();
}

In the example code above, the framework does most of the work. It creates a window, creates a device, handles the main loop, and uses the application-supplied callback functions when events occur, such as device reset or frame render. The framework is modular, and the application can use all of the framework features or just the parts desired.

The remainder of this programming guide covers each of these steps in detail and looks at the choices the application has available to control or replace each step.

Further details on syntax and usage of functions, callback functions, structures, enumerations, and constants can be found in Sample Framework Reference.

Features

The framework provides the following services to help you create an application:

  • Simplified window and device creation.
  • Notification of device events (created, reset, lost, destroyed) and window events (messages, keyboard, mouse).
  • Toggling between windowed and full-screen modes, and between hardware abstraction layer (HAL) and reference devices.
  • High-resolution timer.
  • Command-line support for automated testing.
  • Device selection via dialog or application programming interface (API).
  • Suite of textured graphical user interface (GUI) controls, including an Input Method Editor (IME)-enabled edit box.
  • Extra miscellaneous classes, such as simple camera types.

Limitations

For ease of use, the framework supports only a single window attached to a single device. Advanced applications that need to use multiple devices simultaneously or that need to display multiple Direct3D windows are not supported by the framework. However, most typical applications should be able to use the framework.

Starting a New Project

The easiest way to start a new Microsoft Visual Studio .NET development project using the sample framework is to do the following:

  1. Launch the sample browser, located in the Microsoft DirectX software development kit (SDK) in the following location:

    (SDK root)\Samples\SampleBrowser\

  2. In the browser, select an existing Direct3D sample project that will be a starting point.
  3. Click on the "Install Project" link next to that project to copy the Visual Studio .NET project files to a new directory location.
  4. You can also optionally rename the project, in which case the sample browser will change the appropriate files and source code to give the project the new name.

Changes from the Previous Sample Framework

The new framework is significantly redesigned from the sample framework that shipped in the DirectX 9.0 Summer 2003 SDK Update. The following is a list of major differences and improvements.

  • Flat API design. The new framework is a set of global functions that more clearly define how the application interacts with the framework.
  • Clearer naming. The device, frame, and message events have been renamed to be more easily understood.
  • Modular. An application can use only parts of the framework if desired. An application can use the framework to create its own window or its own device, or it can use its own main loop.
  • Better device selection. The application can fully customize the presentation parameters or behavior flags before creating the device. The new framework also has a more advanced algorithm for finding valid device settings.
  • Toggling between HAL and reference devices (see Device Types). Built-in toggling support is available, and toggling can be bound to a keystroke for simplified debugging.
  • Better error handling. Error handling and macros can be used by the application to display error message boxes immediately if an API is called incorrectly.
  • Better multiple-monitor support. If this feature is enabled, the new framework will automatically change devices if the window is moved to a different monitor.
  • GUI controls. A set of textured GUI controls features an IME-enabled edit box for use in samples, prototypes, and professional games.
  • No dialog dependency on Microsoft Windows Graphics Device Interface (GDI). Unlike the previous framework, the new framework does not require any GDI dialog resources in the application.
  • Late binding with DirectX. Late binding verifies that the required DirectX version is installed on the system.
  • Unicode support. The new framework supports Unicode. Microsoft Windows NT-based operating systems natively support Unicode, which means that ANSI calls need to be converted to Unicode. With this and better international support, Unicode is the better choice because it will result in better performance on these operating systems. For Windows 98 and Windows Millennium Edition (Windows Me) systems, consider using the Microsoft Layer for Unicode (MSLU) World Wide Web link.
  • Documentation. The framework library functions in the Dxut.h header are documented; see Sample Framework Reference.


Initializing the Sample Framework
Microsoft DirectX 9.0 SDK Update (October 2004)

Initializing the Sample Framework

The first step to using the sample framework is to initialize it. This can be done simply with the DXUTInit function:

HRESULT DXUTInit (
    BOOL bParseCommandLine     = TRUE,
    BOOL bHandleDefaultHotkeys = TRUE,
    BOOL bShowMsgBoxOnError    = TRUE
);

You will typically make this call to DXUTInit near the beginning of your application's WinMain World Wide Web link function. If DXUTInit is not called by the application, it will be called automatically by the framework using the default parameters.

If the first parameter, bParseCommandLine, is TRUE, the framework will respond to command-line arguments. For example, run the BasicHLSL Sample executable with the following command-line arguments:

BasicHLSL.exe -windowed -width:600 -height:600

The framework will attempt to comply with these window settings. For a complete list of supported command-line arguments, see DXUTInit.

The second parameter, bHandleDefaultHotkeys, instructs the framework to respond to some predefined keystrokes, such as ALT+ENTER. Again, for a complete list see DXUTInit. If this parameter is FALSE, the application is free to respond to these keystrokes as desired.

The last parameter, bShowMsgBoxOnError, controls the display of message boxes when the framework detects an error. Set it to FALSE to run automated testing or professional applications that require complete control over the user experience.


Using Application Windows with the Sample Framework
Microsoft DirectX 9.0 SDK Update (October 2004)

Using Application Windows with the Sample Framework

Your application can handle most window management tasks by using just a few functions in the sample framework.

  • Creating a Window
  • Using Your Own Window

Creating a Window

Creating a window for a Microsoft Direct3D application involves the following steps:

  1. Defining a WindowProc World Wide Web link callback function to respond to the proper window messages.
  2. Setting up the WNDCLASS World Wide Web link structure.
  3. Using the RegisterClass World Wide Web link application programming interface (API).
  4. Using the CreateWindow World Wide Web link API.
These steps can cause bugs if not done correctly. Although they may not be very exciting for a Direct3D programmer, they are required in every application. The framework simplifies this process with the DXUTCreateWindow function:

HRESULT DXUTCreateWindow(
    const WCHAR *strWindowTitle = L"Direct3D Window",
    HINSTANCE hInstance         = NULL,
    HICON hIcon                 = NULL,
    HMENU hMenu                 = NULL,
    INT x                       = CW_USEDEFAULT,
    INT y                       = CW_USEDEFAULT
);

All parameters are optional:

  • strWindowTitle is the window title and is what appears on the task bar; it is typically the project title.
  • hInstance is the handle to the application's instance; typically, it can be left NULL for most applications.
  • hIcon is the handle to the application's icon. If NULL, the first icon that is embedded in the application's executable will be used, so typically NULL works fine.
  • hMenu is the handle to the menu and can be set if desired. Most games, however, do not use a standard menu but instead create their own custom in-game interface.
  • The last two parameters describe the position of the window. If the application is running in full-screen mode, these parameters are ignored.

In the simplest case, an application can call the DXUTCreateWindow function as follows:

DXUTCreateWindow( L"My New Game" );

Calling the function with only the first parameter, strWindowTitle, will cause the framework to create the window and handle the important window messages automatically. The handle to the window can be retrieved if needed by calling DXUTGetHWND.

If the application is to respond to window messages, then it can use DXUTSetCallbackMsgProc to set a callback function:

void DXUTSetCallbackMsgProc( LPDXUTCALLBACKMSGPROC pCallbackMsgProc );

The pCallbackMsgProc parameter is an LPDXUTCALLBACKMSGPROC callback function with the following syntax:

LRESULT CALLBACK FUNCTION MsgProc(
    HWND   hWnd,
    UINT   uMsg,
    WPARAM wParam,
    LPARAM lParam,
    BOOL   *pbNoFurtherProcessing
    )
{
    return 0;
}

In this callback function, the application does not need to respond to any messages because all of the important messages will still be handled by the framework. To prevent the framework from handling messages, the application can set *pbNoFurtherProcessing to TRUE. (See LPDXUTCALLBACKMSGPROC.) However, be cautious when using this setting, because it may prevent the framework from behaving correctly.

Using Your Own Window

If you want the application to create its own window and use it with the framework instead of letting the sample framework handle window operations, then you can create a window and use the DXUTSetWindow function:

HRESULT DXUTSetWindow(
    HWND hWndFocus,
    HWND hWndDeviceFullScreen,
    HWND hWndDeviceWindowed,
    BOOL bHandleMessages = TRUE
);

This function takes three handles to windows, but all typically will be the same unless the windowed application is in a different window than the full-screen application. The focus window handle is provided to inform Direct3D when the application is switched to background upon an ALT+TAB, mouse click, or other user input. The application usually should pass the focus window handle to the DXUTSetWindow function, regardless of how many Direct3D devices it creates.

In addition to initializing the framework with a window, the application needs to notify the framework about the window messages that the window receives in order for the framework to behave correctly. If the framework creates the window, window messages are handled automatically. Otherwise, the application can pass window messages to the framework from inside the window's WindowProc World Wide Web link callback function by using the DXUTStaticWndProc function, which is defined as follows:

LRESULT CALLBACK DXUTStaticWndProc(
    HWND hWnd,
    UINT uMsg,
    WPARAM wParam,
    LPARAM lParam
);

Although it is not recommended, you can alternately duplicate the functionality found in the function if you do not want the application to use DXUTStaticWndProc.


Using Devices with the Sample Framework
Microsoft DirectX 9.0 SDK Update (October 2004)

Using Devices with the Sample Framework

Microsoft DirectX device creation is streamlined with the sample framework. You can instead have your application create a device directly and other features of the framework will still be available.

  • Creating a Device
  • Choosing the Best Device Settings
  • Modifying Available Device Settings
  • Using Your Own Device
  • Related Topics

Creating a Device

You would typically create a device with the standard Microsoft Direct3D method, IDirect3D9::CreateDevice:

HRESULT CreateDevice(
    UINT                  Adapter,
    D3DDEVTYPE            DeviceType,
    HWND                  hFocusWindow,
    DWORD                 BehaviorFlags,
    D3DPRESENT_PARAMETERS *pPresentationParameters,
    IDirect3DDevice9      **ppReturnedDeviceInterface
);

This method requires a valid adapter, device type (hardware abstraction layer (HAL) or reference), window handle, behavior flags (software/hardware vertex processing and other driver flags), and presentation parameters. Furthermore, the D3DPRESENT_PARAMETERS structure has numerous members that specify back buffer settings, multisampling settings, swap effects, windowed mode, depth-stencil buffer settings, refresh rate, presentation interval, and presentation flags.

Selecting valid settings for all of these parameters can be challenging. The framework simplifies this selection process with the DXUTCreateDevice function:

HRESULT DXUTCreateDevice(
    UINT AdapterOrdinal  = D3DADAPTER_DEFAULT,
    BOOL bWindowed       = TRUE,
    INT nSuggestedWidth  = 640,
    INT nSuggestedHeight = 480,
    LPDXUTCALLBACKISDEVICEACCEPTABLE pCallbackIsDeviceAcceptable     = NULL,
    LPDXUTCALLBACKMODIFYDEVICESETTINGS pCallbackModifyDeviceSettings = NULL
);

The most basic usage is simply to call the function using the default parameters:

DXUTCreateDevice();

With this simple call, the framework creates a device with default settings that should work for most cases. The default device creation settings are as follows:

DXUTMatchOptions Member | Direct3D Creation Flag | Description | Default Value from DXUTCreateDevice
eAdapterOrdinal | Adapter parameter of IDirect3D9::CreateDevice | Display adapter ordinal. | D3DADAPTER_DEFAULT
eDeviceType | DeviceType parameter of IDirect3D9::CreateDevice | Enumerated type of the device. | D3DDEVTYPE_HAL if available, otherwise D3DDEVTYPE_REF or failure code if neither is available.
eWindowed | D3DPRESENT_PARAMETERS. Windowed | Windowed or full-screen mode. | TRUE, indicating windowed mode.
eAdapterFormat | AdapterFormat parameter of IDirect3D9::CheckDeviceFormat | Adapter surface format. | Desktop display mode, or D3DFMT_X8R8G8B8 if the desktop display mode is less than 32 bits.
eVertexProcessing | BehaviorFlags parameter of IDirect3D9::CreateDevice | Vertex processing flags. | D3DCREATE_HARDWARE_VERTEXPROCESSING if supported, otherwise D3DCREATE_SOFTWARE_VERTEXPROCESSING.
eResolution | D3DPRESENT_PARAMETERS. BackBufferWidth and .BackBufferHeight | Display mode resolution. | 640 x 480 pixels for windowed mode, or the desktop resolution for full-screen mode.
eBackBufferFormat | D3DPRESENT_PARAMETERS. BackBufferFormat | Back buffer format. | Desktop display mode, or D3DFMT_X8R8G8B8 if the desktop display mode is less than 32 bits.
eBackBufferCount | D3DPRESENT_PARAMETERS. BackBufferCount | Number of back buffers. | 2, indicating triple buffering.
eMultiSample | D3DPRESENT_PARAMETERS. MultiSampleQuality | Quality level. | MultiSampleQuality = 0, indicating multisampling is disabled.
eSwapEffect | D3DPRESENT_PARAMETERS. SwapEffect | Swap effect. | D3DSWAPEFFECT_DISCARD
eDepthFormat | D3DPRESENT_PARAMETERS. AutoDepthStencilFormat | Depth format of the automatic depth-stencil surface that the device will create. | D3DFMT_D16 if the backbuffer format is 16 bits or less, or D3DFMT_D32 otherwise.
eStencilFormat | D3DPRESENT_PARAMETERS. AutoDepthStencilFormat | Stencil format of the automatic depth-stencil surface that the device will create. | D3DFMT_D16 if the backbuffer format is 16 bits or less, or D3DFMT_D32 otherwise.
ePresentFlags | D3DPRESENT_PARAMETERS. Flags | Presentation parameters flags. | D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL
eRefreshRate | D3DPRESENT_PARAMETERS. FullScreen_RefreshRateInHz | Rate at which the display adapter refreshes the screen. | 0, indicating windowed mode.
ePresentInterval | D3DPRESENT_PARAMETERS. PresentationInterval | Presentation interval. | D3DPRESENT_INTERVAL_IMMEDIATE for windowed mode, or D3DPRESENT_INTERVAL_DEFAULT for full-screen mode.
- | hFocusWindow parameter of IDirect3D9::CreateDevice | Handle to the created window (see Using Application Windows with the Sample Framework). | hWndFocus parameter of DXUTSetWindow
- | D3DPRESENT_PARAMETERS. hDeviceWindow | Handle to the device window. | hWndDeviceFullScreen or hWndDeviceWindowed parameters of DXUTSetWindow
- | D3DPRESENT_PARAMETERS. EnableAutoDepthStencil | Depth-stencil buffer creation flag. | TRUE.

Rather than just using a device created with these defaults, the application can apply more control of device creation through the parameters passed to IDirect3D9::CreateDevice. For example, you can change the window size through the nSuggestedWidth and nSuggestedHeight parameters:

DXUTCreateDevice(
    D3DADAPTER_DEFAULT,
    FALSE,
    1024,
    786,
    NULL,
    NULL
);

For even more control, the application can use the two optional callback functions, LPDXUTCALLBACKISDEVICEACCEPTABLE and LPDXUTCALLBACKMODIFYDEVICESETTINGS.

Choosing the Best Device Settings

You can use the IsDeviceAcceptable callback function in your application to help the framework choose the best device settings for the application, as in the following code:

BOOL CALLBACK IsDeviceAcceptable(
D3DCAPS9      *pCaps,
D3DFORMAT     AdapterFormat,
D3DFORMAT     BackBufferFormat,
BOOL          bWindowed )
{
    // TODO: return TRUE for acceptable settings and FALSE otherwise.
    return TRUE;
}

This callback function is modeled on the prototype LPDXUTCALLBACKISDEVICEACCEPTABLE. The framework calls this function once for each unique valid combination of the following five settings:

D3DDEVTYPE DeviceType;
UINT       AdapterOrdinal;
D3DFORMAT  AdapterFormat;
D3DFORMAT  BackBufferFormat;
BOOL       Windowed;

Note that the adapter ordinal and device type are not passed directly into the callback function, but are, respectively, the DeviceType and AdapterOrdinal members of the D3DCAPS9 structure.

Within this callback function the application can reject any combination that it does not support or want. As an example, the application can use the following code to reject 16-bit back buffer formats and all devices that do not support at least pixel shader ps_2_0:

BOOL CALLBACK IsDeviceAcceptable(
D3DCAPS9      *pCaps,
D3DFORMAT     AdapterFormat,
D3DFORMAT     BackBufferFormat,
BOOL          bWindowed )
{
    if( pCaps->PixelShaderVersion < D3DPS_VERSION(2,0) )
    return FALSE;
    if( BackBufferFormat == D3DFMT_X1R5G5B5
        || BackBufferFormat == D3DFMT_R5G6B5 )
    return FALSE;
    return TRUE;
}

After the callback function is called for every unique combination of settings, the framework ranks the remaining acceptable combinations and chooses the best among them. Higher rankings are given to combinations that include the following:

  • D3DDEVTYPE_HAL, in order to get hardware acceleration.
  • If the application is displaying in full-screen mode, the framework prefers an adapter format that matches the desktop format, so that mode changes from windowed to full-screen are rapid. The exception is if the desktop display mode is less than 32 bits, in which case the framework prefers D3DFMT_X8R8G8B8.
  • A back buffer format that matches the adapter format.

With the highest-ranked combination of these settings chosen, the behavior flags and presentation parameters are still needed to create the device. For these settings, Direct3D uses the defaults as shown in the table above.

Modifying Available Device Settings

The application can modify the choices available to the framework by using an optional second callback function ModifyDeviceSettings similar to the following:

void CALLBACK ModifyDeviceSettings(
    DXUTDeviceSettings *pDeviceSettings,
    const D3DCAPS9     *pCaps )
{
    // TODO: Include device creation requirements here
}

This callback function is modeled on the prototype LPDXUTCALLBACKMODIFYDEVICESETTINGS. The DXUTDeviceSettings structure is defined by the framework as follows:

struct DXUTDeviceSettings
{
    UINT       AdapterOrdinal;
    D3DDEVTYPE DeviceType;
    D3DFORMAT  AdapterFormat;
    DWORD      BehaviorFlags;
    D3DPRESENT_PARAMETERS pp;
};

This structure contains everything needed to create a device except the window handle, which is assumed to be the handle to the window created earlier. The framework fills this structure with valid values, and then allows the application to change device creation choices through the ModifyDeviceSettings callback function.

In this callback function the application can change the behavior flags as well as the presentation parameters in the DXUTDeviceSettings structure, as well as anything else in the structure. If the application does not change anything in the callback function, the device will be created successfully. However, any device creation setting changed by the application needs to be supported by the device, otherwise device creation will likely fail.

For example, if the application needs a depth-stencil format of D3DFMT_D24S8, it should verify that the device supports it, as in the following code:

void CALLBACK ModifyDeviceSettings(
    DXUTDeviceSettings *pDeviceSettings,
    const D3DCAPS9     *pCaps )
{
    IDirect3D9* pD3D = DXUTGetD3DObject();
    if( SUCCEEDED( pD3D->CheckDeviceFormat(
    pDeviceSettings->AdapterOrdinal,
    pDeviceSettings->DeviceType,
    pDeviceSettings->AdapterFormat,
    D3DUSAGE_DEPTHSTENCIL,
    D3DRTYPE_SURFACE,
    D3DFMT_D24S8 ) ) )
    {
    if( SUCCEEDED( pD3D->CheckDepthStencilMatch(
    pDeviceSettings->AdapterOrdinal,
    pDeviceSettings->DeviceType,
    pDeviceSettings->AdapterFormat,
    pDeviceSettings->pp.BackBufferFormat,
    D3DFMT_D24S8 ) ) )
    {
        pDeviceSettings->pp.AutoDepthStencilFormat = D3DFMT_D24S8;
    }
    }
}

Alternately, the callback function could use the framework's CD3DEnumeration object to verify whether D3DFMT_D24S8 is supported:

void CALLBACK ModifyDeviceSettings(
    DXUTDeviceSettings *pDeviceSettings,
    const D3DCAPS9     *pCaps )
{
    CD3DEnumeration *pEnum = DXUTGetEnumeration();
    CD3DEnumDeviceSettingsCombo *pCombo;

    pCombo = pEnum->GetDeviceSettingsCombo( pDeviceSettings );

    if( pCombo->depthStencilFormatList.Contains( D3DFMT_D24S8 ) )
    pDeviceSettings->pp.AutoDepthStencilFormat = D3DFMT_D24S8;
}

After the application modifies the device settings, the framework creates the device with those new settings.

Using Your Own Device

You do not have to rely on the framework to create the Direct3D device. Instead, the application itself can create the device and pass it to the framework to use, similar to the way the application can override the framework's window creation settings. Simply create a device with all desired settings, and then call the DXUTSetDevice function to enable the framework to render on the device.

Note If the application creates the device independent of the framework, the application must also release the device interface upon cleanup after main loop execution is complete.

Related Topics

  • Advanced Device Selection with the Sample Framework


Using the Main Loop with the Sample Framework
Microsoft DirectX 9.0 SDK Update (October 2004)

Using the Main Loop with the Sample Framework

After the window and device are created, the application needs to use a main loop (also called a render loop or message loop) that responds to window messages, updates and renders the scene, and handles device events. The application can either implement the main loop itself, or it can use the sample framework's implementation. Registration of callback functions allows the framework to handle device, frame, and message events.

  • Entering the Main Loop
  • Handling Events

Entering the Main Loop

To use the framework's main loop, simply call DXUTMainLoop with the single parameter set to NULL.

Although it is easiest for the framework to handle the main loop, for some advanced applications a custom main loop may be a better design. It is possible to use the DXUTMainLoop function with a custom main loop, but more code is required in the application, as shown in the following code example:

INT WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR, INT )
{
    DXUTSetCallbackDeviceCreated( OnCreateDevice );
    DXUTSetCallbackDeviceReset( OnResetDevice );
    DXUTSetCallbackDeviceLost( OnLostDevice );
    DXUTSetCallbackDeviceDestroyed( OnDestroyDevice );
    DXUTSetCallbackFrameRender( OnFrameRender );
    DXUTSetCallbackFrameMove( OnFrameMove );

    DXUTInit( TRUE, TRUE, TRUE );
    DXUTCreateWindow( L"BasicHLSL" );
    DXUTCreateDevice( D3DADAPTER_DEFAULT, TRUE, 640, 480 );

    // Custom main loop
    HWND hWnd = DXUTGetHWND();
    BOOL bGotMsg;
    MSG  msg;
    msg.message = WM_NULL;
    PeekMessage( &msg, NULL, 0U, 0U, PM_NOREMOVE );

    while( WM_QUIT != msg.message  )
    {
    // Use PeekMessage() so we can use idle time to render the scene
    bGotMsg = ( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) != 0 );

    if( bGotMsg )
    {
        // Translate and dispatch the message
        if( 0 == TranslateAccelerator( hWnd, NULL, &msg ) )
        {
        TranslateMessage( &msg );
        DispatchMessage( &msg );
        }
    }
    else
    {
        // Render a frame during idle time (no messages are waiting)
        DXUTRender3DEnvironment();
    }
    }

    return DXUTGetExitCode();
}

In this code example, the application calls the function DXUTRender3DEnvironment to have the framework update and render the scene and handle device events. While it is possible for the application to completely replicate this functionality, it is not recommended.

Handling Events

The framework uses a callback function mechanism to allow the application to respond to events. The application simply needs to register, or set, a function pointer with the framework, and the framework will call this function when the event occurs. The framework does not require that any callback function is registered, so the application is free to register only as many callback functions as needed.

Three types of events occur in the framework:

  • Device Events
  • Frame Events
  • Message Events

Device Events

While an application is rendering to a Microsoft Direct3D device, it is possible for the device to become lost. This can happen for a number of reasons, such as when a user presses ALT+TAB to leave a full-screen application, when a user presses CTRL+ALT+DEL, or when the user runs another full-screen 3-D application. The Direct3D application programming interface (API) notifies the application when this happens by returning D3DERR_DEVICELOST when calling certain functions such as IDirect3DDevice9::Present. (See Lost Devices.)

When a device becomes lost, it is the application's responsibility to release all Direct3D objects that do not survive when the device was lost, such as objects created in D3DPOOL_DEFAULT memory. If such objects are not released, the device cannot be reset when it returns from its lost state.

The application must wait while the device is lost. When the device returns, the application must call IDirect3DDevice9::Reset and recreate all device objects that did not survive the reset procedure.

With the framework, this process is simplified by using callback functions in the application to handle the various device events: device created, reset, lost, or destroyed. The framework will note when the device becomes lost and will properly reset the device when it returns from the lost state. The framework uses the application's callback functions to release and recreate the device objects at the appropriate times. All the application needs to do is to register and implement callback functions as follows.

Callback Registration Function | Application Callback Function | When Called By the Framework | Resource Creation | Resource Release
DXUTSetCallbackDeviceCreated | LPDXUTCALLBACKDEVICECREATED | Called immediately after the Direct3D device has been created, which will happen during application initialization and device recreation. | Create D3DPOOL_MANAGED resources because these resources need to be reloaded whenever the device is destroyed. | Resources created in this callback function should be released by calling the device destroyed callback function (LPDXUTCALLBACKDEVICEDESTROYED).
DXUTSetCallbackDeviceReset | LPDXUTCALLBACKDEVICERESET | Called immediately after the Direct3D device has been reset, which will happen after the device is lost. | Create D3DPOOL_DEFAULT resources because these resources need to be reloaded whenever the device is lost. | Resources created in this callback function should be released by calling the device lost callback function (LPDXUTCALLBACKDEVICELOST).
DXUTSetCallbackDeviceLost | LPDXUTCALLBACKDEVICELOST | Called immediately after the Direct3D device has entered a lost state and before IDirect3DDevice9::Reset is called. | - | Resources created in the device reset callback function (LPDXUTCALLBACKDEVICERESET), which generally includes all D3DPOOL_DEFAULT resources, should be released by this application callback function.
DXUTSetCallbackDeviceDestroyed | LPDXUTCALLBACKDEVICEDESTROYED | Called immediately after the Direct3D device has been destroyed, which generally happens as a result of application termination or device recreation. | - | Resources created in the device created callback function (LPDXUTCALLBACKDEVICECREATED), which generally includes all D3DPOOL_MANAGED resources, should be released by this application callback function.

When the device is toggled between windowed and full-screen modes, it is usually reset, but sometimes it will have to be recreated by Direct3D.

It is optional to call any of these callback registration functions. However, if the application does not register the device destroyed and device created callback functions by calling DXUTSetCallbackDeviceDestroyed and DXUTSetCallbackDeviceCreated, then the framework cannot recreate the device because it will have no way of notifying the application that the device is being destroyed or created. In this case, changing devices or toggling between hardware abstraction layer (HAL) or reference devices will not work.

Similarly, if the application does not register the device lost and device reset callback functions by calling DXUTSetCallbackDeviceLost and DXUTSetCallbackDeviceReset, then the framework has no way of notifying the application when the device is lost or reset. In this case, typically if all the device objects are not in D3DPOOL_MANAGED memory, then Direct3D will fail to reset the device.

Frame Events

The framework also provides frame events that are called every frame during the rendering process. The application should register and implement callback functions as follows.

Application Callback Function | Callback Registration Function | When Called By the Framework | Scene Rendering
LPDXUTCALLBACKFRAMEMOVE | DXUTSetCallbackFrameMove | Called once at the beginning of every frame. | This callback function is the best location for your application to handle updates to the scene, but it should not contain actual rendering calls, which should instead be placed in the frame render callback function (LPDXUTCALLBACKFRAMERENDER).
LPDXUTCALLBACKFRAMERENDER | DXUTSetCallbackFrameRender | Called at the end of every frame, or if the window needs to be repainted. | All the rendering calls for the scene should be performed in this callback function. After this callback function has returned, the framework will call IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain.

Message Events

The framework passes window messages, keyboard events, and mouse events through the following callback functions and their corresponding registration functions. Program the application to provide appropriate responses to such events.

Application Callback Function | Callback Registration Function | Description
LPDXUTCALLBACKMSGPROC | DXUTSetCallbackMsgProc | Processes window messages from the framework message pump.
LPDXUTCALLBACKKEYBOARD | DXUTSetCallbackKeyboard | Processes keyboard events from the framework message pump.
LPDXUTCALLBACKMOUSE | DXUTSetCallbackMouse | Processes mouse events from the framework message pump.


Error Handling with the Sample Framework
Microsoft DirectX 9.0 SDK Update (October 2004)

Error Handling with the Sample Framework

This topic covers recommended procedures for handling errors returned from applications that use the sample framework.

  • Efficient Error Handling
  • Error Messages

Efficient Error Handling

The Microsoft Direct3D application programming interface (API) is designed to make it easy to handle failures. Even though most elements of the Direct3D API return HRESULTs, the API is designed such that only a few methods and functions return device errors such as D3DERR_DEVICELOST or D3DERR_DRIVERINTERNALERROR. However, a typical Direct3D application will use many various API methods and functions which, when passed bad parameters, will return D3DERR_INVALIDCALL.

When a Direct3D application is being developed, it should check all API calls for failures, and if a failure occurs that was not expected, the application should be designed to immediately notify the developer or log the error. In this way the developer can quickly catch situations where API functions are called incorrectly. However, a mature application that is correctly calling the API functions can safely ignore error codes from failed calls to most Direct3D APIs, with the exception of errors returned by a few key API functions such as IDirect3DDevice9::Present or IDirect3DDevice9::TestCooperativeLevel.

By handling only the most important Direct3D errors, you can improve execution speed and make the application code more predictable and robust because there are only a few places in code that need to handle errors. Failures in the other few API functions that must be handled properly, such as IDirect3DDevice9::Present, are handled inside the framework.

Error Messages

Error handling in the framework matches how error handling in the Direct3D API was designed. For serious errors such as missing media, the application can notify the user and terminate. For most API functions that are called every frame, the errors are only handled during debug builds by displaying an error message box to the developer. For retail builds these errors are ignored. The framework accomplishes this with several macros defined in Dxstdafx.h:

#if defined(DEBUG) | defined(_DEBUG)
    #define V(x)
    {
        hr = x;
        if( FAILED(hr) )
        {
            DXUTTrace( __FILE__, (DWORD)__LINE__, hr, L#x, TRUE );
        }
    }
    #define V_RETURN(x)
    {
        hr = x;
        if( FAILED(hr) )
        {
            return DXUTTrace( __FILE__, (DWORD)__LINE__, hr, L#x, TRUE );
        }
    }
#else
    #define V(x)
    {
        hr = x;
    {
    #define V_RETURN(x)
    {
        hr = x;
        if( FAILED(hr) )
        {
            return hr;
        }
    }
#endif

A typical application can use the V() macro as follows:

V( g_pEffect->BeginPass( iPass ) );
V( g_pEffect->CommitChanges() );
V( g_pMesh->DrawSubset( 0 ) );

Each of these calls uses the V() macro that ignores the API return code for release builds. For debug builds, the macro will display an error message that looks something like the following:

Error message returned by V() macro for debug build

The debug output window of the compiler will display a message such as the following:

c:\basichlsl\basichlsl.cpp(242):
    D3DXCreateFont( pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
    OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Arial",
    NULL ) hr=D3DERR_INVALIDCALL (0x8876086c)

To jump to the line of source code where the error occurred when using Microsoft Visual Studio .NET, simply double-click on this line in the debug output window.

An application can use the V_RETURN() macro as follows:

V_RETURN( D3DXCreateEffectFromFile(
    pd3dDevice,
    str,
    NULL,
    NULL,
    dwShaderFlags,
    NULL,
    &g_pEffect,
    NULL ) );

This macro will display a similar error message in debug builds, but for both debug and release builds it will also return any failed HRESULT to the calling function. The display of these error messages can be turned off with a call to DXUTInit or with the following command-line argument:

-noerrormsgboxes

See Tutorials and Samples for more examples of how these macros are used.


Advanced Device Selection with the Sample Framework
Microsoft DirectX 9.0 SDK Update (October 2004)

Advanced Device Selection with the Sample Framework

This topic covers advanced scenarios for controlling Microsoft Direct3D device creation using the sample framework.

  • Selecting the Best Available Device
  • Controlling the Device Selection Dialog

Selecting the Best Available Device

The sample framework uses a highly flexible method for selecting the best device from the enumerated set. This device enumeration and ranking system can be used independently from the rest of the framework by calling the DXUTFindValidDeviceSettings function:

HRESULT DXUTFindValidDeviceSettings(
    DXUTDeviceSettings *pOut,
    DXUTDeviceSettings *pIn,
    DXUTMatchOptions   *pMatchOptions )

The pIn parameter accepts a pointer to an existing DXUTDeviceSettings structure. The pMatchOptions parameter is used to specify which of the input device settings must be preserved, which settings should be matched to the closest valid settings, and which settings can be ignored when selecting the best device.

For example, suppose the calling function wants a hardware abstraction layer (HAL) device with a back buffer format of D3DFMT_A2B10G10R10. If the HAL device on the system does not support this back buffer format, but a reference device is installed that does, then the function has a choice to either use the reference device or to change to a back buffer format compatible with the HAL device. The match options in the DXUT_MATCH_TYPE enumeration let the caller control how these choices are made.

Each match option must be one of the following types:

DXUT_MATCH_TYPE Value | Description
DXUTMT_IGNORE_INPUT | Use the closest valid value to a default device setting.
DXUTMT_PRESERVE_INPUT | Use the input parameters without change; however, it is possible that no valid device will be found.
DXUTMT_CLOSEST_TO_INPUT | Use the closest valid value to the input.

If pMatchOptions is NULL, then all of the match options are assumed to be DXUTMT_IGNORE_INPUT. DXUTFindValidDeviceSettings returns a failure code if no valid device settings can be found; otherwise, the function returns a success code and the valid device settings are written to pOut.

See also Choosing the Best Device Settings.

Controlling the Device Selection Dialog

You may wish to control exactly what choices appear in the list of options in the sample framework's device selection dialog. For example, it is possible to notify the device selection dialog that an application requires a stencil buffer.

To control the list of options that appear in the framework's device selection dialog, you can use the LPDXUTCALLBACKISDEVICEACCEPTABLE callback function. This will allow you to control which combinations of device settings are allowed (adapter ordinal, device type, adapter format, back buffer format, and windowed). To control the other settings in the device selection dialog, you can use CD3DEnumeration member functions, which are defined in DXUTenum.cpp and declared in the following header file:

(SDK root)\Samples\C++\Common\DXUTenum.h

For example, to control which depth stencil formats are allowed in the dialog, you can use the following code:

CGrowableArray<D3DFORMAT>* pDSList;
pDSList = DXUTGetEnumeration()->GetPossibleDepthStencilFormatList();

nIndex = pDSList->IndexOf( D3DFMT_D16 );
if( nIndex >= 0 ) pDSList->Remove( nIndex );

nIndex = pDSList->IndexOf( D3DFMT_D24X8 );
if( nIndex >= 0 ) pDSList->Remove( nIndex );

nIndex = pDSList->IndexOf( D3DFMT_D24S8 );
if( nIndex >= 0 ) pDSList->Remove( nIndex );

Calls to CD3DEnumeration functions, such as in this example code, must be made before the device is created.


Additional Sample Framework Functions
Microsoft DirectX 9.0 SDK Update (October 2004)

Additional Sample Framework Functions

Following is a selection of functions that allow you to change the behavior of the sample framework and to retrieve internal variables. For all available framework functions, see Sample Framework Functions.

Function | Description
Window Management
DXUTGetHWND | Gets a handle to the current device window.
DXUTGetHWNDFocus | Gets the handle of the focus window.
DXUTGetHWNDDeviceFullScreen | Gets the handle of the full-screen mode device window.
DXUTGetHWNDDeviceWindowed | Gets the handle of the windowed mode device window.
DXUTGetWindowClientRect | Gets the client rectangle of the application device window.
DXUTGetWindowTitle | Gets a pointer to the application window title.
DXUTIsWindowed | Indicates whether the application is in windowed mode.
Device Management
DXUTSetCursorSettings | Sets options for cursor usage in full-screen mode.
DXUTSetMultimonSettings | Sets options for how the framework functions on multiple monitors.
DXUTToggleFullscreen | Switches the application between windowed and full-screen modes.
DXUTToggleREF | Switches the application between hardware abstraction layer (HAL) and reference devices.
Sample Framework Management
DXUTResetFrameworkState | Resets the framework state to its initial default state. All previous framework state changes are lost.
DXUTShutdown | Triggers program termination and framework cleanup.
DXUTGetExitCode | Gets the framework exit code.
Microsoft Direct3D Variable Retrieval
DXUTGetD3DObject | Gets a pointer to the IDirect3D9 object.
DXUTGetD3DDevice | Gets a pointer to the IDirect3DDevice9 interface that represents the current device.
DXUTGetDeviceSettings | Gets the DXUTDeviceSettings structure used to create the current device.
DXUTGetPresentParameters | Gets the presentation parameters of the current device.
DXUTGetBackBufferSurfaceDesc | Gets a pointer to a D3DSURFACE_DESC surface description of the back buffer on the current adapter.
DXUTGetDeviceCaps | Gets a pointer to the D3DCAPS9 capabilities of the current device.
Statistics
DXUTGetFPS | Gets the current number of frames being presented per second.
DXUTGetFrameStats | Gets a pointer to a string containing the current number of frames per second, resolution, back buffer format, and depth stencil format.
DXUTGetDeviceStats | Gets a pointer to a string containing the current device type, vertex processing behavior, and device name.
Time
DXUTGetTime | Gets the current time, in seconds.
DXUTGetElapsedTime | Gets the time elapsed since the last frame.
DXUTSetConstantFrameTime | Enables or disables a constant frame time.
Timer
DXUTSetTimer | Installs a new timer.
DXUTKillTimer | Uninstalls an existing timer.
Pause
DXUTPause | Sets the paused state of the framework internal timer and/or rendering process.
DXUTIsRenderingPaused | Indicates whether rendering has been paused on the current device.
DXUTIsTimePaused | Indicates whether time has been paused on the current device.
User Input
DXUTIsKeyDown | Indicates whether a specified keyboard key is up or down at the time the function is called.
DXUTIsMouseButtonDown | Indicates whether a specified mouse button is up or down at the time the function is called.
Device Settings Dialog
DXUTGetShowSettingsDialog | Indicates whether the sample framework's device settings dialog box is currently showing.
DXUTSetShowSettingsDialog | Shows or hides the sample framework's device settings dialog box.


HLSL Shaders
Microsoft DirectX 9.0 SDK Update (October 2004)

HLSL Shaders

At a very high level, data enters the graphics pipeline as per-vertex data, is processed by each of the three stages, and generates pixel colors. Briefly, each stage of the pipeline performs a series of steps:

  • Vertex processing. This includes vertex transforms, per-vertex fog, per-vertex material attributes, and per-vertex lighting.
  • Primitive processing. This is comprised of clipping, back-face culling, and per-primitive attribute evaluation in preparation for rasterizing.
  • Pixel processing. This is broken into two parts:

    Part 1 blends texture samples with per-pixel colors, completely replacing the fixed function multi-texture blender. This processing includes: iterating colors and texture coordinates, sampling textures, and blending texture samples with lighting and material colors.

    Part 2 includes all the operations that determine what is written out to the frame buffer. This includes: alpha testing, depth testing, stencil testing, calculating per-pixel fog, alpha blending, dithering, and making gamma adjustments.

By making vertex processing and the first part of pixel processing programmable, the user can now dramatically extend the functionality of the pipeline by implementing custom functionality in each of these stages.

  • Vertex Shader Basics
  • Pixel Shader Basics
  • HLSL Language Basics
  • Writing HLSL Shaders
  • Using HLSL Shaders
  • HLSL Tutorials
  • Getting Started Debugging Shaders
  • Shader Model 3

Programmable high-level shader language (HLSL) shaders use the HLSL compiler to generate asm shader code from HLSL source code. Note that the HLSL compiler is part of the D3DX library that is statically linked to your application, the compiler is not part of the Microsoft DirectX runtime.

A Simple HLSL Shader

To program this enormous variability, a shader language called HLSL was created to design these programmable shaders. Simply design and build shaders in HLSL and compile each shader into an Asm shader.

Here is an example of a vertex shader that implements the minimum vertex processing. This shader transforms vertex position from object space to projection space and assigns per-vertex color from the vertex input.

float4x4 mWorldViewProj;  // World * View * Projection transformation

struct VS_OUTPUT
{
    float4 Position   : POSITION;  // vertex position
    float4 Diffuse    : COLOR0;    // vertex diffuse color
};

VS_OUTPUT Vertex_Shader_Transform(
    in float4 vPosition : POSITION,
    in float4 vColor : COLOR0
 )
{
    VS_OUTPUT Output;

    // Transform the vertex into projection space.
    Output.Position = mul( vPosition, mWorldViewProj );

    // Output the diffuse color.
    Output.Diffuse = vColor;

    return Output;
}

Here is an example of a simple pixel shader. This shader simply copies the interpolated per-vertex color data, and outputs a pixel color.

float4 Pixel_Shader( VS_OUTPUT in ) : COLOR0
{
    float4 color = in.Color;

    return color;
}

These shaders looks very much like C code and contain one global variable, one data structure, and two functions. By browsing these shaders you can see that:

  • The shaders are readable.
  • The shaders use standard HLSL math functions like mul, which does a matrix multiply.
  • In addition to standard C syntax, HLSL introduces a few new data types like float4 and float4x4 that make it easier to map the shader to hardware shaders.
  • HLSL defines semantics like POSITION and COLOR0 for inputs that are streamed into the shader from a vertex buffer.


Vertex Shader Basics
Microsoft DirectX 9.0 SDK Update (October 2004)

Vertex Shader Basics

When in operation, a programmable vertex shader replaces the vertex processing done by the Microsoft Direct3D graphics pipeline. While using a vertex shader, state information regarding transformation and lighting operations is ignored by the fixed function pipeline. When the vertex shader is disabled and fixed function processing is returned, all current state settings apply.

Tessellation of high-order primitives should be done before the vertex shader executes. Implementations that perform surface tessellation after the shader processing must do so in a way that is not apparent to the application and shader code.

As a minimum, a vertex shader must output vertex position in homogeneous clip space. Optionally, the vertex shader can output texture coordinates, vertex color, vertex lighting, fog factors, and so on.


Pixel Shader Basics
Microsoft DirectX 9.0 SDK Update (October 2004)

Pixel Shader Basics

Pixel processing is performed by pixel shaders on individual pixels. Pixel shaders work in concert with vertex shaders; the output of a vertex shader provides the inputs for a pixel shader. Other pixel operations (fog blending, stencil operations, and render-target blending) occur after execution of the shader.

Texture Stage and Sampler States

A pixel shader completely replaces the pixel-blending functionality specified by the multi-texture blender including operations previously defined by the texture stage states. Texture sampling and filtering operations which were controlled by the standard texture stage states for minification, magnification, mip filtering, and the wrap addressing modes, can be initialized in shaders. The application is free to change these states without requiring the regeneration of the currently bound shader. Setting state can be made even easier if your shaders are designed within an effect.

Pixel Shader Inputs

For pixel shader versions ps_1_1 - ps_2_0, diffuse and specular colors are saturated (clamped) to the range 0 through 1 before use by the shader because this is the range of valid inputs to the shader.

Color values input to the pixel shader are assumed to be perspective correct, but this is not guaranteed in all hardware. Colors generated from texture coordinates by the address shader are always iterated in a perspective correct manner. However, they are also clamped to the range 0 to 1 during iteration.

Pixel Shader Outputs

For pixel shader versions ps_1_1 - ps_1_4, the result emitted by the pixel shader is the contents of register r0. Whatever it contains when the shader completes processing is sent to the fog stage and render-target blender.

For pixel shader versions ps_2_0 and above, output color is emitter from oC0 - oC4.


HLSL Language Basics
Microsoft DirectX 9.0 SDK Update (October 2004)

HLSL Language Basics

  • HLSL Implements Per-Component Math Operations
  • The Vector Type
  • The Matrix Type

With high-level shader language (HLSL), you can program shaders at an algorithm level. The time spent considering hardware details such as register allocation, co-issuing instructions, and register read-port limits is greatly reduced. HLSL also has the advantages of other high level languages such as code re-use, improved readability, and a compiler that will optimize the code.

To generate HLSL shaders, you must first learn the high level shading language. Once you understand the language, you will need to know how to: declare variables and functions, use intrinsic functions, define custom data types and use semantics to connect shader arguments to other shaders and to the pipeline.

Once you learn how to author shaders in HLSL, you will need to learn about API calls so that you can: compile a shader for particular hardware, initialize shader constants, and initialize other pipeline state if necessary. These topics are covered in Writing HLSL Shaders. Beyond this, you can reuse your shader code by learning how to:

  • Write shader fragments. These independent shader functions can be compiled at design time and linked at runtime.
  • Use effects to manage state. Effects encapsulate pipeline state (including shader state) which makes managing pipeline state easier and more efficient.

HLSL Implements Per-Component Math Operations

HLSL uses two special types, a vector type and a matrix type to make programming 2-D and 3-D graphics easier. Each of these types contain more than one component; a vector contains up to four components, and a matrix contains up to 16 components. When vectors and matrices are used in standard HLSL equations, the math performed is designed to work per-component. For instance, HLSL implements this multiply:

float4 v = a*b;

as a four-component multiply. The result is four scalars:

float4 v = a*b;

v.x = a.x*b.x;
v.y = a.y*b.y;
v.z = a.z*b.z;
v.w = a.w*a.w;

This is four multiplications where each result is stored in a separate component of v. This is called a four-component multiply. HLSL uses component math which makes writing shaders in HLSL very efficient.

This is very different from a multiply which is typically implemented as a dot product which generates a single scalar:

v = a.x*b.x + a.y*b.y + a.z*b.z + a.w*b.w;

A matrix also use per-component operations in HLSL:

float3x3 mat1,mat2;
...
float3x3 mat3 = mat1*mat2;

The result is a per-component multiply of the two matrices (as opposed to a standard 3x3 matrix multiply). A per component matrix multiply yields this first term:

mat3.m00 = mat1.m00 * mat2._m00;

This is different from a 3x3 matrix multiply which would yield this first term:

// First component of a four-component matrix multiply
mat.m00 = mat1._m00 * mat2._m00 +
          mat1._m01 * mat2._m10 +
          mat1._m02 * mat2._m20 +
          mat1._m03 * mat2._m30;

Overloaded versions of the multiply intrinsic function handle cases where one operand is a vector and the other operand is a matrix. Such as: vector * vector, vector * matrix, matrix * vector, and matrix * matrix. For instance:

float4x3 World;

float4 main(float4 pos : POSITION) : POSITION
{
    float4 val;
    val.xyz = mul(pos,World);
    val.w = 0;

    return val;
}

produces the same result as:

float4x3 World;

float4 main(float4 pos : POSITION) : POSITION
{
    float4 val;
    val.xyz = (float3) mul((float1x4)pos,World);
    val.w = 0;

    return val;
}

This example casts the "pos" vector to a column vector using the "(float1x4)" cast. Changing a vector by casting, or swapping the order of the arguments supplied to mul is equivalent to transposing the matrix.

Automatic cast conversion causes the mul and dot intrinsic functions to return the same results as used here:

{
  float4 val;
  return mul(val,val);
}

This result of the mul is a 1x4 * 4x1 = 1x1 vector. This is equivalent to a dot product:

{
  float4 val;
  return dot(val,val);
}

which returns a single scalar value.

The Vector Type

A vector is a data structure that contains between one and four components.

bool    bVector;   // scalar containing 1 Boolean
bool1   bVector;   // vector containing 1 Boolean
int1    iVector;   // vector containing 1 int
half2   hVector;   // vector containing 2 halfs
float3  fVector;   // vector containing 3 floats
double4 dVector;   // vector containing 4 doubles

The integer immediately following the data type is the number of components on the vector.

Initializers can also be included in the declarations.

bool    bVector = false;
int1    iVector = 1;
half2   hVector = { 0.2, 0.3 };
float3  fVector = { 0.2f, 0.3f, 0.4f };
double4 dVector = { 0.2, 0.3, 0.4, 0.5 };

Alternatively, the vector type can be used to make the same declarations:

vector <bool,   1> bVector = false;
vector <int,    1> iVector = 1;
vector <half,   2> hVector = { 0.2, 0.3 };
vector <float,  3> fVector = { 0.2f, 0.3f, 0.4f };
vector <double, 4> dVector = { 0.2, 0.3, 0.4, 0.5 };

The vector type uses angle brackets to specify the type and number of components.

Vectors contain up to four components, each of which can be accessed using one of two naming sets:

  • The position set: x,y,z,w
  • The color set: r,g,b,a

These statements both return the value in the third component.

// Given
float4 pos = float4(0,0,2,1);

pos.z    // value is 2
pos.b    // value is 2

Naming sets can use one or more components, but they cannot be mixed.

// Given
float4 pos = float4(0,0,2,1);
float2 temp;

temp = pos.xy  // valid
temp = pos.rg  // valid

temp = pos.xg  // NOT VALID because the position and color sets were used.

Specifying one or more vector components when reading components is called swizzling. For example:

float4 pos = float4(0,0,2,1);
float2 f_2D;
f_2D = pos.xy;   // read two components
f_2D = pos.xz;   // read components in any order
f_2D = pos.zx;

f_2D = pos.xx;   // components can be read more than once
f_2D = pos.yy;

Masking controls how many components are written.

float4 pos = float4(0,0,2,1);
float4 f_4D;
f_4D    = pos;     // write four components

f_4D.xz = pos.xz;  // write two components
f_4D.zx = pos.xz;  // change the write order

f_4D.xzyw = pos.w; // write one component to more than one component
f_4D.wzyx = pos;

Assignments cannot be written to the same component more than once. So the left side of this statement is invalid:

f_4D.xx = pos.xy;   // cannot write to the same destination components

Also, the component name spaces cannot be mixed. This is an invalid component write:

f_4D.xg = pos.rgrg;    // invalid write: cannot mix component name spaces

The Matrix Type

A matrix is a data structure that contains rows and columns of data. The data can be any of the scalar data types, however, every element of a matrix is the same data type. The number of rows and columns is specified with the "row by column" string that is appended to the data type.

int1x1    iMatrix;   // integer matrix with 1 row,  1 column
int2x1    iMatrix;   // integer matrix with 2 rows, 1 column
...
int4x1    iMatrix;   // integer matrix with 4 rows, 1 column
...
int1x4    iMatrix;   // integer matrix with 1 row, 4 columns

double1x1 dMatrix;   // double matrix with 1 row,  1 column
double2x2 dMatrix;   // double matrix with 2 rows, 2 columns
double3x3 dMatrix;   // double matrix with 3 rows, 3 columns
double4x4 dMatrix;   // double matrix with 4 rows, 4 columns

The maximum number of rows or columns is 4; the minimum number is 1.

A matrix can be initialized when it is declared:

float2x2 fMatrix = { 0.0f, 0.1, // row 1
                     2.1f, 2.2f // row 2
                   };

Or, the matrix type can be used to make the same declarations:

matrix <float, 2, 2> fMatrix = { 0.0f, 0.1, // row 1
                                 2.1f, 2.2f // row 2
                               };

The matrix type uses the angle brackets to specify the type, the number of rows, and the number of columns. This example creates a floating-point matrix, with two rows and two columns. Any of the scalar data types can be used.

This declaration defines a matrix of half values (16-bit floating-point numbers) with two rows and three columns:

matrix <half, 2, 3> fHalfMatrix;

A matrix contains values organized in rows and columns, which can be accessed using the structure operator "." followed by one of two naming sets:

  • The zero-based row-column position:
    • _m00, _m01, _m02, _m03
    • _m10, _m11, _m12, _m13
    • _m20, _m21, _m22, _m23
    • _m30, _m31, _m32, _m33
  • The one-based row-column position:
    • _11, _12, _13, _14
    • _21, _22, _23, _24
    • _31, _32, _33, _34
    • _41, _42, _43, _44

Each naming set starts with an underscore followed by the row number and the column number. The zero-based convention also includes the letter "m" before the row and column number. Here's an example that uses the two naming sets to access a matrix:

// given
float2x2 fMatrix = { 1.0f, 1.1f, // row 1
                     2.0f, 2.1f  // row 2
                   };

float f_1D;
f_1D = matrix._m00; // read the value in row 1, column 1: 1.0
f_1D = matrix._m11; // read the value in row 2, column 2: 2.1

f_1D = matrix._11;  // read the value in row 1, column 1: 1.0
f_1D = matrix._22;  // read the value in row 2, column 2: 2.1

Just like vectors, naming sets can use one or more components from either naming set.

// Given
float2x2 fMatrix = { 1.0f, 1.1f, // row 1
                     2.0f, 2.1f  // row 2
                   };
float2 temp;

temp = fMatrix._m00_m11 // valid
temp = fMatrix._m11_m00 // valid
temp = fMatrix._11_22   // valid
temp = fMatrix._22_11   // valid

A matrix can also be accessed using array access notation, which is a zero-based set of indices. Each index is inside of square brackets. A 4x4 matrix is accessed with the following indices:

  • [0][0], [0][1], [0][2], [0][3]
  • [1][0], [1][1], [1][2], [1][3]
  • [2][0], [2][1], [2][2], [2][3]
  • [3][0], [3][1], [3][2], [3][3]

Here is an example of accessing a matrix:

float2x2 fMatrix = { 1.0f, 1.1f, // row 1
                     2.0f, 2.1f  // row 2
                   };
float temp;

temp = fMatrix[0][0] // single component read
temp = fMatrix[0][1] // single component read

Notice that the structure operator "." is not used to access an array. Array access notation cannot use swizzling to read more than one component.

float2 temp;
temp = fMatrix[0][0]_[0][1] // invalid, cannot read two components

However, array accessing can read a multi-component vector.

float2 temp;
float2x2 fMatrix;
temp = fMatrix[0] // read the first row

As with vectors, reading more than one matrix component is called swizzling. More than one component can be assigned, assuming only one name space is used. These are all valid assignments:

// Given these variables
float4x4 worldMatrix = float4( {0,0,0,0}, {1,1,1,1}, {2,2,2,2}, {3,3,3,3} );
float4x4 tempMatrix;

tempMatrix._m00_m11 = worldMatrix._m00_m11; // multiple components
tempMatrix._m00_m11 = worldMatrix.m13_m23;

tempMatrix._11_22_33 = worldMatrix._11_22_33; // any order on swizzles
tempMatrix._11_22_33 = worldMatrix._24_23_22;

Masking controls how many components are written.

// Given
float4x4 worldMatrix = float4( {0,0,0,0}, {1,1,1,1}, {2,2,2,2}, {3,3,3,3} );
float4x4 tempMatrix;

tempMatrix._m00_m11 = worldMatrix._m00_m11; // write two components
tempMatrix._m23_m00 = worldMatrix.m00_m11;

Assignments cannot be written to the same component more than once. So the left side of this statement is invalid:

// cannot write to the same component more than once
tempMatrix._m00_m00 = worldMatrix.m00_m11;

Also, the component name spaces cannot be mixed. This is an invalid component write:

// Invalid use of same component on left side
tempMatrix._11_m23 = worldMatrix._11_22;

Matrix Ordering

Matrix packing order for uniform parameters is set to column-major by default. This means each column of the matrix is stored in a single constant register. On the other hand, a row-major matrix packs each row of the matrix in a single constant register. Matrix packing can be changed with the "#pragma pack_matrix" directive, or with the "row_major" or the "col_major" keywords.

In general, column-major matrices are more efficient than row-major matrices. Here is an example that compares the number of instructions used for both column-major and row-major matrices:

// column-major matrix packing
float4x3 World;

float4 main(float4 pos : POSITION) : POSITION
{
    float4 val;
    val.xyz = mul(pos,World);
    val.w = 0;

    return val;
}

If you look at the assembly code generated from the HLSL compiler, you will see these instructions:

vs_2_0
def c3, 0, 0, 0, 0
dcl_position v0
m4x3 oPos.xyz, v0, c0
mov oPos.w, c3.x
// approximately four instruction slots used

Using a column-major matrix in this example generated four assembly-language instructions.

Here is the same example using a row-major matrix:

// row-major matrix packing
#pragma pack_matrix(row_major)

float4x3 World;

float4 main(float4 pos : POSITION) : POSITION
{
    float4 val;
    val.xyz = mul(pos,World);
    val.w = 0;

    return val;
}

The assembly code generated from compiling this HLSL code is:

vs_2_0
def c4, 0, 0, 0, 0
dcl_position v0
mul r0.xyz, v0.x, c0
mad r2.xyz, v0.y, c1, r0
mad r4.xyz, v0.z, c2, r2
mad oPos.xyz, v0.w, c3, r4
mov oPos.w, c4.x

// approximately five instruction slots used

This generated five instruction slots. In this example, writing the same code with a column-major packing order saved one instruction out of five. In addition to saving instruction slots, column-major packing usually saves constant register space.

The data in a matrix is loaded into shader constant registers before a shader runs. There are two choices for how the matrix data is read: in row-major order or in column-major order. Column-major order means that each matrix column will be stored in a single constant register, and row-major order means that each row of the matrix will be stored in a single constant register. This is an important consideration for how many constant registers are used for a matrix.

A row-major matrix is laid out like this:

11 | 12 | 13 | 14
21 | 22 | 23 | 24
31 | 32 | 33 | 34
41 | 42 | 43 | 44

A column-major matrix is laid out like this:

11 | 21 | 31 | 41
12 | 22 | 32 | 42
13 | 23 | 33 | 43
14 | 24 | 34 | 44

Row-major and column-major matrix ordering determine the order the matrix components are read from the constant table or from shader inputs. Once the data is written into constant registers, matrix order has no effect on how the data is used or accessed from within shader code. Also, matrices declared in a shader body do not get packed into constant registers. Row-major and column-major packing order has no influence on the packing order of constructors (which always follows row-major ordering).

The order of the data in a matrix can be declared at compile time (see Type Modifiers, or the compiler will order the data at runtime for the most efficient use.


Writing HLSL Shaders
Microsoft DirectX 9.0 SDK Update (October 2004)

Writing HLSL Shaders

  • Declaring Shader Variables
  • Uniform Shader Inputs
  • Varying Shader Inputs and Semantics
  • Samplers and Texture Objects
  • Writing Functions
  • Flow Control
  • Writing Shader Fragments

Declaring Shader Variables

The simplest variable declaration includes a type and a variable name, such as this floating-point declaration:

float fVar;

You can initialize a variable in the same statement.

float fVar = 3.1f;

An array of variables can be declared,

int iVar[3];

or declared and initialized in the same statement.

int iVar[3] = {1,2,3};

Here are a few declarations that demonstrate many of the characteristics of high-level shader language (HLSL) variables:

float4 color;
uniform float4 position : POSITION;
const float4 lightDirection = {0,0,1};

Data declarations can use any valid type including:

  • basic types
  • vector types
  • matrix types
  • shader types
  • sampler type
  • user-defined types.

A shader can have top-level variables, arguments, and functions.

// top-level variable
float globalShaderVariable;

// top-level function
void function(
in float4 position: POSITION0 // top-level argument
              )
{
  float localShaderVariable; // local variable
  function2(...)
}

void function2()
{
  ...
}

Top-level variables are declared outside of all functions. Top-level arguments are parameters to a top-level function. A top-level function is any function called by the application (as opposed to a function that is called by another function).

Uniform Shader Inputs

Vertex and pixel shaders accept two kinds of input data: varying and uniform. The varying input is the data that is unique to each execution of the shader. For a vertex shader, the varying data (for example: position, normal, etc.) comes from the vertex streams. The uniform data (for example: material color, world transform, etc.) is constant for multiple executions of a shader. For those familiar with the assembly shader models, uniform data is specified by constant registers and varying data by the v and t registers.

Uniform data can be specified by two methods. The most common method is to declare global variables and use them within a shader. Any use of global variables within a shader will result in adding that variable to the list of uniform variables required by that shader. The second method is to mark an input parameter of the top-level shader function as uniform. This marking specifies that the given variable should be added to the list of uniform variables.

Uniform variables used by a shader are communicated back to the application via the constant table. The constant table is the name for the symbol table that defines how the uniform variables used by a shader fit into the constant registers. The uniform function parameters appear in the constant table prepended with a dollar sign ($), unlike the global variables. The dollar sign is required to avoid name collisions between local uniform inputs and global variables of the same name.

The constant table contains the constant register locations of all uniform variables used by the shader. The table also includes the type information and the default value, if specified.

Varying Shader Inputs and Semantics

Varying input parameters (of a top-level shader function) must be marked either with a semantic or uniform keyword indicating the value is constant for the execution of the shader. If a top-level shader input is not marked with a semantic or uniform keyword, then the shader will fail to compile.

The input semantic is a name used to link the given input to an output of the previous part of the graphics pipeline. For example, the input semantic POSITION0 is used by the vertex shaders to specify where the position data from the vertex buffer should be linked.

Pixel and vertex shaders have different sets of input semantics due to the different parts of the graphics pipeline that feed into each shader unit. Vertex shader input semantics describe the per-vertex information (for example: position, normal, texture coordinates, color, tangent, binormal, etc.) to be loaded from a vertex buffer into a form that can be consumed by the vertex shader. The input semantics directly map to the vertex declaration usage and the usage index.

Pixel shader input semantics describe the information that is provided per pixel by the rasterization unit. The data is generated by interpolating between outputs of the vertex shader for each vertex of the current primitive. The basic pixel shader input semantics link the output color and texture coordinate information to input parameters.

Input semantics can be assigned to shader input by two methods:

  • Appending a colon and the semantic name to the parameter declaration.
  • Defining an input structure with input semantics assigned to each structure member.

Vertex and pixel shaders provide output data to the subsequent graphics pipeline stage. Output semantics are used to specify how data generated by the shader should be linked to the inputs of the next stage. For example, the output semantics for a vertex shader are used to link the outputs of the interpolators in the rasterizer to generate the input data for the pixel shader. The pixel shader outputs are the values provided to the alpha blending unit for each of the render targets or the depth value written to the depth buffer.

Vertex shader output semantics are used to link the shader both to the pixel shader and to the rasterizer stage. A vertex shader that is consumed by the rasterizer and not exposed to the pixel shader must generate position data as a minimum. Vertex shaders that generate texture coordinate and color data provide that data to a pixel shader after interpolation is done.

Pixel shader output semantics bind the output colors of a pixel shader with the correct render target. The pixel shader output color is linked to the alpha blend stage, which determines how the destination render targets are modified. The pixel shader depth output can be used to change the destination depth values at the current raster location. The depth output and multiple render targets are only supported with some shader models.

The syntax for output semantics is identical to the syntax for specifying input semantics. The semantics can be either specified directly on parameters declared as "out" parameters or assigned during the definition of a structure that either returned as an "out" parameter or the return value of a function.

Semantics identify where data comes from. Semantics are optional identifiers that identify shader inputs and outputs. Semantics appear in one of three places:

  • After a structure member.
  • After an argument in a function's input argument list.
  • After the function's input argument list.

This example uses a structure to provide one or more vertex shader inputs, and another structure to provide one or more vertex shader outputs. Each of the structure members uses a semantic.

vector vClr;

struct VS_INPUT
{
    float4 vPosition : POSITION;
    float3 vNormal : NORMAL;
    float4 vBlendWeights : BLENDWEIGHT;
};

struct VS_OUTPUT
{
    float4  vPosition : POSITION;
    float4  vDiffuse : COLOR;

};

float4x4 mWld1;
float4x4 mWld2;
float4x4 mWld3;
float4x4 mWld4;

float Len;
float4 vLight;

float4x4 mTot;

VS_OUTPUT VS_Skinning_Example(const VS_INPUT v, uniform float len=100)
{
    VS_OUTPUT out;

    // Skin position (to world space)
    float3 vPosition =
        mul(v.vPosition, (float4x3) mWld1) * v.vBlendWeights.x +
        mul(v.vPosition, (float4x3) mWld2) * v.vBlendWeights.y +
        mul(v.vPosition, (float4x3) mWld3) * v.vBlendWeights.z +
        mul(v.vPosition, (float4x3) mWld4) * v.vBlendWeights.w;

    // Skin normal (to world space)
    float3 vNormal =
        mul(v.vNormal, (float3x3) mWld1) * v.vBlendWeights.x +
        mul(v.vNormal, (float3x3) mWld2) * v.vBlendWeights.y +
        mul(v.vNormal, (float3x3) mWld3) * v.vBlendWeights.z +
        mul(v.vNormal, (float3x3) mWld4) * v.vBlendWeights.w;

    // Output stuff
    out.vPosition    = mul(float4(vPosition + vNormal * Len, 1), mTot);
    out.vDiffuse  = dot(vLight,vNormal);

    return out;
}

The input structure identifies the data from the vertex buffer that will provide the shader inputs. This shader maps the data from the position, normal, and blendweight elements of the vertex buffer into vertex shader registers. The input data type does not have to exactly match the vertex declaration data type. If it doesn't exactly match, the vertex data will automatically be converted into the HLSL's data type when it is written into the shader registers. For instance, if the normal data were defined to be of type UINT by the application, it would be converted into a float3 when read by the shader.

If the data in the vertex stream contains fewer components than the corresponding shader data type, the missing components will be initialized to 0 (except for w, which is initialized to 1).

Input semantics are similar to the values in the D3DDECLUSAGE.

The output structure identifies the vertex shader output parameters of position and color. These outputs will be used by the pipeline for triangle rasterization (in primitive processing). The output marked as position data denotes the position of a vertex in homogenous space. As a minimum, a vertex shader must generate position data. The screen space position is computed after the vertex shader completes by dividing the (x, y, z) coordinate by w. In screen space, -1 and 1 are the minimum and maximum x and y values of the boundaries of the viewport, while z is used for z-buffer testing.

Output semantics are also similar to the values in D3DDECLUSAGE. In general, an output structure for a vertex shader can also be used as the input structure for a pixel shader, provided the pixel shader does not read from any variable marked with the position, point size, or fog semantics. These semantics are associated with per-vertex scalar values that are not used by a pixel shader. If these values are needed for the pixel shader, they can be copied into another output variable that uses a pixel shader semantic.

Global variables are assigned to registers automatically by the compiler. Global variables are also called uniform parameters because the contents of the variable is the same for all pixels processed each time the shader is called. The registers are contained in the constant table, which can be read using the ID3DXConstantTable interface.

Input semantics for pixel shaders map values into specific hardware registers for transport between vertex shaders and pixel shaders. Each register type has specific properties. Because there are currently only two semantics for color and texture coordinates, it is common for most data to be marked as a texture coordinate even when it is not.

Notice that the vertex shader output structure used an input with position data, which is not used by the pixel shader. HLSL allows valid output data of a vertex shader that is not valid input data for a pixel shader, provided that it is not referenced in the pixel shader.

Input arguments can also be arrays. Semantics are automatically incremented by the compiler for each element of the array. For instance, consider the following explicit declaration:

struct VS_OUTPUT
{
    float4 Position   : POSITION;
    float3 Diffuse    : COLOR0;
    float3 Specular   : COLOR1;
    float3 HalfVector : TEXCOORD3;
    float3 Fresnel    : TEXCOORD2;
    float3 Reflection : TEXCOORD0;
    float3 NoiseCoord : TEXCOORD1;
};

float4 Sparkle(VS_OUTPUT In) : COLOR

The explicit declaration given above is equivalent to the following declaration that will have semantics automatically incremented by the compiler:

float4 Sparkle(float4 Position : POSITION,
                 float3 Col[2] : COLOR0,
                 float3 Tex[4] : TEXCOORD0) : COLOR0
{
   // shader statements
   ...

Just like input semantics, output semantics identify data usage for pixel shader output data. Many pixel shaders write to only one output color. Pixel shaders can also write out a depth value into one or more multiple render targets at the same time (up to four). Like vertex shaders, pixel shaders use a structure to return more than one output. This shader writes 0 to the color components, as well as to the depth component.

struct PS_OUTPUT
{
    float4 Color[4] : COLOR0;
    float  Depth  : DEPTH;
};

PS_OUTPUT main(void)
{
    PS_OUTPUT out;

   // Shader statements
   ...

  // Write up to four pixel shader output colors
  out.Color[0] =  ...
  out.Color[1] =  ...
  out.Color[2] =  ...
  out.Color[3] =  ...

  // Write pixel depth
  out.Depth =  ...

    return out;
}

Pixel shader output colors must be of type float4. When writing multiple colors, all output colors must be used contiguously. In other words, COLOR1 cannot be an output unless COLOR0 has already been written. Pixel shader depth output must be of type float1.

Samplers and Texture Objects

A sampler contains sampler state. Sampler state specifies the texture to be sampled, and controls the filtering that is done during sampling. Three things are required to sample a texture:

  • A texture
  • A sampler (with sampler state)
  • A sampling instruction

Samplers can be initialized with textures and sampler state as shown here:

sampler s = sampler_state
{
  texture = NULL;
  mipfilter = LINEAR;
};

Here's an example of the code to sample a 2-D texture:

texture tex0;
sampler2D s_2D;

float2 sample_2D(float2 tex : TEXCOORD0) : COLOR
{
  return tex2D(s_2D, tex);
}

The texture is declared with a texture variable tex0.

In this example, a sampler variable named s_2D is declared. The sampler contains the sampler state inside of curly braces. This includes the texture that will be sampled and, optionally, the filter state (that is, wrap modes, filter modes, etc.). If the sampler state is omitted, a default sampler state is applied specifying linear filtering and a wrap mode for the texture coordinates. The sampler function takes a two-component floating-point texture coordinate, and returns a two-component color. This is represented with the float2 return type and represents data in the red and green components.

Four types of samplers are defined (see Keywords) and texture lookups are performed by the intrinsic functions: tex1D, tex2D, tex3D, texCUBE. Here is an example of 3-D sampling:

texture tex0;
sampler3D s_3D;

float3 sample_3D(float3 tex : TEXCOORD0) : COLOR
{
  return tex3D(s_3D, tex);
}

This sampler declaration uses default sampler state for the filter settings and address mode.

Here is the corresponding cube sampling example:

texture tex0;
samplerCUBE s_CUBE;

float3 sample_CUBE(float3 tex : TEXCOORD0) : COLOR
{
  return texCUBE(s_CUBE, tex);
}

And finally, here is is the 1-D sampling example:

texture tex0;
sampler1D s_1D;

float sample_1D(float tex : TEXCOORD0) : COLOR
{
  return tex1D(s_1D, tex);
}

Because the runtime does not support 1-D textures, the compiler will use a 2-D texture with the knowledge that the y-coordinate is unimportant. Since tex1D is implemented as a 2-D texture lookup, the compiler is free to choose the y-component in an efficient manner. In some rare scenarios, the compiler cannot choose an efficient y-component, in which case it will issue a warning.

texture tex0;
sampler s_1D_float;

float4 main(float texCoords : TEXCOORD) : COLOR
{
    return tex1D(s_1D_float, texCoords);
}

This particular example is inefficient because the compiler must move the input coordinate into another register (because a 1-D lookup is implemented as a 2-D lookup and the texture coordinate is declared as a float1). If the code is rewritten using a float2 input instead of a float1, the compiler can use the input texture coordinate because it knows that y is initialized to something.

texture tex0;
sampler s_1D_float2;

float4 main(float2 texCoords : TEXCOORD) : COLOR
{
    return tex1D(s_1D_float2, texCoords);
}

All texture lookups can be appended with "bias" or "proj" (that is, tex2Dbias, texCUBEproj). With the "proj" suffix, the texture coordinate is divided by the w-component. With "bias," the mip level is shifted by the w-component. Thus, all texture lookups with a suffix always take a float4 input. tex1D and tex2D ignore the yz- and z-components respectively.

Samplers may also be used in array, although no back end currently supports dynamic array access of samplers. Therefore, the following is valid because it can be resolved at compile time:

tex2D(s[0],tex)

However, this example is not valid.

tex2D(s[a],tex)

Dynamic access of samplers is primarily useful for writing programs with literal loops. The following code illustrates sampler array accessing:

sampler sm[4];

float4 main(float4 tex[4] : TEXCOORD) : COLOR
{
    float4 retColor = 1;

    for(int i = 0; i < 4;i++)
    {
        retColor *= tex2D(sm[i],tex[i]);
    }

    return retColor;
}
Note

Using the Microsoft Direct3D debug runtime can help you catch mismatches between the number of components in a texture and a sampler.

Writing Functions

Functions break large tasks into smaller ones. Small tasks are easier to debug and can be reused, once proven. Functions can be used to hide details of other functions, which makes a program composed of functions easier to follow.

HLSL functions are similar to C functions in several ways: They both contain a definition and a function body and they both declare return types and argument lists. Like C functions, HLSL validation does type checking on the arguments, argument types, and the return value during shader compilation.

Unlike C functions, HLSL entry point functions use semantics to bind function arguments to shader inputs and outputs (HLSL functions called internally ignore semantics). This makes it easier to bind buffer data to a shader, and bind shader outputs to shader inputs.

A function contains a declaration and a body, and the declaration must precede the body.

float4 VertexShader_Tutorial_1(float4 inPos : POSITION ) : POSITION
{
    return mul(inPos, WorldViewProj );
};

The function declaration includes everything in front of the curly braces:

float4 VertexShader_Tutorial_1(float4 inPos : POSITION ) : POSITION

A function declaration contains:

  • A return type
  • A function name
  • An argument list (optional)
  • An output semantic (optional)
  • An annotation (optional)

The return type can be any of the HLSL basic data types such as a float4:

float4 VertexShader_Tutorial_1(float4 inPos : POSITION ) : POSITION
{
   ...
}

The return type can be a structure that has already been defined:

struct VS_OUTPUT
{
    float4  vPosition        : POSITION;
    float4  vDiffuse         : COLOR;
};

VS_OUTPUT VertexShader_Tutorial_1(float4 inPos : POSITION )
{
   ...
}

If the function does not return a value, void can be used as the return type.

void VertexShader_Tutorial_1(float4 inPos : POSITION )
{
   ...
}

The return type always appears first in a function declaration.

float4 VertexShader_Tutorial_1(float4 inPos : POSITION ) : POSITION

An argument list declares the input arguments to a function. It may also declare values that will be returned. Some arguments are both input and output arguments. Here is an example of a shader that takes four input arguments.

float4 Light(float3 LightDir : TEXCOORD1,
             uniform float4 LightColor,
             float2 texcrd : TEXCOORD0,
             uniform sampler samp) : COLOR
{
    float3 Normal = tex2D(samp,texcrd);

    return dot((Normal*2 - 1), LightDir)*LightColor;
}

This function returns a final color, that is a blend of a texture sample and the light color. The function takes four inputs. Two inputs have semantics: LightDir has the TEXCOORD1 semantic, and texcrd has the TEXCOORD0 semantic. The semantics mean that the data for these variables will come from the vertex buffer. Even though the LightDir variable has a TEXCOORD1 semantic, the parameter is probably not a texture coordinate. The TEXCOORDn semantic type is often used to supply a semantic for a type that is not predefined (there is no vertex shader input semantic for a light direction).

The other two inputs LightColor and samp are labeled with the uniform keyword. These are uniform constants that will not change between draw calls. The values for these parameters come from shader global variables.

Arguments can be labeled as inputs with the in keyword, and output arguments with the out keyword. Arguments cannot be passed by reference; however, an argument can be both an input and an output if it is declared with the inout keyword. Arguments passed to a function that are marked with the inout keyword are considered copies of the original until the function returns, and they are copied back. Here's an example using inout:

void Increment_ByVal(inout float A, inout float B)
{
    A++; B++;
}

This function increments the values in A and B and returns them.

The function body is all of the code after the function declaration.

float4 VertexShader_Tutorial_1(float4 inPos : POSITION ) : POSITION
{
    return mul(inPos, WorldViewProj );
};

The body consists of statements which are surrounded by curly braces. The function body implements all of the functionality using variables, literals, expressions, and statements.

The shader body does two things: it performs a matrix multiply and returns a float4 result. The matrix multiply is accomplished with the mul function, which performs a 4x4 matrix multiply. mul is called an intrinsic function because it is already built into the HLSL library of functions. Intrinsic functions will be covered in more detail in the next section.

The matrix multiply combines an input vector Pos and a composite matrix WorldViewProj. The result is position data transformed into screen space. This is the minimum vertex shader processing we can do. If we were using the fixed function pipeline instead of a vertex shader, the vertex data could be drawn after doing this transform.

The last statement in a function body is a return statement. Just like C, this statement returns control from the function to the statement that called the function.

Function return types can be any of the simple data types defined in HLSL, including bool, int half, float, and double. Return types can be one of the complex data types such as vectors and matrices. HLSL types that refer to objects cannot be used as return types. This includes pixelshader, vertexshader, texture, and sampler.

Here is an example of a function that uses a structure for a return type.

float4x4 WorldViewProj : WORLDVIEWPROJ;

struct VS_OUTPUT
{
    float4 Pos  : POSITION;
};

VS_OUTPUT VS_HLL_Example(float4 inPos : POSITION )
{
    VS_OUTPUT Out;

    Out.Pos = mul(inPos,  WorldViewProj );

    return Out;
};

The float4 return type has been replaced with the structure VS_OUTPUT, which now contains a single float4 member.

A return statement signals the end of a function. This is the simplest return statement. It returns control from the function to the calling program. It returns no value.

void main()
{
    return ;
}

A return statement can return one or more values. This example returns a literal value:

float main( float input : COLOR0) : COLOR0
{
    return 0;
}

This example returns the scalar result of an expression:

return  light.enabled = true ;

This example returns a float4 constructed from a local variable and a literal:

return  float4(color.rgb, 1) ;

This example returns a float4 that is constructed from the result returned from an intrinsic function, and a few literal values:

float4 func(float2 a: POSITION): COLOR
{
    return float4(sin(length(a) * 100.0) * 0.5 + 0.5, sin(a.y * 50.0), 0, 1);
}

This example returns a structure that contains one or more members:

float4x4 WorldViewProj;

struct VS_OUTPUT
{
    float4 Pos  : POSITION;
};

VS_OUTPUT VertexShader_Tutorial_1(float4 inPos : POSITION )
{
    VS_OUTPUT out;
    out.Pos = mul(inPos, WorldViewProj );
    return out;
};

Flow Control

Most current vertex and pixel shader hardware is designed to run a shader line by line, executing each instruction once. HLSL supports flow control, which includes static branching, predicated instructions, static looping, dynamic branching, and dynamic looping.

Previously, using an if statement resulted in assembly-language shader code that implements both the if side and the else side of the code flow. Here is an example of the in HLSL code that was compiled for vs_1_1:

if (Value > 0)
    oPos = Value1;
else
    oPos = Value2;

And here is the resulting assembly code:

// Calculate linear interpolation value in r0.w
mov r1.w, c2.x
slt r0.w, c3.x, r1.w
// Linear interpolation between value1 and value2
mov r7, -c1
add r2, r7, c0
mad oPos, r0.w, r2, c1

Some hardware allows for either static or dynamic looping, but most require linear execution. On the models that do not support looping, all loops must be unrolled. An example is the DepthOfField Sample sample that uses unrolled loops even for ps_1_1 shaders.

HLSL now includes support for each of these types of flow control:

  • static branching
  • predicated instructions
  • static looping
  • dynamic branching
  • dynamic looping

The most common branching support in current hardware shading models is static branching. Static branching is a capability in a shader model that allows for blocks of code to be switched on or off based on a Boolean shader constant. This is a convenient method for enabling or disabling code paths based on the type of object currently being rendered. Between draw calls, you can decide which features you want to support with the current shader and then set the Boolean flags required to get that behavior. Now that HLSL supports branching, any statements that are disabled by a Boolean constant are skipped during execution.

The most familiar branching support is dynamic branching. With dynamic branching, the comparison condition resides in a variable, which means that the comparison is done for each vertex or each pixel at run time (as opposed to the comparison occuring at compile time, or between two draw calls). The performance hit is the cost of the branch plus the cost of the instructions on the side of the branch taken. Dynamic branching is currently available for vertex shaders. Optimizing shaders that work with these models is similar to optimizing code that runs on a CPU.

Writing Shader Fragments

A fragment is a stand-alone shader function. A fragment can be compiled from a vertex shader or a pixel shader. By building encapsulated shader functions, they can be linked together to increase functionality.

You can share parameters from one fragment with another fragment using a semantic. Fragments can be compiled and linked at run time, or compiled offline and linked at run time. One way to use fragments is to generate overloaded shader functions so that each fragment can be compiled for a different compile target. This is a convenient way to use fragments to cover a range of shader models within an effect.

HLSL and assembly fragments can be linked with a fragment linker. The linker (ID3DXFragmentLinker) generates a symbol table that contains the constant table (ID3DXConstantTable). The linker can also optimize register use and remove dead code. Since the linker is part of D3DX, it can be updated independently of the runtime.

HLSL Fragment Syntax

You can turn any HLSL function into a shader fragment by adding a fragment declaration (see Fragment Declaration Syntax). Each parameter that is shared between fragments must be marked by adding an r_ prefix to its semantic. The semantic provides a data link between shared fragment parameters, and is used to build the vertex declaration. Each parameter that is not shared does not need the r_ prefix with its semantic.

Any HLSL function can be converted to a fragment. There are a few shader fragments in the FragmentLinker Sample. For example, here is a vertex shader fragment called AmbientDiffuse, that calculates ambient and diffuse scene lighting:

float3 g_vLightPosition = float3( 0.0f, 5.0f, -5.0f );
float4 g_vLightColor = float4( 1.0f, 1.0f, 1.0f, 1.0f );
float4 g_vMaterialAmbient = float4( 0.3f, 0.3f, 0.3f, 1.0f );
float4 g_vMaterialDiffuse = float4( 0.6f, 0.6f, 0.6f, 1.0f );

void AmbientDiffuse( float3 vPosWorld: r_PosWorld,
                     float3 vNormalWorld: r_NormalWorld,
                     out float4 vColor: COLOR0 )
{
    // Compute the light vector
    float3 vLight = normalize( g_vLightPosition - vPosWorld );

    // Compute the ambient and diffuse components of illumination
    vColor = g_vLightColor * g_vMaterialAmbient;
    vColor += g_vLightColor * g_vMaterialDiffuse * saturate( dot( vLight, vNormalWorld ) );
}
vertexfragment AmbientDiffuseFragment = compile_fragment vs_1_1 AmbientDiffuse();

The shader uses two shared parameters: vPosWorld and vNormalWorld. They are shared parameters because each of them has a custom semantic attached to it (r_PosWorld and r_NormalWorld). The last line of code is the fragment declaration.

Here is an example of a vertex shader fragment that does not have any shared parameters:

float4 g_vLightColor = float4( 1.0f, 1.0f, 1.0f, 1.0f );
float4 g_vMaterialAmbient = float4( 0.3f, 0.3f, 0.3f, 1.0f );

void Ambient( out float4 vColor: COLOR0 )
{
    // Compute the ambient component of illumination
    vColor = g_vLightColor * g_vMaterialAmbient;
}
vertexfragment AmbientFragment = compile_fragment vs_1_1 Ambient();

The fragment still requires the fragment declaration; but because there are no shared parameters, the color argument has a standard semantic with no r_ prefix.

Here's an example of a pixel shader fragment:

texture  g_MeshTexture;             // Color texture for mesh

sampler MeshTextureSampler =
sampler_state
{
    Texture = ;
    MipFilter = LINEAR;
    MinFilter = LINEAR;
    MagFilter = LINEAR;
};

void ModulateTexture( float4 vColorIn: COLOR0,
                      float2 vTexCoord: TEXCOORD0,
                      out float4 vColorOut: COLOR0 )
{
    // Sample and modulate the texture
    vColorOut = vColorIn * tex2D( MeshTextureSampler, vTexCoord );
}
pixelfragment PixelFragment = compile_fragment ps_2_0 ModulateTexture();

This pixel shader fragment is called ModulateTexture because it multiplies (or modulates) the input color by the sampled texture color. Just like an HLSL vertex shader fragment, an HLSL pixel shader fragment also requires a fragment declaration.

Each fragment declaration consists of the following:

  • a keyword that identifies the shader type VertexFragment or PixelFragment
  • the fragment name
  • the compile_fragment keyword
  • the shader compile target
  • the shader function name
Unlike a function prototype in C, a fragment declaration can occur before or after the shader fragment. For more about fragment declaration syntax, see Fragment Declaration Syntax.

The shader compile target is included in the fragment declaration because each fragment is compiled (and validated) against this specific shader model (vs_1_1 in this case). When running an application, it is still the application's responsibility to check the hardware to make sure that it will support this shader model.

Assembly Fragment Syntax

Assembly fragment syntax is similar to the syntax of an assembly block in an effect file. The only difference is that the asm_fragment keyword is used instead of the asm keyword. Unlike HLSL, an assembly fragment does not require a fragment declaration. In assembly, the shared parameters require a custom semantic for each type of register:

  • Use c_ for constant registers.
  • Use r_ for temp registers.
  • Use v_ for input registers.

The semantic provides a data link between shared fragment parameters, and is used to build the vertex declaration. Each shared constant register must be defined at global scope.

Here is an example of a vertex shader fragment created from an assembly shader. The declaration contains the assembly block, with the c_, r_, and v_ prefix on the appropriate shared parameters:

vertexfragment ComputeGlowAsm =
asm_fragment
{
    vs_1_1

    dp3 r_Length.w, r_TransformedNormal.xyz, r_TransformedNormal.xyz
    rsq r_Length.w, r_Length.w
    mul r_TransformedNormal.xyz, r_TransformedNormal.xyz, r_Length.www
    mov r_Temp.x, c_One.x

    mad r_Power.z, r_TransformedNormal.z, -r_TransformedNormal.z, c_One.x
    mul r_Power.z, r_Power.z, r_Power.z
    mul oD0, c_vGlowColor, r_Power.z

    mad r_TransformedPosition.xyz, r_TransformedNormal.xyz,
                          c_vDisplace.xxx, r_TransformedPosition.xyz
    mov r_TransformedPosition.w, c_One.x
    m4x4 oPos, r_TransformedPosition, c_mProjection
};


Using HLSL Shaders
Microsoft DirectX 9.0 SDK Update (October 2004)

Using HLSL Shaders

  • Compiling a Shader for Specific Hardware
  • Initializing Shader Constants
  • Binding a Shader Parameter to a Particular Register
  • Rendering a Programmable Shader
  • Debugging Shaders
  • Building and Rendering Fragments

Compiling a Shader for Specific Hardware

Shaders were first added to Microsoft DirectX in DirectX 8.0. At that time, several virtual shader machines were defined, each roughly corresponding to a particular graphics processor produced by the top 3-D graphics vendors. For each of these virtual shader machines, an assembly language was designed. In DirectX 9.0 and DirectX 8.1, programs written to the shader models (names vs_1_1 and ps_1_1 - ps_1_4) were relatively short and were generally written by developers directly in the appropriate assembly language. The application would pass this human-readable assembly language code to the D3DX library via D3DXAssembleShader and get back a binary representation of the shader which would in turn get passed via IDirect3DDevice9::CreateVertexShader or IDirect3DDevice9::CreatePixelShader. For more detail, see the software development kit (SDK).

The situation in DirectX 9.0 is similar. An application passes an high-level shader language (HLSL) shader to D3DX via D3DXCompileShader and gets back a binary representation of the compiled shader which in turn is passed to Microsoft Direct3D via IDirect3DDevice9::CreatePixelShader or IDirect3DDevice9::CreateVertexShader. The runtime does not know anything about HLSL, only the binary assembly shader models. This is nice because it means that the HLSL compiler can be updated independent of the Direct3D runtime.

In addition to the development of the HLSL compiler, DirectX 9.0 also introduced the assembly-level shader models to expose the functionality of the latest generation of graphics hardware. Application developers can work in assembly for these new models (vs_2_0, vs_3_0, ps_2_0, ps_3_0) but we expect most developers to move to HLSL for shader development.

Of course, the ability to write an HLSL program to express a particular shading algorithm does not automatically enable it to run on any given hardware. An application calls D3DX to compile a shader into binary assembly code with D3DXCompileShader. One of the limitations with this entry point is a parameter that defines which of the assembly-level models (or compilation targets) the HLSL compiler should use to express the final shader code. If an application is doing HLSL shader compilation at run time (as opposed to compile time or offline), the application could examine the capabilities of the Direct3D device and select the compilation target to match. If the algorithm expressed in the HLSL shader is too complex to execute on the selected compilation target, compilation will fail. This means that while HLSL is a huge benefit to shader development, it does not free developers from the realities of shipping games to a target audience with graphics devices of varying capabilities. As a game developer, you still have to manage a tiered approach to your visuals; this means writing better shaders for more capable graphics cards and writing more basic versions for older cards. With well written HLSL, however, this burden can be eased significantly.

Rather than compile HLSL shaders using D3DX on the customer's machine at application load time or on first use, many developers choose to compile their shader from HLSL to binary assembly code before they even ship. This keeps their HLSL source code away from prying eyes and also ensures that all the shaders their application will ever run have gone through their internal quality assurance process. A convenient utility that allows developers to compile shaders offline is the HLSL Command-Line Compiler. This utility has a number of options that you can use to compile code for the specified compile target. Studying the disassembled output can be very educational during development if you want to optimize your shaders or just generally get to know the virtual shader machine's capabilities at a more detailed level. These options are summarized below:

Initializing Shader Constants

Shader constants are contained in the constant table. This can be accessed with the ID3DXConstantTable interface. Global shader variables can be initialized in shader code. These are initialized at run time by calling ID3DXConstantTable::SetDefaults.

Binding a Shader Parameter to a Particular Register

The compiler will automatically assign registers to global variables. The compiler would assign Environment to sampler register s0, SparkleNoise to sampler register s1, and k_s to constant register c0 (assuming no other sampler or constant registers were already assigned) for the following three global variables:

sampler Environment;
sampler SparkleNoise;
float4 k_s;

It is also possible to bind variables to a specific register. To force the compiler to assign to a particular register, use the following syntax:

register(RegisterName)

where RegisterName is the name of the specific register. The following examples demonstrate the specific register assignment syntax, where the sampler Environment will be bound to sampler register s1, SparkleNoise will be bound to sampler register s0, and k_s will be bound to constant register c12:

sampler Environment : register(s1);
sampler SparkleNoise : register(s0);
float4 k_s : register(c12);

Rendering a Programmable Shader

A shader is rendered by setting the current shader in the device, initializing the shader constants, telling the device where the varying input data is coming from, and finally rendering the primitives. Each of these can be accomplished by calling the following methods respectively:

  • SetVertexShader
  • SetConstants
  • SetStreamSource
  • DrawPrimitive

Debugging Shaders

Do you want to debug your vertex and pixel shader code by stepping through the per-vertex code or the per-pixel code and watching instructions as they are executed, looking at the values in shader constants and variables, and setting breakpoints in trouble spots? The DirectX extension for Microsoft Visual Studio .NET is fully integrated into the Visual Studio .NET Integrated Development Environment (IDE).

In order to prepare for shader debugging, you must install the right tools on your machine. These are listed below. If you already have the right tools installed, you can also try the Goal 5: Shader Debugging Tutorial. To see more about all the features of the debugger, see DirectX Extensions for Visual Studio .NET.

Getting Started Debugging Shaders

Building and Rendering Fragments

Fragments can be compiled, linked, and rendered with or without effects. Since it is easier to take advantage of an effect, this case will be shown first.

Building and Rendering Fragments from an Effect

Given an effect that contains an HLSL or an assembly fragment, (see Writing Shader Fragments), compile the fragment by calling D3DXGatherFragmentsFromFile as shown here:

DWORD         g_dwShaderFlags; // Shader compilate and link flags
LPD3DXBUFFER  g_pCompiledFragments = NULL;

    D3DXGatherFragmentsFromFile( L"FragmentLinker.fx", NULL,
                NULL, g_dwShaderFlags, &g_pCompiledFragments, NULL );

D3DXGatherFragmentsFromFile requires the .fx file, pointers to the #define and #include handlers (both set to NULL in this example), and the shader compile flags. The method returns a buffer which contains the compiled shader fragment. The method can return a second buffer with compile errors, which is set to NULL in this example because it is not used. D3DXGatherFragments is overloaded to handle loading fragments from a string, a file, or a resource.

Set your debugger to break on this method to look for compile errors in the debugger. The compiler can catch errors in syntax, but it cannot check for registers that are shared incorrecly due to the fact that it has no way to predict which parameters a user may want to share between fragments.

You need a fragment linker to manage the compiled fragments. Create the fragment linker by calling D3DXCreateFragmentLinker:

ID3DXFragmentLinker* g_pFragmentLinker = NULL;     // Fragment linker interface
IDirect3DDevice9*    pd3dDevice        = NULL;

    // Initialize the device before using it
    ...

    // Create the fragment linker interface
    D3DXCreateFragmentLinker( pd3dDevice, 0, &g_pFragmentLinker );

Then simply add the compiled fragments to the fragment linker using ID3DXFragmentLinker::AddFragments.

    // Add the compiled fragments to a list
    g_pFragmentLinker->AddFragments(
              (DWORD*)g_pCompiledFragments->GetBufferPointer() );

ID3DXFragmentLinker::AddFragments requires a pointer to the DWORD stream that contains the compiled shader.

After compiling fragments and creating a fragment linker, there are several ways to link fragments. One way to link a vertex shader fragment is to call ID3DXFragmentLinker::LinkVertexShader. Here is an example that links two vertex shader fragments:

    // Get a handle to each fragment
    D3DXHANDLE fragmentHandle[2];
    fragmentHandle[0] =
        (D3DXHANDLE)g_pFragmentLinker->GetFragmentHandleByName("Ambient");
    fragmentHandle[1] =
        (D3DXHANDLE)g_pFragmentLinker->GetFragmentHandleByName("AmbientDiffuseFragment");

    // Link the fragments together to form a vertex shader
    IDirect3DVertexShader9* pVertexShader = NULL;
    g_pFragmentLinker->LinkVertexShader( "vs_1_1", g_dwShaderFlags,
              fragmentHandle, 2, &pVertexShader, NULL );

This requires a shader compile target, the shader compile and link flags, and a handle to each of the fragments to link. If the fragments are successfully linked, ID3DXFragmentLinker::LinkVertexShader returns a vertex shader (IDirect3DVertexShader9). The vertex shader needs to be set in the effect before rendering. But before this, here's how the shader is declared in the effect:

VertexShader MyVertexShader; // Vertex shader set by the application

The effect technique contains all the state set for a pass. This pass specifies the vertex shader like this:

technique RenderScene
{
    pass P0
    {
        VertexShader = <MyVertexShader>;
        PixelShader = compile ps_1_1 ModulateTexture();
    }
}

So, to pass the vertex shader pointer from the application to the effect, use ID3DXEffect::SetVertexShader :

    // Associate this vertex shader with the effect object
    g_pEffect->SetVertexShader( "MyVertexShader", pVertexShader );

With the effect's vertex shader created and initialized, the render code also sets the uniform constants and calls the render loop. Set the uniform constants similar to this:

    // Update the uniform shader constants.
    g_pEffect->SetMatrix( "g_mWorldViewProjection", &mWorldViewProjection );
    g_pEffect->SetMatrix( "g_mWorld", &mWorld );
    g_pEffect->SetFloat( "g_fTime", (float)fTime );

Then render the effect by setting the current technique and pass:

    // Render the scene
    if( SUCCEEDED( pd3dDevice->BeginScene() ) )
    {
        // Apply the technique contained in the effect
        UINT cPasses, iPass;
        g_pEffect->Begin(&cPasses, 0);

        for (iPass = 0; iPass < cPasses; iPass++)
        {
            g_pEffect->BeginPass(iPass);

            // Render the mesh with the applied technique
            g_pMesh->DrawSubset(0);

            g_pEffect->EndPass();
        }
        g_pEffect->End();

        pd3dDevice->EndScene();
    }

When setting uniform shader constants, it is more efficient to cache a handle to the parameter by calling ID3DXEffect::GetParameterByName. This avoids the string lookup that is necessary when calling effect methods like ID3DXEffect::SetMatrix.

  // Instead of setting a uniform constant like this in the render loop
  g_pEffect->SetMatrix( "g_mWorldViewProjection", &mWorldViewProjection );

  // Get a handle to a uniform constant outside of the render loop
  D3DXHANDLE hParameter;
  GetParameterByName( hParameter,"g_mWorldViewProjection");

  ...

  // Use the handle to set the uniform constant in the render loop
  g_pEffect->SetMatrix(hParameter);

Building and Rendering Fragments Without an Effect

Building a fragment that does not live in an effect is very similar to building a fragment that is in an effect. You still use D3DXGatherFragments to compile one or more fragments. If the fragments are HLSL, they will be compiled. If the fragments are assembly fragments, they will be assembled. You still create a fragment linker(created by D3DXCreateFragmentLinker), add all the fragments to the linker (with ID3DXFragmentLinker::AddFragments), and link the fragments together to create a vertex shader with ID3DXFragmentLinker::LinkVertexShader.

Rendering a fragment without an effect is slightly different, because you cannot use the effect to set the uniform shader constants. Because every vertex or pixel shader contains a constant table (ID3DXConstantTable), you will need to get the constant table and use it to initialize the uniform shader constants.

    // Compile the fragments to a buffer.
    D3DXGatherFragmentsFromFile( L"FragmentLinker.fx", NULL, NULL,
        g_dwShaderFlags, &g_pCompiledFragments, NULL );

    // Link the fragments together to form a shader.
    IDirect3DVertexShader9* pVertexShader = NULL;
    V_RETURN( g_pFragmentLinker->LinkVertexShader( "vs_1_1", g_dwShaderFlags,
        aHandles, NUM_FRAGMENTS, &pVertexShader, NULL ) );

    // Get a pointer to the constant table from the compiled shader.
    LPD3DXCONSTANTTABLE ppConstantTable;
    D3DXGetShaderConstantTable(
        (DWORD*)g_pCompiledFragments->GetBufferPointer(), &ppConstantTable );

The fragment linking operation efficiently links together HLSL fragments and assembly fragments, and generates a shader object from one or more fragments. The constant table generated from a fragment is identical to the constant table generated from a shader. This is because each binary shader contains the constant table and the shader input declarations.


HLSL Tutorials
Microsoft DirectX 9.0 SDK Update (October 2004)

HLSL Tutorials

The HLSL Workshop is a set of tutorials that make it easy to learn how to generate high-level shader language (HLSL) shaders. These tutorials are .fx files designed to run in the EffectEdit Sample. The tutorials offer a step-by-step approach to learning how to use vertex, pixel, and texture shaders in HLSL to create the following functionality:

  • Goal 1: Hemispheric Lighting Tutorial
  • Goal 2: Vertex Animation Tutorial
  • Goal 3: Environment Mapping
  • Goal 4: Procedural Texture Tutorial

If you already have the right tools installed, you can also try the Goal 5: Shader Debugging Tutorial. To see more about all the features of the debugger, see DirectX Extensions for Visual Studio .NET.


Getting Started Debugging Shaders
Microsoft DirectX 9.0 SDK Update (October 2004)

Getting Started Debugging Shaders

Do you want to debug your vertex and pixel shader code by stepping through the per-vertex code or the per-pixel code and watching instructions as they are executed, looking at the values in shader constants and variables, and setting breakpoints in trouble spots? The Microsoft DirectX extensions for Microsoft Visual Studio .NET, which we will refer to as the shader debugger, is fully integrated into the Visual Studio .NET Integrated Development Environment (IDE).

In order to prepare for shader debugging, you must install the right tools on your machine. These are listed below. If you already have the right tools installed, you can also try the Goal 5: Shader Debugging Tutorial. To see more about all the features of the debugger, see DirectX Extensions for Visual Studio .NET.

Using the Shader Debugger

Here is a list of some of the operations that you can perform within the IDE while a shader is running:

  • Debug vertex and pixel shaders.
  • Debug high-level shader language (HLSL) and assembly shaders.
  • Look at the contents of variables, registers, and device state.
  • Use the IDE to run the code, single step through code, or break where necessary.
  • Set breakpoints on lines or on a pixel area.
  • Perform expression evaluation in a watch window.
  • View the assembly code generated by the HLSL compiler.
  • View loaded texture(s) on the Microsoft Direct3D device.
  • View render target(s) as pixel shaders write to them.
  • See syntax coloring for recognized file types, including: .fx (effects files), .vsh (assembly vertex shader files), and .psh (assembly pixel shader files).

Setting Up the Tools

To prepare for debugging, you must load the right tools on your machine, configure the runtime, and set up your application for debugging. This section will walk you through each of these preparation steps:

  • Install Visual Studio .NET
  • Install the DirectX 9 SDK (install the software development kit (SDK) and the shader debugger from the SDK)
  • Enable Debug Mode from the Control Panel

Install Visual Studio .NET

Visual Studio .NET provides a compiler and debugging tools for several programming languages within an interactive development environment. The shader debugger is a Visual Studio .NET extension, meaning that it is designed and integrated into Visual Studio .NET. To perform shader debugging with this extension, you will need to have access to Visual Studio .NET. For information about getting Visual Studio .NET as well as the installation instructions, see Microsoft Visual Studio World Wide Web link 2002 or 2003.

Install the DirectX 9 SDK

The shader debugger is installed as part of the DirectX 9.0 SDK install. In fact, you must install the SDK for two reasons: you will need the proper debug or reference dynamic-link libraries (DLLs), and you will need the shader debugger. The DirectX debug DLLs or the reference DLL can be used to debug vertex shaders, but a reference DLL must be used to debug a pixel shader.

The SDK install wizard takes care of most of this for you, but here is a step-by-step description for installing the SDK and the shader debugger:

  1. Install the DirectX 9.0 SDK.
  2. Click Next on the InstallShield Wizard.
  3. Select the Add radio button if you don't have the SDK on your machine. Or select Modify if you have the SDK installed, but you want to change something (such as adding the shader debugger).

  4. In the Custom Setup panel, you will see a listing of all the resources available on the CD. Anything marked with the red X will not be installed. Because we want to debug shaders, we need to make sure the shader debugger will be installed. This is in the DirectX Utilities folder, and is called DirectX extensions for Visual Studio .NET. If this does not have a red X on it, it will be installed. If it does have the red X, left click on the X and select "This feature will be installed on the local hard drive". It should look like this when you are done.

  5. Click Next one more time and wait for the install wizard to finish installing the SDK. This can take a few minutes, especially if you copy all the samples (C++, C#, and VB) to your hard drive. When the install finishes, you will get a message that it was successful. In addition you can now start Visual Studio .NET and check it to see the following on the splash screen when it starts up:

    The DirectX extensions for Visual Studio .NET logo in the bottom right corner means that Visual Studio .NET has the extensions loaded, and is now available for shader debugging.

Enable Debug Mode from the Control Panel

If you are are ready to enable the debug switches in the control panel, then you must already have done the following:

  • Install Visual Studio .NET
  • Install the DirectX 9 SDK

With all the right tools installed, the next step is to enable the debugger settings. This is easily done by launching the DirectX dialog box from the control panel (Start/Control Panel/DirectX). This will open up a dialog box that looks like this:

There are a number of settings on this dialog box, but we are interested in two in particular to enable shader debugging. These are:

  • In the Debug/Retail D3D Runtime group of controls, select the Use Debug Version of Direct3D radio button. This tells DirectX to use the debug version of the DLLs which allows you to debug any vertex shader that your graphics adapter supports. If you set this to retail, Direct3D will run the release DLLs which do not support any type of shader debugging.
  • In the Debugging group of controls, set the Enable Shader Debugging check box. This enables Visual Studio .NET to debug shader code.

The debug mode can also be enabled from within Visual Studio .NET by clicking on Tools | Options | Debugger | DirectX.

This concludes preparing the tools for shader debugging. In summary, you need to rememember to:

  • Install Visual Studio .NET.
  • Install the DirectX SDK with debug or reference DLLs and the shader debugger.
  • Enable the DirectX debug flags.

Choosing the Device Type

To debug a shader, the shader must be running on the right type of Direct3D device since vertex and pixel shaders can only be debugged on certain devices. Once you determine whether you want to debug a vertex shader, a pixel shader, or both, you can use the following table to choose a device type that supports debug.

 | HAL Device | HAL Device | REF Device | REF Device
Shader | SWVP | HWVP or pure HWVP | SWVP | HWVP or pure HWVP
Vertex Shader | Yes, with the debug runtime | No | Yes, with the debug runtime | No
Pixel Shader | No | No | Yes | Yes

Choose the device type(s) that support the type of shader you want to debug. Then when your application runs create that device type with IDirect3D9::CreateDevice. The SDK samples also use F2 to switch the device type once the sample is running. Any entry in the table that says "No" means that it is not possible to debug that type of shader on that type of device.

Setting the Shader Flags

With the device type chosen, you can now make the appropriate choice for the shader compile flags. These flags are one or more #defines that are enumerated in D3DXSHADER Compile Options. These flags are specified at shader creation time when calling functions like D3DXCompileShaderXXX or ID3DXEffectCompiler::CompileShader or ID3DXEffectCompiler::CompileEffect.

Since we want to debug the shader, we need to use these two flags:

  • D3DXSHADER_DEBUG tells the compiler to build a shader with source debugging information.
  • D3DXSHADER_SKIPOPTIMIZATION tells the compiler to skip optimization. Optimization may reorder instructions; this is good for making shaders fast, but also makes debugging more difficult. On the other hand, unoptimized shaders might exceed the maximum instruction limits if they are close to the limits without optimization.

If you run into the problem of exceeding instruction slot limits when running unoptimized, there is an additional flag that you can choose. D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT (or D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT) force the compiler to compile against the next higher available software target. Because software shader models do not have instruction slot limits, this flag ensures that unoptimized shaders do not have this problem. This flag still does the other things that the skip optimization flag does, such as preventing instruction reordering and dead code elimination. The shaders will run in software which will reduce their performance.

Troubleshooting

If you have read this shader debugging tutorial and followed the steps, you are probably debugging a vertex shader already. If you skipped through the tutorial and are still having problems, the table below offers a summary of the problems you may encounter, and what you need to do to solve them. The solutions listed in the table are the same ones covered in the tutorial.

If you cannot: You may need to:
Launch VS .NET. | Install VS .NET. See Install Visual Studio .NET.
See the "DX extensions for VS.NET" icon on the start up screen when you launch Visual Studio .NET or cannot find the debugger menu option Debug, Direct3D, Start With Direct3D Debugging. | Need to install the shader debugger from the SDK. See Install the DirectX 9 SDK (installing the SDK and the shader debugger from the SDK).
Put a breakpoint in your shader code

The shader debugger will give you the following message: "The breakpoint will not currently be hit. No executable code is currently loaded at this location."

You need to do one or more of the following:
  • Enable Direct3D shader debugging from the control panel. See Enable Debug Mode from the Control Panel. The shader will warn you with a message box if this is not enabled.
  • Build a Visual Studio .NET debug project.
  • Install the DirectX SDK to get the debug or reference DLLs and the shader debugger.

    The shader debugger warns you with a message box if the debug or reference DLLs are not installed.

  • Launch the debugger from Debug, Direct3D, Start With Direct3D Debugging.
  • Use a shader/effect compile flag compatible with debugging.

    If you don't compile the with D3DXSHADER_DEBUG | D3DXSHADER_SKIPOPTIMIZATION, the debugger will warn you with a message box.

  • Use a device compatible with debugging.

    The debugger warns you if you try to use a HWVP device with a vertex shader, or a hardware abstraction layer (HAL) device with a pixel shader.


Shader Model 3
Microsoft DirectX 9.0 SDK Update (October 2004)

Shader Model 3

Vertex shaders and pixel shaders are simplified considerably from earlier shader versions. If you are implementing shaders in hardware, you may not use vs_3_0 or ps_3_0 with any other shader versions, and you may not use either shader type with the fixed function pipeline. These changes make it possible to simplify drivers and the runtime. The only exception is that software-only vs_3_0 shaders may be used with any pixel shader version. In addition, if you are using a software-only vs_3_0 shader with a previous pixel shader version, the vertex shader can only use output semantics that are compatible with flexible vertex format (FVF) codes.

The semantics used on vertex shader outputs must be used on pixel shader inputs. The semantics are used to map the vertex shader outputs to the pixel shader inputs, similar to the way the vertex declaration is mapped to the vertex shader input registers and previous shader models. See Match Semantics on vs_3_0 and ps_3_0 Shaders.

Additional wrap mode render states have been added to cover the possibility of additional texture coordinates in this new scheme. Attributes with D3DDECLUSAGE_TEXCOORD and usage index from 0 to 15 are interpolated in wrap mode when the corresponding D3DRS_WRAP* is set.

  • Vertex Shader Model 3 Features
  • Pixel Shader Model 3 Features
  • Match Semantics on vs_3_0 and ps_3_0 Shaders
  • Fog, Depth, and Shading Mode Changes
  • Floating Point and Integer Conversions
  • Specifying Full or Partial Precision
  • Software Vertex and Pixel Shaders

Vertex Shader Model 3 Features

The vertex shader output register types have been collapsed into twelve registers (see Output Registers). Each register that is used needs to be declared using the dcl instruction and a semantic (for example, dcl_color0 o0.xyzw).

The 3_0 vertex shader model (vs_3_0) expands on the features of vs_2_0 with more powerful register indexing, a set of simplified output registers, the ability to sample a texture in a vertex shader, and the ability to control the rate at which shader inputs are initialized.

Index Any Register

All Input Register and Output Registers can be indexed using Loop Counter Register (only constant registers could be indexed in earlier versions.)

You must declare input and output registers before indexing them. However, you may not index any output register that has been declared with a position or point size semantic. In fact, if indexing is used the position and psize semantics have to be declared in the o0 and o1 registers respectively.

You are only allowed to index a continuous range of registers; that is, you cannot index across registers that have not been declared. While this restriction may be inconvenient, it permits hardware optimization to take place. Attempting to index across non-contiguous registers will produce undefined results. Shader validation does not enforce this restriction.

Simplify Output Registers

All the various types of output registers have been collapsed into twelve output registers: 1 for position, 2 for color, 8 for texture, and 1 for fog or point size. These registers will interpolate any data they contain for the pixel shader. Output register declarations are required and semantics are assigned to each register.

The registers can be broken down as follows:

  • At least one register must be declared as a four-component position register. This is the only vertex shader register that is required.
  • The first ten registers consumed by a shader may use up to four components (xyzw) maximum.
  • The last (or twelfth) register may only contain a scalar (such as point size).

For a listing of the registers, see Registers - vs_3_0.

Texture Sample in a Vertex Shader

Vertex shader 3_0 supports texture lookup in the vertex shader using texldl. See Vertex Textures in vs_3_0.

Pixel Shader Model 3 Features

The pixel shader color and texture registers have been collapsed into ten input registers (see Input Register Types). The Face Register is a floating point scalar register. Only the sign of this register is valid. If the sign is negative the primitive is a back face. This can be used inside a pixel shader to achieve two-sided lighting, for instance. The Position Register references the current (x,y) pixels.

The shader constant registers can be set using:

  • IDirect3DDevice9::SetPixelShaderConstantB
  • IDirect3DDevice9::SetPixelShaderConstantI
  • IDirect3DDevice9::SetPixelShaderConstantF

Match Semantics on vs_3_0 and ps_3_0 Shaders

There are some restrictions on semantic usage with vs_3_0 and ps_3_0. In general, you need to be careful when using a semantic for a shader input that matches a semantic used on a shader output.

For instance, this pixel shader packs multiple names into one register:

ps_3_0
dcl_texcoord0 v0.x
dcl_texcoord1 v0.yz // Valid to pack multiple names into one register
dcl_texcoord2_centroid v1.w
...

Each register has a different semantic. Notice that you can also name v0.x and v0.yz with different (multiple) semantics because of the use of the write mask.

Given the pixel shader, the following vs_3_0 shader cannot be paired with it:

vs_3_0
...
dcl_texcoord0 o5.x
dcl_texcoord1 o6.yzw
...

These two shaders conflict with their use of the D3DDECLUSAGE_TEXCOORD0 and D3DDECLUSAGE_TEXCOORD1 semantics.

Rewrite the vertex shader like this to avoid the semantic collision:

vs_3_0
...
dcl_texcoord2 o3
dcl_texcoord3 o9
...

Similarly, a semantic name declared on different input registers in the pixel shader (v0 and v1 in the pixel shader) cannot be used in a single output register in this vertex shader. For instance, this vertex shader cannot be paired with the pixel shader because D3DDECLUSAGE_TEXCOORD1 is used for both pixel shader input registers (v0, v1) and the vertex shader output register o3.

vs_3_0
...
dcl_texcoord0 o3.x
dcl_texcoord1 o3.yz

dcl_texcoord2 o3.w // BAD! Would be valid if this were not o3
dcl_texcoord3 o9 ...

On the other hand, this vertex shader cannot be paired with the pixel shader because the output mask for a parameter with a given semantic does not provide the data that is requested by the pixel shader:

vs_3_0
...
dcl_texcoord0 o5.x
dcl_texcoord1 o5.yzw
dcl_texcoord2 o7.yz // BAD! Would be valid if w were included
dcl_texcoord3 o9
...

This vertex shader does not provide an output with one of the semantic names requested by the pixel shader, so the shader pairing is invalid:

vs_3_0
...
dcl_texcoord0 o5.x
dcl_texcoord1 o5.yzw
dcl_texcoord3 o9
// The pixel shader wants texcoord2, with a w component,
// but it isn't output by this vertex shader at all!
...

Fog, Depth, and Shading Mode Changes

When D3DRS_SHADEMODE is set for flat shading during clipping and triangle rasterization, attributes with D3DDECLUSAGE_COLOR are interpolated as flat shaded. If any components of a register are declared with a color semantic but other components of the same register are given different semantics, flat shading interpolation (linear vs. flat) will be undefined on the components in that register without a color semantic.

If fog rendering is desired, vs_3_0 and ps_3_0 shaders must implement fog. No fog calculations are done outside of the shaders. There is no fog register in vs_3_0 and additional semantics D3DDECLUSAGE_FOG (for fog blend factor computed per vertex) and D3DDECLUSAGE_DEPTH (for passing in a depth value to the pixel shader to compute the fog blend factor) have been added.

Texture stage state D3DTSS_TEXCOORDINDEX is ignored when using pixel shader 3.0.

The following values have been added to accommodate these changes:

// Fog and Depth usages
D3DDECLUSAGE_FOG
D3DDECLUSAGE_DEPTH

// Additional wrap states for vs_3_0 attributes with D3DDECLUSAGE_TEXCOORD
D3DRS_WRAP8
D3DRS_WRAP9
D3DRS_WRAP10
D3DRS_WRAP11
D3DRS_WRAP12
D3DRS_WRAP13
D3DRS_WRAP14
D3DRS_WRAP15

Floating Point and Integer Conversions

Floating point math happens at different precision and ranges (16-bit, 24-bit, and 32-bit) in different parts of the pipeline. A value greater than the dynamic range of the pipeline that enters that pipeline (for example, a 32-bit float texture map is sampled into a 24-bit float pipeline in ps_2_0) creates an undefined result. For predictable behavior, you should clamp such a value to the dynamic range maximum.

Conversion from a floating point value to an integer happens in several places such as:

  • When encountering a mova instruction.
  • During texture addressing.
  • When writing out to a non-floating point render target.

Specifying Full or Partial Precision

Both ps_3_0 and ps_2_x provide support for two levels of precision:

ps_3_0 | ps_2_0 | Precision | Value
x |  | Full | fp32 or higher
x |  | Partial precision | fp16=s10e5
x | x | Full | fp24=s16e7 or higher
x | x | Partial precision | fp16=s10e5

ps_3_0 supports more precision than ps_2_0 does. By default, all operations occur at the full precision level.

Partial precision (see Modifiers for ps_2_0 and Above) is requested by adding the _pp modifier to shader code (provided that the underlying implementation supports it). Implementations are always free to ignore the modifier and perform the affected operations in full precision.

The _pp modifier can occur in two contexts:

  • On a texture coordinate declaration to pass partial-precision texture coordinates to the pixel shader. This could be used when texture coordinates relay color data to the pixel shader, which may be faster with partial precision than with full precision in some implementations.
  • On any instruction to request the use of partial precision, including texture load instructions. This indicates that the implementation is allowed to execute the instruction with partial precision and store a partial-precision result. In the absence of an explicit modifier, the instruction must be performed at full precision (regardless of the precision of the input operands).

An application might deliberately choose to trade off precision for performance. There are several kinds of shader input data which are natural candidates for partial precision processing:

  • Color iterators are well represented by partial-precision values.
  • Texture values from most formats can be accurately represented by partial-precision values (values sampled from 32-bit, floating-point format textures are an obvious exception).
  • Constants may be represented by partial-precision representation as appropriate to the shader.

In all these cases the developer may choose to specify partial precision to process the data, knowing that no input data precision is lost. In some cases, a shader may require that the internal steps of a calculation be performed at full precision even when input and final output values do not have more than partial precision.

Software Vertex and Pixel Shaders

Software implementations (run-time and reference for vertex shaders and reference for pixel shaders) of version 2_0 shaders and above have some validation relaxed. This is useful for debugging and prototyping purposes. The application indicates to the runtime/assembler that it needs some of the validation relaxed using the _sw flag in the assembler (for example, vs_2_sw). A software shader will not work with hardware.

vs_2_sw is a relaxation to the maximum caps of vs_2_x; similarly, ps_2_sw is a relaxation to the maximum caps of ps_2_x. Specifically, the following validations are relaxed:

Shader Model | Resource | Limit
vs_2_sw, vs_3_sw, ps_2_sw, ps_3_sw | Instruction Counts | Unlimited
vs_2_sw, vs_3_sw, ps_2_sw, ps_3_sw | Float Constant Registers | 8192
vs_2_sw, vs_3_sw, ps_2_sw, ps_3_sw | Integer Constant Registers | 2048
vs_2_sw, vs_3_sw, ps_2_sw, ps_3_sw | Boolean Constant Registers | 2048
ps_2_sw | Dependent-read depth | Unlimited
vs_2_sw | flow control instructions and labels | Unlimited
vs_2_sw, vs_3_sw, ps_2_sw, ps_3_sw | Loop start/step/counts | Iteration start and iteration step size for rep and loop instructions are 32-bit signed integers. Count can be up to MAX_INT/64.
vs_2_sw, vs_3_sw, ps_2_sw, ps_3_sw | Port limits | Port limits for all register files are relaxed.
vs_3_sw | Number of interpolators | 16 output registers in vs_3_sw.
ps_3_sw | Number of interpolators | 14(16-2) input registers for ps_3_sw.


Vertex Textures in vs_3_0
Microsoft DirectX 9.0 SDK Update (October 2004)

Vertex Textures in vs_3_0

The vertex shader 3.0 model supports texture lookup in the vertex shader using the texldl texture load statement. The vertex engine contains four texture sampler stages, named D3DVERTEXTEXTURESAMPLER0, D3DVERTEXTEXTURESAMPLER1, D3DVERTEXTEXTURESAMPLER2, and D3DVERTEXTEXTURESAMPLER3. These are distinct from the displacement map sampler and texture samplers in the pixel engine.

To sample textures set at those four stages, you can use the vertex engine and program the stages with the IDirect3D9::CheckDeviceFormat method. Set textures at those stages using IDirect3DDevice9::SetTexture, with the stage index D3DVERTEXTEXTURESAMPLER0 through D3DVERTEXTEXTURESAMPLER3. A new register has been introduced in the vertex shader, the sampler register (like in ps_2_0), which represents the vertex texture sampler. This register needs to be defined in the shader before using it.

An application can query if a format is supported as a vertex texture by calling IDirect3D9::CheckDeviceFormat with D3DUSAGE_QUERY_VERTEXTEXTURE".

Note This is a query flag so it is not accepted in any Create xxx function. A vertex texture created in the default pool can be set as a pixel texture and vice versa. However, to use the software vertex processing, the vertex texture must be created in the scratch pool (no matter if it is a mixed-mode device or a software vertex processing device).

The functionality is identical to the pixel textures, except for the following:

  • Anisotropic texture filtering is not supported, hence D3DSAMP_MAXANISOTROPY is ignored and D3DTEXF_ANISOTROPIC cannot be set for magnify, or minify for these stages.
  • Rate of change information is not available, hence the application has to compute the level of detail and provide that information as a parameter to texldl.

Restrictions include:

  • As in pixel shaders, if multielement textures are supported, D3DSAMP_ELEMENTINDEX is used to figure out which element to sample from.
  • The state D3DSAMP_DMAPOFFSET is ignored for these stages.
  • Use IDirect3D9::CheckDeviceFormat with D3DUSAGE_QUERY_VERTEXTEXTURE" to query a texture to see if it can be used as a vertex texture.
  • VertexTextureFilterCaps indicates what kind of filters are allowed at the vertex texture samplers. D3DPTFILTERCAPS_MINFANISOTROPIC and D3DPTFILTERCAPS_MAGFANISOTROPIC are disallowed.

Sampling Stage Registers

A sampling stage register identifies a sampling unit that can be used in texture load statements. A sampling unit corresponds to the texture sampling stage, encapsulating the sampling-specific state provided in IDirect3DDevice9::SetSamplerState.

Each sampler uniquely identifies a single texture surface that is set to the corresponding sampler using IDirect3DDevice9::SetTexture. However, the same texture surface can be set at multiple samplers.

At draw time, a texture cannot be simultaneously set as a render target and a texture at a stage.

Because vs_3_0 supports four samplers, up to four texture surfaces can be read from in a single shader pass. A sampler register might appear only as an argument in the texture load statement: texldl.

In vs_3_0, if you use a sampler, it must be declared at the beginning of the shader program, using the dcl_samplerType (as in ps_2_0).

Software Processing

This feature will be supported in software vertex processing. The specific filter types supported can be checked by calling IDirect3DDevice9::GetDeviceCaps and checking VertexTextureFilterCaps. All published texture formats will be supported as vertex textures in software vertex processing.

Applications can check if a particular texture format is supported in the software vertex processing mode by calling IDirect3D9::CheckDeviceFormat and providing (D3DVERTEXTEXTURESAMPLER | D3DUSAGE_SOFTWAREPROCESSING) as usage. All formats are supported for software vertex processing. The scratch pool is required for software vertex processing.

API Changes

// New define
#define D3DVERTEXTEXTURESAMPLER0 (D3DDMAPSAMPLER+1)
#define D3DVERTEXTEXTURESAMPLER1 (D3DDMAPSAMPLER+2)
#define D3DVERTEXTEXTURESAMPLER2 (D3DDMAPSAMPLER+3)
#define D3DVERTEXTEXTURESAMPLER3 (D3DDMAPSAMPLER+4)

#define D3DVERTEXTEXTURESAMPLER  (0x00100000L)

// New caps field in D3DCAPS9
DWORD VertexTextureFilterCaps;


Effects
Microsoft DirectX 9.0 SDK Update (October 2004)

Effects

A Microsoft DirectX effect enables the integration of vertex and pixel shaders with pipeline state to render objects. Effects are the next logical step in combining shaders to produce unique render conditions.

Effects also provide a convenient way to write shaders for different hardware versions. Because different video cards support different functionalities, an application can write several techniques that will run on a variety of devices. This way, if the application is running on the latest and greatest hardware, the application can run the most sophisticated effect technique. On the other hand, less sophisticated effect techniques can automatically be chosen to run on less-expensive or less-capable hardware.

An effect can replace the vertex processing and part of the pixel processing performed by the graphics pipeline. An example of an effect that uses a vertex shader and a pixel shader is in the BasicHLSL Sample.

For more information about effects, see these topics:

  • Writing An Effect
  • Using An Effect
  • Using Standard Semantics and Standard Annotations

Effects and the 3-D Pipeline

A block diagram of the pipeline looks like this:

The pipeline transforms input data into output pixels that fill the frame buffer. The input data comes from objects that are made up of vertices in object space, or higher-order surfaces created from N-patches, rectangle patches, and triangle patches. Once the input data has been tessellated, the pipeline performs vertex processing, primitive processing, and pixel processing before generating the final pixel colors.

Vertex and pixel processing can be performed by the fixed function pipeline, or can be implemented with programmable shaders. The input data tessellation, primitive processing, and data outputs are controlled by pipeline state. All this can be integrated into an effect. An effect sets the state that controls how the pipeline functions. Effects manage programmable shaders as well as fixed function state.

Effects can save and restore state, leaving the device in the same state as before the effect was run. The types of state that an effect can manage include:

  • Shader state. This includes creating and deleting shaders, setting shader constants, setting shader state, and rendering with shaders.
  • Texture and sampler state. This includes specifying texture files, initializing texture stages, creating sampler objects, and setting sampler state.
  • Other pipeline state. This includes states for setting transformations, lighting, materials, and rendering options. These can be global or local variables. The variables can be set by either the effect itself or by the application.

Effects contain multiple rendering options called techniques. Each technique encapsulates global variables, pipeline state, texture and sampler state, and shader state. A single style is implemented in a rendering pass. One or more passes can be encapsulated in a technique. All of the passes and techniques can be validated to see if the effect code will run on the hardware device.

Effects Save and Restore State

Effects manage state. The word state is used very broadly here as it includes all kinds of information that the pipeline needs to specify the render conditions. This includes nearly all the functional areas of the pipeline.

Rendering options are controlled by techniques and passes. An application renders an effect by setting one active technique, and rendering one or more passes. All rendering in an effect is done within a matching pair of ID3DXEffect::Begin and ID3DXEffect::End calls. When ID3DXEffect::Begin is called, a stateblock is created and device state is saved (unless you specify otherwise). After a technique renders the passes that the application specifies to render, ID3DXEffect::End is called to end the active technique. The effect system responds by automatically restoring the pipeline state that was captured in the state block (unless you choose to disable this save and restore functionality).

When programming multiple-pass rendering sequences, each of which requires its own state setup, effects can reduce the housekeeping required for tracking state changes. To see more information about the states that can be saved and restored by effects, see Effect States.

Effects Can Share Parameters

Effect parameters are all the non-static variables declared in an effect. This can include global variables and annotations. Effect parameters can be shared between different effects by declaring parameters with the shared keyword and then creating the effect with an effect pool.

Cloned effects use the same effect pool as the effect from which they are cloned. Cloning an effect makes an exact copy of an effect, including global variables, techniques, passes, and annotations.


Writing an Effect
Microsoft DirectX 9.0 SDK Update (October 2004)

Writing an Effect

Writing an effect requires that you understand effect syntax, and generate the required state information. You can add shader state, texture and sampler state, and all of the pipeline state that your application requires in an effect.

The effect syntax is detailed in the Effect Format. An effect is typically encapsulated into an effect file (.fx) but could also be written as a text string in an application.

Effect Example

Effects contain three types of state: shader state, texture and sampler state, and pipeline state. Here is an example of an effect from the BasicHLSL Sample:

// Global variables
float4 g_MaterialAmbientColor;      // Material's ambient color
float4 g_MaterialDiffuseColor;      // Material's diffuse color
int g_nNumLights;

float3 g_LightDir[3];               // Light's direction in world space
float4 g_LightDiffuse[3];           // Light's diffuse color
float4 g_LightAmbient;              // Light's ambient color

texture g_MeshTexture;              // Color texture for mesh

float    g_fTime;                   // App's time in seconds
float4x4 g_mWorld;                  // World matrix for object
float4x4 g_mWorldViewProjection;    // World * View * Projection matrix

// Texture samplers
sampler MeshTextureSampler =
sampler_state
{
    Texture = ;
    MipFilter = LINEAR;
    MinFilter = LINEAR;
    MagFilter = LINEAR;
};

struct VS_OUTPUT
{
    float4 Position   : POSITION;   // vertex position
    float2 TextureUV  : TEXCOORD0;  // vertex texture coords
    float4 Diffuse    : COLOR0;     // vertex diffuse color
};

VS_OUTPUT RenderSceneVS( float4 vPos : POSITION,
                         float3 vNormal : NORMAL,
                         float2 vTexCoord0 : TEXCOORD0,
                         uniform int nNumLights,
                         uniform bool bTexture,
                         uniform bool bAnimate )
{
    VS_OUTPUT Output;
    float3 vNormalWorldSpace;

    float4 vAnimatedPos = vPos;

    // Animation the vertex based on time and the vertex's object space position
    if( bAnimate )
        vAnimatedPos += float4(vNormal, 0) * (sin(g_fTime+5.5)+0.5)*5;

    // Transform the position from object space to homogeneous projection space
    Output.Position = mul(vAnimatedPos, g_mWorldViewProjection);

    // Transform the normal from object space to world space
    vNormalWorldSpace = normalize(mul(vNormal, (float3x3)g_mWorld));

    // Compute simple directional lighting equation
    float3 vTotalLightDiffuse = float3(0,0,0);
    for(int i=0; i < nNumLights; i++ )
        vTotalLightDiffuse += g_LightDiffuse[i] * max(0,dot(vNormalWorldSpace, g_LightDir[i]));

    Output.Diffuse.rgb = g_MaterialDiffuseColor * vTotalLightDiffuse +
                         g_MaterialAmbientColor * g_LightAmbient;
    Output.Diffuse.a = 1.0f;

    // Just copy the texture coordinate through
    if( bTexture )
        Output.TextureUV = vTexCoord0;
    else
        Output.TextureUV = 0;

    return Output;
}

struct PS_OUTPUT
{
    float4 RGBColor : COLOR0;  // Pixel color
};

PS_OUTPUT RenderScenePS( VS_OUTPUT In,
                         uniform bool bTexture )
{
    PS_OUTPUT Output;

    // Lookup mesh texture and modulate it with diffuse
    if( bTexture )
        Output.RGBColor = tex2D(MeshTextureSampler, In.TextureUV) * In.Diffuse;
    else
        Output.RGBColor = In.Diffuse;

    return Output;
}

technique RenderSceneWithTexture1Light
{
    pass P0
    {
        VertexShader = compile vs_1_1 RenderSceneVS( 1, true, true );
        PixelShader  = compile ps_1_1 RenderScenePS( true );
    }
}

This effect contains:

  • The shader state, which is all of the state associated with the vertex shader and pixel shader. This is defined by the vertex and pixel shader functions, any global variables they require, and their input and output data structures, all of which are listed here:

    struct VS_OUTPUT
{  ...  };

VS_OUTPUT RenderSceneVS( float4 vPos : POSITION,
                         ...
{  ...  }

struct PS_OUTPUT
{  ...  };

PS_OUTPUT RenderScenePS( VS_OUTPUT In,
                         uniform bool bTexture )
{  ...  }

  • Texture and sampler state, which are the the global variables for the texture object and the sampler object:

    texture g_MeshTexture;              // Color texture for mesh

sampler MeshTextureSampler =
sampler_state
{
   ...
};

  • The other effect state. There is no other effect state explicitly used in this example. If there were, it would be the technique inside of the pass to which it applied:

    technique RenderSceneWithTexture1Light
{
    pass P0
    {
        // Any other effect state can be set here.

        VertexShader = compile vs_1_1 RenderSceneVS( 1, true, true );
        PixelShader  = compile ps_1_1 RenderScenePS( true );
    }
}

Effects Contain One or More Techniques and Passes

Effect rendering options are controlled by adding techniques and passes.

Effects can be created with additional passes to facilitate more complex rendering effects. A technique supports an arbitrary number of passes:

technique T0
{
    pass P0
    { ... }

    pass P1
    { ... }

    ...

    pass Pn
    { ... }
}

Effects can also be created with an arbitrary number of techniques.

technique T0
{
    pass P0
    { ... }
}

technique T1
{
    pass P0
    { ... }

    pass P1
    { ... }
}

...

technique Tn
{
    pass P0
    { ... }
}

technique TVertexShaderOnly
{
    pass P0
    {
        VertexShader =
        asm
        {
         // assembly-language shader code goes here
         ...
        };
    }
}

The techniques and passes can be given arbitrary names.


Using an Effect
Microsoft DirectX 9.0 SDK Update (October 2004)

Using an Effect

This page will show you how to generate and use an effect. The topics covered include how to:

  • Create an Effect
  • Render an Effect
  • Use Semantics to Find Effect Parameters
  • Use Handles to Get and Set Parameters Efficiently
  • Add Parameter Information with Annotations
  • Share Effect Parameters
  • Compile an Effect Offline
  • Improve Performance with Preshaders
  • Use Parameter Blocks to Manage Effect Parameters

Create an Effect

Here is an example of creating an effect taken from the BasicHLSL Sample. The effect creation code for creating a debug shader is from OnCreateDevice:

ID3DXEffect* g_pEffect = NULL;
DWORD dwShaderFlags = 0;

    dwShaderFlags |= D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT;
    dwShaderFlags |= D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT;
    dwShaderFlags |= D3DXSHADER_NO_PRESHADER;

    // Read the D3DX effect file
    WCHAR str[MAX_PATH];
    DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"BasicHLSL.fx" );

    D3DXCreateEffectFromFile(
        pd3dDevice,
        str,
        NULL, // CONST D3DXMACRO* pDefines,
        NULL, // LPD3DXINCLUDE pInclude,
        dwShaderFlags,
        &g_pEffect,
        NULL );

This function takes these arguments:

  • The device.
  • The file name of the effect file.
  • A pointer to a NULL-terminated list of #defines, to be used while parsing the shader.
  • An optional pointer to a user-written include handler. The handler is called by the processor whenever it needs to resolve a #include.
  • A shader compile flag that gives the compiler hints about how the shader will be used. The options include:
    • Skipping validation, if known good shaders are being compiled.
    • Skipping optimization (sometimes used when optimizations make debugging harder).
    • Requesting debug information to be included in the shader so it can be debugged.
  • The effect pool. If more than one effect uses the same memory pool pointer, the global variables in the effects are shared with each other. If there is no need to share effect variables, the memory pool can be set to NULL.
  • A pointer to the new effect.
  • A pointer to a buffer to which validation errors can be sent. In this example, the parameter was set to NULL and not used.

Render an Effect

The sequence of calls for applying effect state to a device is:

  • ID3DXEffect::Begin sets the active technique.
  • ID3DXEffect::BeginPass sets the active pass.
  • ID3DXEffect::CommitChanges updates changes to any set calls in the pass. This should be called before any draw call.
  • ID3DXEffect::EndPass ends a pass.
  • ID3DXEffect::End ends the active technique.

Effect render code is also simpler than the corresponding render code without an effect. Here's the render code with an effect:

// Apply the technique contained in the effect
g_pEffect->Begin(&cPasses, 0);

for (iPass = 0; iPass < cPasses; iPass++)
{
    g_pEffect->BeginPass(iPass);

    // Only call CommitChanges if any state changes have happened
    // after BeginPass is called
    g_pEffect->CommitChanges();

    // Render the mesh with the applied technique
    g_pMesh->DrawSubset(0);

    g_pEffect->EndPass();
}
g_pEffect->End();

The render loop consists of querying the effect to see how many passes it contains, and then calling all the passes for a technique. The render loop could be expanded to call multiple techniques, each with multiple passes.

Use Semantics to Find Effect Parameters

A semantic is an identifier that is attached to an effect parameter to allow an application to search for the parameter. A parameter can have at most one semantic. The semantic is located following a colon (:) after the parameter name. For instance:

float4x4 matWorldViewProj : WORLDVIEWPROJ;

If you declared the effect global variable without using a semantic, it would look like this instead:

float4x4 matWorldViewProj;

The effect interface can use a semantic to get a handle to a particular effect parameter. For instance, the following returns the handle of the matrix:

D3DHANDLE handle =
    m_pEffect->GetParameterBySemantic(NULL, "WORLDVIEWPROJ");

In addition to searching by semantic name, the effect interface has many other methods to search for parameters.

Use Handles to Get and Set Parameters Efficiently

Handles provide an efficient means for referencing effect parameters, techniques, passes, and annotations with an effect. Handles (which are of type D3DXHANDLE) are string pointers. The handles that are passed into functions such as GetParameterxxx or GetAnnotationxxx can be in one of three forms:

  • A handle returned by a function such as GetParameterxxx.
  • A string containing the name of the parameter, technique, pass, or annotation.
  • A handle set to NULL.

This example returns a handle to the parameter that has the WORLDVIEWPROJ semantic attached to it:

D3DHANDLE handle =
    m_pEffect->GetParameterBySemantic(NULL, "WORLDVIEWPROJ");

Add Parameter Information with Annotations

Annotations are user-specific data that can be attached to any technique, pass, or parameter. An annotation is a flexible way to add information to individual parameters. The information can be read back and used any way the application chooses. An annotation can be of any data type and can be added dynamically. Annotation declarations are delimited by angle brackets. An annotation contains:

  • A data type.
  • A variable name.
  • An equals sign (=).
  • The data value.
  • A ending semicolon (;).

For instance, both of the previous examples in this paper contain this annotation:

texture Tex0 < string name = "tiger.bmp"; >;

The annotation is attached to the texture object and specifies the texture file that should be used to initialize the texture object. The annotation does not initialize the texture object, it is simply a piece of user information that is attached to the variable. An application can read the annotation with either ID3DXEffect::GetAnnotation or ID3DXEffect::GetAnnotationByName to return the string. Annotations can also be added by the application.

Each annotation:

  • Must be either numeric or strings.
  • Must always be initialized with a default value.
  • Can be associated with Techniques and Passes and top-level Parameters.
  • Can be written to and read from with either ID3DXEffect or ID3DXEffectCompiler.
  • Can be added with ID3DXEffect.
  • Cannot be referenced inside the effect.
  • Cannot have sub-semantics or sub-annotations.

Share Effect Parameters

Effect parameters are all the non-static variables declared in an effect. This can include global variables and annotations. Effect parameters can be shared between different effects by declaring parameters with the "shared" keyword and then creating the effect with an effect pool.

An effect pool contains shared effect parameters. The pool is created by calling D3DXCreateEffectPool, which returns an ID3DXEffectPool interface. The interface can be supplied as an input to any of the D3DXCreateEffectxxx functions when an effect is created. For a parameter to be shared across multiple effects, the parameter must have the same name, type, and semantic in each of the shared effects.

ID3DXEffectPool* g_pEffectPool = NULL;   // Effect pool for sharing parameters

    D3DXCreateEffectPool( &g_pEffectPool );

Effects that share parameters must use the same device. This is enforced to prevent the sharing of device-dependent parameters (such as shaders or textures) across different devices. Parameters are deleted from the pool whenever the effects that contain the shared parameters are released. If sharing parameters is not necessary, supply NULL for the effect pool when an effect is created.

Cloned effects use the same effect pool as the effect from which they are cloned. Cloning an effect makes an exact copy of an effect, including global variables, techniques, passes, and annotations.

Compile an Effect Offline

You can compile an effect at run time with D3DXCreateEffect, or you can compile an effect offline using the command line compiler Effect Command Line Compile. The effect in the CompiledEffect Sample contains a vertex shader, a pixel shader, and one technique:

// File: CompiledEffect.fx

// Global variables
float4 g_MaterialAmbientColor;	// Material's ambient color
...

// Texture samplers
sampler RenderTargetSampler =
   ...

// Type: Vertex shader
VS_OUTPUT RenderSceneVS( float4 vPos : POSITION,
                         float3 vNormal : NORMAL,
                         float2 vTexCoord0 : TEXCOORD0 )
{
   ...
};

// Type: Pixel shader
PS_OUTPUT RenderScenePS( VS_OUTPUT In )
{
   ...
}

// Type: Technique
technique RenderScene
{
    pass P0
    {
        ZENABLE = true;
        VertexShader = compile vs_1_1 RenderSceneVS();
        PixelShader  = compile ps_1_1 RenderScenePS();
    }
}

Using fxc to compile the shader for vs_1_1 generated the following assembly shader instructions:

//
// Generated by Microsoft (R) D3DX9 Shader Compiler 4.09.02.1188
//
//   fxc /T vs_1_1 /E RenderSceneVS /Fc CompiledEffect.txt CompiledEffect.fx
//
//
// Parameters:
//
//   float4 g_LightAmbient;
//   float4 g_LightDiffuse;
//   float3 g_LightDir;
//   float4 g_MaterialAmbientColor;
//   float4 g_MaterialDiffuseColor;
//   float g_fTime;
//   float4x4 g_mWorld;
//   float4x4 g_mWorldViewProjection;
//
//
// Registers:
//
//   Name                   Reg   Size
//   ---------------------- ----- ----
//   g_mWorldViewProjection c0       4
//   g_mWorld               c4       3
//   g_MaterialAmbientColor c7       1
//   g_MaterialDiffuseColor c8       1
//   g_LightDir             c9       1
//   g_LightAmbient         c10      1
//   g_LightDiffuse         c11      1
//   g_fTime                c12      1
//
//
// Default values:
//
//   g_LightDir
//     c9   = { 0.57735, 0.57735, 0.57735, 0 };
//
//   g_LightAmbient
//     c10  = { 1, 1, 1, 1 };
//
//   g_LightDiffuse
//     c11  = { 1, 1, 1, 1 };
//

    vs_1_1
    def c13, 0.159154937, 0.25, 6.28318548, -3.14159274
    def c14, -2.52398507e-007, 2.47609005e-005, -0.00138883968, 0.0416666418
    def c15, -0.5, 1, 0.5, 0
    dcl_position v0
    dcl_normal v1
    dcl_texcoord v2
    mov r0.w, c12.x
    mad r0.w, r0.w, c13.x, c13.y
    expp r3.y, r0.w
    mov r0.w, r3.y
    mad r0.w, r0.w, c13.z, c13.w
    mul r0.w, r0.w, r0.w
    mad r1.w, r0.w, c14.x, c14.y
    mad r1.w, r0.w, r1.w, c14.z
    mad r1.w, r0.w, r1.w, c14.w
    mad r1.w, r0.w, r1.w, c15.x
    mad r0.w, r0.w, r1.w, c15.y
    mul r0.w, r0.w, v0.x
    mul r0.x, r0.w, c15.z
    dp3 r1.x, v1, c4
    dp3 r1.y, v1, c5
    dp3 r1.z, v1, c6
    mov r0.yzw, c15.w
    dp3 r2.x, r1, r1
    add r0, r0, v0
    rsq r1.w, r2.x
    dp4 oPos.x, r0, c0
    mul r1.xyz, r1, r1.w
    dp4 oPos.y, r0, c1
    dp3 r1.x, r1, c9
    dp4 oPos.z, r0, c2
    max r1.w, r1.x, c15.w
    mov r1.xyz, c8
    mul r1.xyz, r1, c11
    mov r2.xyz, c7
    mul r2.xyz, r2, c10
    dp4 oPos.w, r0, c3
    mad oD0.xyz, r1, r1.w, r2
    mov oD0.w, c15.y
    mov oT0.xy, v2

// approximately 34 instruction slots used

Improve Performance with Preshaders

A preshader is a technique for increasing shader efficiency by pre-calculating constant shader expressions. The effect compiler automatically pulls out shader computations from the body of a shader and executes them on the CPU prior to the shader running. Consequently, preshaders only work with effects. For instance, these two expressions can be evaluated outside of the shader before it runs.

mul(World,mul(View, Projection));
sin(time)

Shader computations that can be moved are those associated with uniform parameters; that is, the computations do not change for each vertex or pixel. If you are using effects, the effect compiler automatically generates and runs a preshader for you; there are no flags to enable. Preshaders can reduce the number of instructions per shader and can also reduce the number of constant registers a shader consumes.

Think of the effect compiler as a sort of multi-processor compiler because it compiles shader code for two types of processors: a CPU and a graphics processing unit (GPU). In addition, the effect compiler is designed to move code from the GPU to the CPU and therefore improve shader performance. This is very similar to pulling a static expression out of a loop. A shader that transforms position from world space to projection space, and copies texture coordinates would look like this in high-level shader language (HLSL):

float4x4 g_mWorldViewProjection;    // World * View * Projection matrix
float4x4 g_mWorldInverse;           // Inverse World matrix
float3 g_LightDir;                  // Light direction in world space
float4 g_LightDiffuse;              // Diffuse color of the light

struct VS_OUTPUT
{
    float4 Position   : POSITION;   // vertex position
    float2 TextureUV  : TEXCOORD0;  // vertex texture coords
    float4 Diffuse    : COLOR0;     // vertex diffuse color
};

VS_OUTPUT RenderSceneVS( float4 vPos : POSITION,
                         float3 vNormal : NORMAL,
                         float2 vTexCoord0 : TEXCOORD0)
{
    VS_OUTPUT Output;

    // Transform the position from object space to projection space
    Output.Position = mul(vPos, g_mWorldViewProjection);

    // Transform the light from world space to object space
    float3 vLightObjectSpace = normalize(mul(g_LightDir, (float3x3)g_mWorldInverse));

    // N dot L lighting
    Output.Diffuse = max(0,dot(vNormal, vLightObjectSpace));

    // Copy the texture coordinate
    Output.TextureUV = vTexCoord0;

    return Output;
}

technique RenderVS
{
    pass P0
    {
        VertexShader = compile vs_1_1 RenderSceneVS();
    }
}

Using fxc to compile the shader for vs_1_1 generates the following assembly instructions:

//
//
// Parameters:
//
//   float3 g_LightDir;
//   float4x4 g_mWorldInverse;
//   float4x4 g_mWorldViewProjection;
//
//
// Registers:
//
//   Name                   Reg   Size
//   ---------------------- ----- ----
//   g_mWorldViewProjection c0       4
//   g_mWorldInverse        c4       3
//   g_LightDir             c7       1
//

    vs_1_1
    def c8, 0, 0, 0, 0
    dcl_position v0
    dcl_normal v1
    dcl_texcoord v2
    mov r1.xyz, c7
    dp3 r0.x, r1, c4
    dp3 r0.y, r1, c5
    dp3 r0.z, r1, c6
    dp4 oPos.x, v0, c0
    dp3 r1.x, r0, r0
    dp4 oPos.y, v0, c1
    rsq r0.w, r1.x
    dp4 oPos.z, v0, c2
    mul r0.xyz, r0, r0.w
    dp4 oPos.w, v0, c3
    dp3 r0.x, v1, r0
    max oD0, r0.x, c8.x
    mov oT0.xy, v2

// approximately 14 instruction slots used, 9 constant registers used

This uses up approximately fourteen instruction slots and consumes nin constant registers. With a preshader, the compiler moves the static expressions out of the shader and into the preshader. The same shader would look like this with a preshader:

// Shader Instructions
    vs_1_1
    def c8, 0, 0, 0, 0
    dcl_position v0
    dcl_normal v1
    dcl_texcoord v2
    mov r1.xyz, c7
                              // Preshader instructions
                              dp3 r0.x, r1, c4
                              dp3 r0.y, r1, c5
                              dp3 r0.z, r1, c6

    dp4 oPos.x, v0, c0
    dp3 r1.x, r0, r0
    dp4 oPos.y, v0, c1
    rsq r0.w, r1.x
    dp4 oPos.z, v0, c2
    mul r0.xyz, r0, r0.w
    dp4 oPos.w, v0, c3
    dp3 r0.x, v1, r0
    max oD0, r0.x, c8.x
    mov oT0.xy, v2

// approximately 11 instruction slots used, 3 fewer constant registers used

An effect executes a preshader just before executing a shader. The result is the same functionality with increased shader performance because the number of instructions that need to be executed (for each vertex or pixel depending on the type of shader) has been reduced. In addition, fewer constant registers are consumed by the shader as a result of the static expressions being moved to the preshader. This means that shaders previously limited by the number of constant registers they required may now compile because they require fewer constant registers. It is reasonable to expect a 5 percent and a 20 percent performance improvement from preshaders.

Use Parameter Blocks to Manage Effect Parameters

Parameter blocks are blocks of effect state changes. A parameter block can record state changes, so that they can be applied later on with a single call. Create a parameter block by calling ID3DXEffect::BeginParameterBlock:

    m_pEffect->SetTechnique( "RenderScene" );

    m_pEffect->BeginParameterBlock();
    D3DXVECTOR4 v4( Diffuse.r, Diffuse.g, Diffuse.b, Diffuse.a );
    m_pEffect->SetVector( "g_vDiffuse", &v4 );
    m_pEffect->SetFloat( "g_fReflectivity", fReflectivity );
    m_pEffect->SetFloat( "g_fAnimSpeed", fAnimSpeed );
    m_pEffect->SetFloat( "g_fSizeMul", fSize );
    m_hParameters = m_pEffect->EndParameterBlock();

The parameter block saves four changes applied by the application programming interface (API) calls. Calling ID3DXEffect::BeginParameterBlock starts recording the state changes. ID3DXEffect::EndParameterBlock stops adding the changes to the parameter block and returns a handle. The handle will be used when calling ID3DXEffect::ApplyParameterBlock.

In the EffectParam Sample, the parameter block is applied in the render sequence:

CObj g_aObj[NUM_OBJS];       // Object instances

    if( SUCCEEDED( pd3dDevice->BeginScene() ) )
    {
        // Set the shared parameters using the first mesh's effect.

        // Render the mesh objects
        for( int i = 0; i < NUM_OBJS; ++i )
        {
            ID3DXEffect *pEffect = g_aObj[i].m_pEffect;

            // Apply the parameters
            pEffect->ApplyParameterBlock( g_aObj[i].m_hParameters );

            ...

            pEffect->Begin( &cPasses, 0 );
            for( iPass = 0; iPass < cPasses; iPass++ )
            {
              ...
            }
            pEffect->End();
        }

        ...
        pd3dDevice->EndScene();
    }

The parameter block sets the value of all four of the state changes just before ID3DXEffect::Begin is called. Parameter blocks are a handy way to set multiple state changes with a single API call.


Using Standard Semantics and Standard Annotations
Microsoft DirectX 9.0 SDK Update (October 2004)

Using Standard Semantics and Standard Annotations

Standardized semantics and annotations make it possible for an application to understand the intention behind an effect parameter. This is because semantics and annotations specify additional usage information about a parameter. Parameters that an effect author doesn't need (or want) an application to understand do not need to attach semantics or annotations (because they are optional). The example below will help illustrate cases where it is highly desirable to use standardized usage information.

Parameters that are meant to be shared between the effect and the application must somehow indicate their usage to the application. For instance, almost all effects require the current transformation matrices for use in the vertex shader. Unless the application was specifically written to work with a particular effect file, there's no way for the application to know the names of the parameters which hold the transformation matrices (or whether those parameters even exist).

Instead of creating naming guidelines for parameters, Microsoft has created a set of optional standard semantics and annotations which can be attached to effect parameters. Any effect which implements these standard semantics and annotations can be read by an application.

Attaching a Standard Semantic

For instance, an effect parameter which the application is expected to fill with the current world transformation matrix could use a semantic like this:

float4x4 MyWorldMatrix : World;

The world semantic is a standard semantic which has been defined as a 4x4 floating-point matrix which contains the world transformation (see Standard Semantics Reference). Attaching this standard semantic to an effect parameter makes it possible for an application to understand the intent of this effect parameter.

Attaching a Standard Annotation

Some parameters require additional information to specify the parameter usage. For instance, this parameter uses the diffuse semantic which identifies it as a diffuse color. But what is this the diffuse color of? The annotation can identify the usage as shown here:

float4 MyLightDiffuseColor : Diffuse
<
    string Object = "Light";
>;

An annotation is attached to a parameter inside of a pair of angle brackets. This annotation has a single string which identifies the parameter usage as a light. This means that the diffuse color parameter is the diffuse color of a light (whose index is 0 because the index is not specified). This annotation used a single string, but annotations can use several strings to identify different types of information.

For instance, here's an example of a parameter that is connected to a user interface (UI) control:

float4 MyTweakableLightDiffuseColor : Diffuse
<
    string Object = "Light";

    string UIWidget = "Color";
    float4 UIMin = float4(0.2, 0.2, 0.2, 1.0);
    float4 UIMax = float4(1.0, 1.0, 1.0, 1.0);
    string UIName = "The diffuse color of the light";
>;

This example has several annotations. They are attached to a diffuse light color, which is intended to be interactively adjusted by a user. The annotations define the following:

  • UIWidget identifies a type of control or widget for controlling the parameter value.
  • UIMin identifies the minimum value of the control.
  • UIMax identifies the maximum value of the control.
  • UIName is a help string that can be displayed over the control if the user hovers a mouse over the control to cause it to pop up.

This example highlights the use of semantics and annotations to identify the parameters necessary for an application to connect this parameter to a UI control. This means that any effect that chooses to implement standard annotations and semantics can now be read by an application that knows how to interpret them. This means that shader development and application development can take advantage of each other even if both are written at different times by different authors.


Advanced Topics
Microsoft DirectX 9.0 SDK Update (October 2004)

Advanced Topics

Microsoft Direct3D provides a powerful set of tools that you can use to increase the realistic appearance of a 3-D scene. Once you have mastered the topics in Getting Started, you can move on to advanced topics like antialiasing, working with the frame buffer, querying for resource status, and profiling your application.

The following topics contain more information:

  • Vertex Pipeline
  • Pixel Pipeline
  • Frame Buffer
  • Precomputed Radiance Transfer
  • HDR Lighting
  • Accurately Profiling Direct3D API Calls
  • Queries
  • Drawing Multiple Instances of Geometry Efficiently


Vertex Pipeline
Microsoft DirectX 9.0 SDK Update (October 2004)

Vertex Pipeline

This is a list of advanced topics that are implemented by vertex processing.

  • Tessellation
  • Displacement Mapping
  • Geometry Blending
  • Higher-Order Primitives
  • Point Sprites
  • Matrix Stacks


Tessellation
Microsoft DirectX 9.0 SDK Update (October 2004)

Tessellation

Tessellator Unit

The tessellator unit has been enhanced. You can now use it to:

  • Perform adaptive tessellation of all higher-order primitives.
  • Look up per-vertex displacement values from a displacement map and pass them on to a vertex shader.
  • Support rectangle-patch tessellation. This is specified through a vertex declaration using D3DDECLMETHOD_PARTIALU or D3DDECLMETHOD_PARTIALV. If a vertex declaration containing these methods is used to draw a triangle patch, IDirect3DDevice9::DrawTriPatch will fail. For more information about vertex declarations, see D3DVERTEXELEMENT9.

In Microsoft DirectX 8.x, what was called ORDER was really the degree. In DirectX 9.0, the degree is now specified by D3DDEGREETYPE.

 // This used to be D3DORDERTYPE and D3DORDER*
 typedef enum _D3DDEGREETYPE
 {
 D3DDEGREE_LINEAR = 1,
 D3DDEGREE_QUADRATIC = 2,
 D3DDEGREE_CUBIC = 3,
 D3DDEGREE_QUINTIC = 5,
 D3DDEGREE_FORCE_DWORD = 0x7fffffff,
 } D3DDEGREETYPE;

The change in degree type affected two other structures.

typedef struct _D3DRECTPATCH_INFO
 {
 UINT StartVertexOffsetWidth;
 UINT StartVertexOffsetHeight;
 UINT Width;
 UINT Height;
 UINT Stride;
 D3DBASISTYPE Basis;
 D3DDEGREETYPE Degree;
 } D3DRECTPATCH_INFO;

 typedef struct _D3DTRIPATCH_INFO
 {
 UINT StartVertexOffset;
 UINT NumVertices;
 D3DBASISTYPE Basis;
 D3DDEGREETYPE Degree;
 } D3DTRIPATCH_INFO;

Drivers need to fix compilation errors that will result from this change when they compile with the new headers. No functionality has to be changed.

Adaptive Tessellation

Adaptive tessellation can be applied to high-order primitives including N-patches, rectangle patches, and triangle patches. This feature is enabled by the D3DRS_ENABLEADAPTIVETESSELLATION and adaptively tessellates a patch, based on the depth value of the control vertex in eye space.

The z-coordinates (Zi) of control vertices (Vi), which are transformed into eye space (Zieye) by performing a dot product with a 4-vector, are used as the depth values. The 4-D vector (Mdm) is specified by the application using four render states (D3DRS_ADAPTIVETESS_X, D3DRS_ADAPTIVETESS_Y, D3DRS_ADAPTIVETESS_Z, and D3DRS_ADAPTIVETESS_W). This 4-vector could be the third column of the concatenated world and view matrices. It also could be used to apply a scale to Zieye.

The function to compute a tessellation level Ti from Zieye is assumed to be (MaxTessellationLevel/Zieye), which means that the MaxTessellationLevel is the tessellation level at Z = 1 in eye space. The MaxTessellationLevel is equal to a value set by IDirect3DDevice9::SetNPatchMode for N-patches and, for RT-patches, it is equal to pNumSegs. The tessellation level is then clamped to values, defined by the two additional render states D3DRS_MINTESSELLATIONLEVEL and D3DRS_MAXTESSELLATIONLEVEL, which define the minimum and maximum tessellation levels to be clamped to. The Ti's for each vertex along an edge of a patch are averaged to obtain a tessellation level for that edge. The algorithm for computing Ti for rectangle patches, triangle patches, and N-patches differs in what control vertices are used to compute the tessellation level.

For the rectangle patches with a B-spline basis, the four outermost control vertices are used. For example, with D3DORDER_CUBIC order: vertices (1,1) and (1,width-2) are used with pNumSegs[0], vertices (1,width-2) and (height-2,height-2) are used with pNumSegs[1], vertices (height-2,width-2) and (1,width-2) are used with pNumSegs[2], and vertices (2,1) and (1,1) are used with pNumSegs[3].

For the triangle patches, the corner patch vertices are used. With D3DORDER_CUBIC order: vertices (0) and (9) are used with pNumSegs[0], vertices (9) and (6) are used with pNumSegs[1] and vertices (6) and (0) are used with pNumSegs[3].

For N-patches the triangle vertices are used.

For the rectangle and triangle patches with a Bezier basis, the corner-control vertices are used.

Per-vertex tessellation rate control. An application can optionally supply a single positive floating-point value per vertex, which can be used to control the rate of tessellation. This is supplied using the D3DDECLUSAGE_TESSFACTOR, for which usage index must be 0 and input type must be D3DDECLTYPE_FLOAT1. This is multiplied to the per-vertex tessellation level.

Math

The tessellation level (Te) for an edge e, represented by two control vertices (Ve1, Ve2), is computed as shown below :

Vertex Vi: (Xi, Yi, Zi, TFactori (optional)).
Ze1eye = Ve1 . Mdm
Ze2eye = Ve2 . Mdm
Te1 = MaxTessellationLevel * TFactore1 / Ze1eye
Te2 = MaxTessellationLevel * TFactore2 / Ze2eye
Te = ( Te1 + Te2 ) / 2;
if Te > D3DRS_MAXTESSELLATIONLEVEL || Te < 0, then Te = D3DRS_MAXTESSELLATIONLEVEL
if Te < D3DRS_MINTESSELLATIONLEVEL, then Te = D3DRS_MINTESSELLATIONLEVEL

When D3DRS_ENABLEADAPTIVETESSELLATION is TRUE, triangle primitives (triangle lists, fans, strips) are drawn as N-patches, IDirect3DDevice9::SetNPatchMode has set value less than 1.0.

API Changes

New render states:

 D3DRS_ENABLEADAPTIVETESSELLATION // BOOL
 D3DRS_MAXTESSELLATIONLEVEL       // Float
 D3DRS_MINTESSELLATIONLEVEL       // Float
 D3DRS_ADAPTIVETESS_X             // Float
 D3DRS_ADAPTIVETESS_Y             // Float
 D3DRS_ADAPTIVETESS_Z             // Float
 D3DRS_ADAPTIVETESS_W             // Float

 // D3DRS_MINTESSELLATIONLEVEL and D3DRS_MAXTESSELLATIONLEVEL
 // cannot be less than 1

And their default values:

D3DRS_MAXTESSELLATIONLEVEL = 1.0f
D3DRS_MINTESSELLATIONLEVEL = 1.0f
D3DRS_ADAPTIVETESS_X = 0.0f
D3DRS_ADAPTIVETESS_Y = 0.0f
D3DRS_ADAPTIVETESS_Z = 1.0f
D3DRS_ADAPTIVETESS_W = 0.0f
D3DRS_ENABLEADAPTIVETESSELLATION = FALSE

New hardware caps:

D3DDEVCAPS2_ADAPTIVETESSRTPATCH // Can adaptively tessellate RT-patches
D3DDEVCAPS2_ADAPTIVETESSNPATCH  // Can adaptively tessellate N-patches


Displacement Mapping
Microsoft DirectX 9.0 SDK Update (October 2004)

Displacement Mapping

Displacement maps are similar to texture maps but are accessed by the vertex engine.

Block Diagram

An additional sampler stage is present in the early part of the vertex pipe, which can sample a displacement map to provide vertex displacement data.

Tessellator block diagram

The displacement map sampler state can be set by the IDirect3DDevice9::SetSamplerState using stage number 256, which is a new stage number. The displacement map texture is set by IDirect3DDevice9::SetTexture.

The map can be presampled or not, which means that it can be ordered in a way that enables the lookup of the displacement values without filtering.

  • Displacement maps are analogous to texture maps but are accessed by the vertex engine.
  • An additional sampler stage is present in the early part of the vertex pipe that can sample a displacement map. This stage is accessed by the usual SetSamplerState application programming interface (API) but the stage number is D3DDMAPSAMPLER = 256.
  • The displacement map sampler state can be set by the SetSamplerState(D3DDMAPSAMPLER, ...) API.
  • The displacement map texture is set by the SetTexture(D3DDMAPSAMPLER, texture) API.
  • The map can be pre-sampled or not. This means that it can be ordered in a particular way that enables the lookup of the displacement values without filtering.
  • The changes in the declaration structure allow the specification of the texture coordinate used to look up the texture map. For example, Stream0, Offset, FLOAT2, LOOKUP, Displacement_value. This tells the tessellator to use the 2-D float vector in stream0 at a certain offset as a texture coordinate to look up the displacement map and associate the Displacement_value usage semantic to it. The vertex shader declaration would contain a line similar to {dcl_texture0, v0} indicating that the texture0 semantic is to be associated with the v0 input register. The displacement value looked up is copied into input register v0.
  • There is a special type of displacement mapping, when the texture map is pre-sampled. Sequential index of generated vertices is used as a texture coordinate to a texture map. For example, 0,0,(D3DDECLTYPE)0,D3DDECLMETHOD_LOOKUPPRESAMPLED, Usage, UsageIndex.
  • The output of the lookup is 4 floats.
  • Displacement mapping is supported only with N-patches.
  • Drivers need to ignore D3DDMAPSAMPLER in SetTextureStageState if they do not handle displacement maps.
  • D3DTEXF_ANISOTROPIC filter mode is not supported.
  • When D3DSAMP_MIPFILTER in the displacement map sampler is not D3DTEXF_NONE, the level of detail is computed as follows (Note that the adaptive tessellation state is used even if the D3DRS_ENABLEADAPTIVETESSELLATION is FALSE):

    Tmax = render state D3DRS_MAXTESSELLATIONLEVEL
  • Compute tessellation level Te for a vertex Vi: (Xi, Yi, Zi) the same way as described in the "Adaptive tessellation" section. Level of detail L = log2(Tmax) - log2 (Te).
  • Texture filtering and sampling operations follow the same rules as the pixel pipeline (level of detail (LOD) bias is applied, etc.).
  • Not all formats can be used as displacement maps but only those that support the D3DUSAGE_DMAP. The application can query that with the CheckDeviceFormat IDirect3D9::CheckDeviceFormat.
  • D3DUSAGE_DMAP must be specified in IDirect3DDevice9::CreateTexture to notify the driver that this texture is to be used as a displacement map.
  • D3DUSAGE_DMAP can only be used with textures. It cannot be used with cube maps or volumes.
  • Textures and render targets created with D3DUSAGE_DMAP can be set at regular sampler stages and as render targets.
  • The render states to set the wrap mode for the texture coordinates are ignored in displacement mapping. In general, there are no wrap modes for the tessellator engine.
  • A displacement map sampler has behavior identical to that of the pixel texture samplers. If a texture with less than four channels (like R32f) is looked up, the looked-up values go to the appropriate channels of the destination register (the vertex shader input register tagged with the _sample semantic), while the other channels default to (1, 1, 1). When looked up, D3DFMT_L8 gets broadcast into the R, G, B channels and A defaults to 1. The reference rasterizer has the full implementation details.

Pre-Sampled Displacement Mapping

  • New sampler state is introduced: D3DSAMP_DMAPOFFSET (DWORD) - offset (in vertices) in a pre-sampled displacement map.
  • New declaration method is introduced: D3DDECLMETHOD_LOOKUPPRESAMPLED.
  • Adaptive tessellation should be disabled.
  • Texture filter settings are ignored. Point sampling is done. The mip texture filter is assumed to be D3DTEXF_NONE. All other texture filter modes are assumed to be D3DTEXF_POINT.
  • Texture coordinates are computed as: U = (Index % TextureWidthInPixeles) / (float)(TextureWidthInPixeles) V = (Index / TextureWidthInPixeles) / (float)(TextureHeightInPixeles) where Index is a sequential index of generated vertices plus TSS[D3DSAMP_DMAPOFFSET]. The sequential index is set to zero at the start of each primitive and is increased after a vertex is generated.

These are the API changes that support displacement mapping.

  • A single channel format added, D3DFMT_L16.
  • A new usage flag, D3DUSAGE_DMAP.
  • A special texture stage, used to set a displacement map texture, D3DDMAPSAMPLER.
  • New hardware caps have been added, D3DDEVCAPS2_DMAPNPATCH and D3DDEVCAPS2_PRESAMPLEDDMAPNPATCH. See D3DDEVCAPS2.


Geometry Blending
Microsoft DirectX 9.0 SDK Update (October 2004)

Geometry Blending

Microsoft Direct3D enables an application to increase the realism of its scenes by rendering segmented polygonal objects—especially characters—that have smoothly blended joints. These effects are often referred to as skinning. The system achieves this effect by applying additional world transformation matrices to a single set of vertices to create multiple results, and then performing a linear blend between the resultant vertices to create a single set of geometry for rendering. The following image of a banana illustrates this.

Blended composite of two objects with banana texture

This image shows how you might imagine the geometry-blending process. In a single rendering call, the system takes the vertices for the banana, transforms them twice—once without modification, and once with a simple rotation—and blends the results to create a bent banana. The system blends the vertex position, as well as the vertex normal when lighting is enabled. Applications are not limited to two blending paths; Direct3D can blend geometry between as many as four world matrices, including the standard world matrix, D3DTS_WORLD.

Note

When lighting is enabled, vertex normals are transformed by a corresponding inverse world-view matrix, weighted in the same way as the vertex position computations. The system normalizes the resulting normal vector if the D3DRS_NORMALIZENORMALS render state is set to TRUE.

Without geometry blending, dynamic articulated models are often rendered in segments. For instance, consider a 3-D model of the human arm. In the simplest view, an arm has two parts: the upper arm which connects to the body, and the lower arm, which connects to the hand. The two are connected at the elbow, and the lower arm rotates at that point. An application that renders an arm might retain vertex data for the upper and lower arm, each with a separate world transformation matrix. The following code example illustrates this.

typedef struct _Arm
{
    VERTEX upper_arm_verts[200];
    D3DMATRIX matWorld_Upper;

    VERTEX lower_arm_verts[200];
    D3DMATRIX matWorld_Lower;
} ARM, *LPARM;

ARM MyArm; // This needs to be initialized.

To render the arm, two rendering calls are made, as shown in the following code.

// Render the upper arm.
d3dDevice->SetTransform( D3DTS_WORLD, &MyArm.matWorld_Upper );
d3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, numFaces );

// Render the lower arm, updating its world matrix to articulate
// the arm by pi/4 radians (45 degrees) at the elbow.
MyArm.matWorld_Lower = RotateMyArm(MyArm.matWorld, pi/4);
d3dDevice->SetTransform( D3DTS_WORLD, &MyArm.matWorld_Lower );
d3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, numFaces );

The following image is a banana, modified to use this technique.

Blended banana image

The differences between the blended geometry and the nonblended geometry are obvious. This example is somewhat extreme. In a real-world application, the joints of segmented models are designed so that seams are not as obvious. However, seams are visible at times, which presents constant challenges for model designers.

Geometry blending in Direct3D presents an alternative to the classic segmented-modeling scenario. However, the improved visual quality of segmented objects comes at the cost of the blending computations during rendering. To minimize the impact of these additional operations, the Direct3D geometry pipeline is optimized to blend geometry with the least possible overhead. Applications that intelligently use the geometry blending services offered by Direct3D can improve the realism of their characters while avoiding serious performance repercussions.

Blending Transform and Render States

The IDirect3DDevice9::SetTransform method recognizes the D3DTS_WORLD and D3DTS_WORLDn macros, which correspond to values that can be defined by the D3DTS_WORLDMATRIX macro. These macros are used to identify the matrices between which geometry will be blended.

The D3DRENDERSTATETYPE enumerated type includes the D3DRS_VERTEXBLEND render state to enable and control geometry blending. Valid values for this render state are defined by the D3DVERTEXBLENDFLAGS enumerated type. If geometry blending is enabled, the vertex format must include the appropriate number of blending weights.

Blending Weights

A blending weight, sometimes called a beta weight, controls the extent to which a given world matrix affects a vertex. Blending weights are floating-point values that range from 0.0 to 1.0, encoded in the vertex format, where a value of 0.0 means the vertex is not blended with that matrix, and 1.0 means that the vertex is affected in full by the matrix.

Geometry blending weights are encoded in the vertex format, appearing immediately after the position for each vertex, as described in Fixed Function FVF Codes. You communicate the number of blending weights in the vertex format by including one of the FVF constants in the vertex description that you provide to the rendering methods.

The system performs a linear blend between the weighted results of the blend matrices. The following is the complete blending formula.

Formula for linear blending, using world transformation matrices

In the preceding formula, vBlend is the output vertex, the v-elements are the vertices produced by the applied world matrix (D3DTS_WORLDn). The W elements are the corresponding weight values within the vertex format. A vertex blended between n matrices can have –1 blending weight values, one for each blending matrix, except the last. The system automatically generates the weight for the last world matrix so that the sum of all weights is 1.0, expressed in sigma notation here. This formula can be simplified for each of the cases supported by Direct3D.

Formulas for linear blending for three blending cases

These are the simplified forms of the complete blending formula for the two, three, and four blend matrix cases.

Note Although Direct3D includes flexible vertex format (FVF) descriptors to define vertices that contain up to five blending weights, only three can be used in this release of Microsoft DirectX.

Additional information is contained in the following topics.

  • Using Geometry Blending
  • Indexed Vertex Blending
  • Vertex Tweening


Using Geometry Blending
Microsoft DirectX 9.0 SDK Update (October 2004)

Using Geometry Blending

The following user-defined structure can be used for vertices that will be blended between two matrices.

// The flexible vertex format (FVF) descriptor for this vertex would be:
//   FVF = D3DFVF_XYZB1 | D3DFVF_NORMAL | D3DFVF_TEX1;

struct D3DBLENDVERTEX {
    D3DVECTOR v;
    FLOAT     blend;
    D3DVECTOR n;
    FLOAT     tu, tv;
};

The blend weight must appear after the position and RHW data in the flexible vertex format (FVF), and before the vertex normal.

Notice that the preceding vertex format contains only one blending weight value. This is because there will be two world matrices, defined in the D3DTS_WORLDMATRIX(0) and D3DTS_WORLDMATRIX(1) transform states. The system blends each vertex between these two matrices using the single weight value. For three matrices, only two weights are required, and so on.

Note

Defining skin weights is easy. Using a linear function of the distance between joints is good start, but a smoother sigmoid function looks better. Choosing a skin-weight distribution function can result in sharp creases at joints, if desired, by using a large variation in skin weight over a short distance.

Setting Blending Matrices

You set the transformation matrices between which the system blends by calling the IDirect3DDevice9::SetTransform method. Set the first parameter to a value defined by the D3DTS_WORLDMATRIX macro, and set the second parameter to the address of the matrix to be set.

The following C++ code example sets two world matrices, between which geometry is blended to create the illusion of a jointed arm.

// For this example, the d3dDevice variable is assumed to be a valid pointer
//   to an IDirect3DDevice9 interface for an initialized 3-D scene.

float     BendAngle = 3.1415926f / 4.0f; // 45 degrees
D3DMATRIX matUpperArm, matLowerArm;

// The upper arm is immobile. Use the identity matrix.
D3DXMatrixIdentity( matUpperArm );
d3dDevice->SetTransform( D3DTS_WORLDMATRIX(0), &matUpperArm );

// The lower arm rotates about the x-axis, attached to the upper arm.
D3DXMatrixRotationX( matLowerArm, -BendAngle );
d3dDevice->SetTransform( D3DTS_WORLDMATRIX(1), &matLowerArm );

Setting a blending matrix merely causes the system to cache the matrix for later use; it doesn't instruct the system to begin blending vertices.

Enabling Geometry Blending

Geometry blending is disabled by default. To enable geometry blending, call the IDirect3DDevice9::SetRenderState method to set the D3DRS_VERTEXBLEND render state to a value from the D3DVERTEXBLENDFLAGS enumerated type. The following code example shows what this call might look like when setting the render state for a blend between two world matrices.

d3dDevice->SetRenderState( D3DRS_VERTEXBLEND, D3DVBF_1WEIGHTS );

When D3DRS_VERTEXBLEND is set to any value other than D3DVBF_DISABLE, the system assumes that the appropriate number of blending weights will be included in the vertex format. It is your responsibility to provide a compliant vertex format, and to provide a proper description of that format to the Microsoft Direct3D rendering methods.

When enabled, the system performs geometry blending for all objects rendered by the DrawPrimitive rendering methods.

See Also

Fixed Function FVF Codes


Indexed Vertex Blending
Microsoft DirectX 9.0 SDK Update (October 2004)

Indexed Vertex Blending

Indexed vertex blending extends the vertex blending support in Microsoft Direct3D to allow matrices to be used for blending. These matrices are referred to by using a matrix index. These indices are supplied on a per-vertex basis and refer to a palette of up to 256 matrices. Each index is 8 bits and each vertex can have up to four indices, which allows four matrices to be blended per vertex. The indices are packed into a DWORD. Because indices are specified on a per-vertex basis, up to 12 matrices can affect a single triangle, and any matrix in the palette can affect the vertices of one draw call. This approach has the following advantages.

  • It enables more matrices to affect a single triangle.
  • It enables more blended triangles to be passed in the same draw call.
  • It makes vertex blending independent of triangle indices. This enables progressive meshes to work in conjunction with vertex blending.

One disadvantage of this approach is that it does not work with curved-surface primitives when tessellation occurs before vertex processing.

The following illustration demonstrates how four matrices can affect a vertex. Each vertex has up to four indices, so four matrices can be blended per vertex. The illustration below uses the matrices indexed at 0, 2, 5, and 6.

Indexed vertex blending using 4 of 256 available matrices

The illustration below demonstrates how up to 12 matrices can affect a triangle. Using indices specified on a per-vertex basis, up to 12 matrices can affect the triangle.

Indexed vertex blending for a triangle, using 12 of 256 available matrices

The following formula determines the general case for how matrices effect a vertex.

Formula for the general case of indexed vertex blending

Vmodel is the input model space vertex position. Index0..Index3 are the per-vertex matrix indices packed into a DWORD. M[] is the array of world matrices that get indexed into. b0..b2 are the blend weights. Vworld is the output world space vertex position.

Additional information is contained in the following topic.

  • Using Indexed Vertex Blending


Using Indexed Vertex Blending
Microsoft DirectX 9.0 SDK Update (October 2004)

Using Indexed Vertex Blending

Transform states 256-511 are reserved to store up to 256 matrices that can be indexed using 8-bit indices. Use the macro D3DTS_WORLDMATRIX to map indices 0-255 to the corresponding transform states. The following code example shows how to use the IDirect3DDevice9::SetTransform method to set the matrix at transform state number 256 to an identity matrix.

D3DMATRIX matBlend1;
D3DXMatrixIdentity( &matBlend1 );
m_pD3DDevice->SetTransform( D3DTS_WORLDMATRIX(0), &matBlend );

To enable or disable indexed vertex blending, set the D3DRS_INDEXEDVERTEXBLENDENABLE render state to TRUE. When the render state is enabled ,you must pass matrix indices as packed DWORDs with every vertex. When this render state is disabled and vertex blending is enabled, it is equivalent to having the matrix indices 0, 1, 2, and 3 in every vertex. The code example below uses the IDirect3DDevice9::SetRenderState method to enable indexed vertex blending.

m_pD3DDevice->SetRenderState( D3DRS_INDEXEDVERTEXBLENDENABLE, TRUE );

To enable or disable vertex blending, set the IDirect3DDevice9::SetRenderState render state to a value other than D3DRS_DISABLE from the D3DVERTEXBLENDFLAGS enumerated type. If this render state is not set to D3DRS_DISABLE, then you must pass the required number of weights for each vertex. The following code example uses IDirect3DDevice9::SetRenderState to enable vertex blending with three weights for each vertex.

m_pD3DDevice->SetRenderState( D3DRS_VERTEXBLEND, D3DVBF_3WEIGHTS );

Determining Indexed Vertex Blending Support

To determine the maximum size for the indexed vertex blending matrix, check the D3DCAPS9 structure's MaxVertexBlendMatrixIndex member. The code example below uses the IDirect3DDevice9::GetDeviceCaps method to retrieve this size.

D3DCAPS9 d3dCaps;

m_pD3DDevice->GetDeviceCaps( &d3dCaps );
IndexedMatrixMaxSize = d3dCaps.MaxVertexBlendMatrixIndex;

If the value set in MaxVertexBlendMatrixIndex is 0, the device does not support indexed matrices.

Note When software vertex processing is used, 256 matrices can be used for indexed vertex blending, with or without normal blending.

Passing Matrix Indices to Direct3D

World matrix indices can be passed to Microsoft Direct3D by using legacy vertex shaders—flexible vertex format (FVF)—or declarations.

The code example below shows how to use legacy vertex shaders.

struct VERTEX
{
    float x,y,z;
    float weight;
    DWORD matrixIndices;
    float normal[3];
};

#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZB2 | D3DFVF_LASTBETA_UBYTE4 |
                             D3DFVF_NORMAL);

When a legacy vertex shader is used, matrix indices are passed together with vertex positions using D3DFVF_XYZBn flags. Matrix indices are passed as bytes inside a DWORD and must be present immediately after the last vertex weight. Vertex weights are also passed using D3DFVF_XYZBn. A packed DWORD contains index3, index2, index1, and index0, where index0 is located in the lowest byte of the DWORD. The number of used world-matrix indices is equal to the number passed to the number of matrices used for blending as defined by D3DRS_VERTEXBLEND.

When a declaration is used, D3DVSDE_BLENDINDICES defines the input vertex register to get matrix indices from. Matrix indices must be passed as D3DVSDT_UBYTE4.

The code example below shows how to use declarations. Note that the order of the components is no longer important unless using a fixed-function vertex shader.

Here is the vertex declaration.

struct VERTEX
{
    float x,y,z;
    float weight;
    DWORD matrixIndices;
    float normal[3];
}

Here is the corresponding register declaration.

// Create the shader declaration.
D3DVERTEXELEMENT9 decl[] =
{
    { 0, 0,  D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
    { 0, 12, D3DDECLTYPE_FLOAT1, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDWEIGHT, 0 },
    { 0, 16, D3DDECLTYPE_UBYTE4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BLENDINDICES, 0 },
    { 0, 20, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 },
    D3DDECL_END()
};


Vertex Tweening
Microsoft DirectX 9.0 SDK Update (October 2004)

Vertex Tweening

Vertex tweening blends two user-provided positions (or normals). Tweening is mutually exclusive from vertex blending with weights. Tweening is performed before lighting and clipping, and is enabled by setting D3DRS_VERTEXBLEND to D3DVBF_TWEENING. The resulting vertex position is computed by:

POSITION = POSITION1 * (1.0 - TWEENFACTOR) + POSITION2 * TWEENFACTOR

The same approach is used for calculating normals. For more information, see Using Vertex Tweening.


Using Vertex Tweening
Microsoft DirectX 9.0 SDK Update (October 2004)

Using Vertex Tweening

To determine if Microsoft Direct3D supports vertex tweening, check for the D3DVTXPCAPS_TWEENING flag in the VertexProcessingCaps member of the D3DCAPS9 structure. The following code example uses the IDirect3DDevice9::GetDeviceCaps method to determine if tweening is supported.

// This example assumes that m_pD3DDevice is
// a valid pointer to a IDirect3DDevice9 interface.
//
D3DCAPS9 d3dCaps;

m_pD3DDevice->GetDeviceCaps( &d3dCaps );
if( 0 != (d3dCaps.VertexProcessingCaps & D3DVTXPCAPS_TWEENING) )
    // Vertex tweening is supported.

To use vector tweening, you must first set up a custom vertex type that uses a second normal or a second position. The following code example shows a sample declaration that includes both a second point and a second position.

struct TEX_VERTEX
{
    D3DVECTOR position;
    D3DVECTOR normal;
    D3DVECTOR position2;
    D3DVECTOR normal2;
};

//Create a vertex buffer with the type TEX_VERTEX.

The next step is to set the current declaration. The code example below shows how to do this.

// Create the shader declaration.
D3DVERTEXELEMENT9 decl[] =
{
    { 0, 0,  D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
    { 0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 },
    { 0, 24, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 1 },
    { 0, 36, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 1 },
    D3DDECL_END()
};

For more information about creating a custom vertex type and a vertex buffer, see Creating a Vertex Buffer.

Note When vertex tweening is enabled, a second position or a second normal must be present in the current declaration.


Higher-Order Primitives
Microsoft DirectX 9.0 SDK Update (October 2004)

Higher-Order Primitives

Microsoft DirectX 9.0 supports points, lines, triangles, and grid primitives. These have been extended to support higher-order interpolation beyond linear. While triangles and lines have spatial extent, until now they were both rendered using linear interpolation. In DirectX 9.0, Microsoft Direct3D supports rendering of these primitive types using higher order, up to quintic, interpolation. Furthermore, a new quad primitive type is now supported. This new type can also be rendered with higher-order interpolation. This feature is primarily driven by requirements for animation and rendering of characters. It can also be used for other surfaces such as terrain or water.

Higher-order primitives support higher-order interpolation when transmitted to the application programming interface (API) as lists, strips, fans, or indexed meshes. This is achieved by using additional information encoded in the vertices themselves. For example, normal vectors can be used to define tangent planes at the vertices to enable cubic interpolation. Most implementations support higher-order interpolation by tessellation into planar triangles. The tessellation step is applied logically before the vertex shader stage. Because the vertex shader API does not impose semantics on its input data, a special mechanism is provided to identify the vertex stream component that represents the position, and optionally the normal vector. All other components are interpolated accordingly.

This section introduces higher-order primitives and discusses how they can be used in your applications. Information is divided into the following topics.

  • Improved Quality through Resolution Enhancement
  • Direct Mapping from Spline-Based Tools

Improved Quality through Resolution Enhancement

Current primitives are not ideal for representing smooth surfaces. Higher-order interpolation methods, such as cubic polynomials, allow more accurate calculations in rendering curved shapes. This provides increased realism by reducing or eliminating faceting artifacts visible on silhouette edges or on specular surface lighting. Furthermore, when tessellation occurs on the chip, the tessellated triangles do not impact the bus bandwidth. In many cases, a small amount of tessellation can provide improvements in image quality with minimal performance impact.

Direct3D for DirectX 9.0 provides a simple way to apply resolution enhancement to content created by existing polygon-oriented tools and art pipelines. The application need only provide a desired level of tessellation, and transmit the data using standard triangle syntax that includes normal vectors.

Direct Mapping from Spline-Based Tools

Many current authoring tools support higher-order primitives to enable more powerful modeling operations than are commonly provided for with planar triangle meshes. When used efficiently, so that the number of patches generated is reasonable, such tools can produce content that can be rendered directly by the API. To meet this requirement, a new entry point has been added that interprets the incoming vertex data stream as a 2-D array of control points and tessellates it to the desired resolution.

  • Using Higher-Order Primitives


Using Higher-Order Primitives
Microsoft DirectX 9.0 SDK Update (October 2004)

Using Higher-Order Primitives

This section shows you how to use higher-order primitives in your application.

  • Determining Higher-Order Primitive Support
  • Drawing Patches
  • Generating Normals and Texture Coordinates

Determining Higher-Order Primitive Support

The D3DCAPS9 structure's DevCaps member can be queried to determine the level of support for operations involving higher-order primitives. The following table lists the device capabilities related to higher-order primitives in Microsoft DirectX 9.0.

Device capability | Description
D3DDEVCAPS_NPATCHES | Device supports N-patches.
D3DDEVCAPS_QUINTICRTPATCHES | Device supports quintic Bézier curves and B-splines.
D3DDEVCAPS_RTPATCHES | Device supports rectangular and triangular patches (RT-patches).
D3DDEVCAPS_RTPATCHHANDLEZERO | RT-patches might be drawn efficiently using handle zero.

Note that D3DDEVCAPS_RTPATCHHANDLEZERO does not mean that a patch with handle zero can be drawn. A handle zero patch can always be drawn, whether this device capability is set or not. When this capability is set, the hardware architecture does not require caching of any information and that uncached patches (handle zero) be drawn as efficiently as cached ones.

Drawing Patches

DirectX 9.0 supports two types of higher-order primitives, or patches. These are referred to as N-Patches and Rect/Tri patches. N-patches can be rendered using any triangle rendering call by enabling N-patches through the call to IDirect3DDevice9::SetNPatchMode( nSegments ) with nSegments value greater than 1.0. Rect/Tri patches must be rendered using the following explicit entry points.

You can use the following methods to draw patches.

  • IDirect3DDevice9::DrawRectPatch. To better understand how the patch data is referenced in the vertex buffer, see D3DRECTPATCH_INFO.
  • IDirect3DDevice9::DrawTriPatch. To better understand how the patch data is referenced in the vertex buffer, see D3DTRIPATCH_INFO.

IDirect3DDevice9::DrawRectPatch draws a rectangular high-order patch specified by the pRectPatchInfo parameter using the currently set streams. The Handle parameter is used to associate the patch with a handle, so that the next time the patch is drawn, there is no need to respecify pRectPatchInfo. This makes it possible to precompute and cache forward difference coefficients or other information, which in turn enables subsequent calls to IDirect3DDevice9::DrawRectPatch using the same handle to run efficiently.

It is intended that for static patches, an application would set the vertex shader and appropriate streams, supply patch information in the pRectPatchInfo parameter, and specify a handle so that Microsoft Direct3D can capture and cache information. The application can then call IDirect3DDevice9::DrawRectPatch subsequently with pRectPatchInfo set to NULL to efficiently draw the patch. When drawing a cached patch, the currently set streams are ignored. However, it is possible to override the cached pNumSegs by specifying new values for pNumSegs. Also, it is required to set the same vertex shader when rendering a cached patch as was set when it was captured.

For dynamic patches, the patch data changes for every rendering of the patch, so it is not efficient to cache information. The application can convey this to Direct3D by setting Handle to 0. In this case, Direct3D draws the patch using the currently set streams and the pNumSegs values and does not cache any information. It is not valid to simultaneously set Handle to 0 and pPatch to NULL.

By respecifying pRectPatchInfo for the same handle, the application can overwrite the previously cached information.

IDirect3DDevice9::DrawTriPatch is similar to IDirect3DDevice9::DrawRectPatch except that it draws a triangular high-order patch.

Generating Normals and Texture Coordinates

If you are using a flexible vertex format (FVF) shader, automatic generation of normals and texture coordinates is not possible.

For normals, you can either directly supply them or have Direct3D calculate them for you.

The coordinates generated for rectangular patches are spline-based coordinates, as illustrated by the following images.

The coordinates generated for triangular patches are barycentric spline-based coordinates, as illustrated by the images below.

Barycentric spline-based coordinates

If an application must change the range of the generated texture coordinates, this can be done using texture transforms.


Point Sprites
Microsoft DirectX 9.0 SDK Update (October 2004)

Point Sprites

Support for point sprites in Microsoft Direct3D for Microsoft DirectX 9.0 enables the high-performance rendering of points (particle systems). Point sprites are generalizations of generic points that enable arbitrary shapes to be rendered as defined by textures.

  • Point Primitive Rendering Controls
  • Point Size Computations
  • Point Rendering

Point Primitive Rendering Controls

Direct3D for DirectX 9.0 supports additional parameters to control the rendering of point sprites (point primitives). These parameters enable points to be of variable size and have a full texture map applied. The size of each point is determined by an application-specified size combined with a distance-based function computed by Direct3D. The application can specify point size either as per-vertex or by setting D3DRS_POINTSIZE, which applies to points without a per-vertex size. The point size is expressed in camera space units, with the exception of when the application is passing post-transformed flexible vertex format (FVF) vertices. In this case, the distance-based function is not applied and the point size is expressed in units of pixels on the render target.

The texture coordinates computed and used when rendering points depends on the setting of D3DRS_POINTSPRITEENABLE. When this value is set to TRUE, the texture coordinates are set so that each point displays the full texture. In general, this is only useful when points are significantly larger than one pixel. When D3DRS_POINTSPRITEENABLE is set to FALSE, each point's vertex texture coordinate is used for the entire point.

Point Size Computations

Point size is determined by D3DRS_POINTSCALEENABLE. If this value is set to FALSE, the application-specified point size is used as the screen-space (post-transformed) size. Vertices that are passed to Direct3D in screen space do not have point sizes computed; the specified point size is interpreted as screen-space size.

If D3DRS_POINTSCALEENABLE is TRUE, Direct3D computes the screen-space point size according to the following formula. The application-specified point size is expressed in camera space units.

S s = Vh * S i * sqrt(1/(A + B * D e + C *( D e2 )))

In this formula, the input point size, S i, is either per-vertex or the value of the D3DRS_POINTSIZE render state. The point scale factors, D3DRS_POINTSCALE_A, D3DRS_POINTSCALE_B, and D3DRS_POINTSCALE_C, are represented by the points A, B, and C. The height of the viewport, V h, is the D3DVIEWPORT9 structure's Height member representing the viewport. D e, the distance from the eye to the position (the eye at the origin), is computed by taking the eye space position of the point (Xe, Ye, Ze) and performing the following operation.

D e = sqrt (Xe2 + Y e2 + Z e2)

The maximum point size, Pmax, is determined by taking the smaller of either the D3DCAPS9 structure's MaxPointSize member or the D3DRS_POINTSIZE_MAX render state. The minimum point size, Pmin, is determined by querying the value of D3DRS_POINTSIZE_MIN. Thus the final screen-space point size, S, is determined in the following manner.

  • If Ss > Pmax, then S = P max
  • if S < Pmin, then S = P min
  • Otherwise, S = S s

Point Rendering

A screen-space point, P = ( X, Y, Z, W), of screen-space size S is rasterized as a quadrilateral of the following four vertices.

(( X + S/2, Y + S/2, Z, W), ( X + S/2, Y - S/2, Z, W), ( X - S/2, Y- S/2, Z, W), ( X - S/2, Y + S/2, Z, W))

The vertex color attributes are duplicated at each vertex; thus each point is always rendered with constant colors.

The assignment of texture indices is controlled by the D3DRS_POINTSPRITEENABLE render state setting. If D3DRS_POINTSPRITEENABLE is set to FALSE, then the vertex texture coordinates are duplicated at each vertex. If D3DRS_POINTSPRITEENABLE is set to TRUE, then the texture coordinates at the four vertices are set to the following values.

(0.F, 0.F), (0.F, 1.F), (1.F, 0.F), (1.F, 1.F)

This is shown in the following diagram.

Square with vertices labeled with (u,v) and (x,y) coordinate values

When clipping is enabled, points are clipped in the following manner. If the vertex exceeds the range of depth values - MinZ and MaxZ of the D3DVIEWPORT9 structure - into which a scene is to be rendered, the point exists outside of the view frustum and is not rendered. If the point, taking into account the point size, is completely outside the viewport in X and Y, then the point is not rendered; the remaining points are rendered. It is possible for the point position to be outside the viewport in X or Y and still be partially visible.

Points may or may not be correctly clipped to user-defined clip planes. If D3DPMISCCAPS_CLIPPLANESCALEDPOINTS is not set in the D3DCAPS9 structure's PrimitiveMiscCaps member, points are clipped to user-defined clip planes based only on the vertex position, ignoring the point size. In this case, scaled points are fully rendered when the vertex position is inside the clip planes, and discarded when the vertex position is outside a clip plane. Applications can prevent potential artifacts by adding a border geometry to clip planes that is as large as the maximum point size.

If the D3DPMISCCAPS_CLIPPLANESCALEDPOINTS bit is set, then the scaled points are correctly clipped to user-defined clip planes.

Hardware vertex processing may or may not support point size. For example, if a device is created with D3DCREATE_HARDWARE_VERTEXPROCESSING on a HAL device (D3DDEVTYPE_HAL) that has the D3DCAPS9 structure's MaxPointSize member set to 1.0 or 0.0, then all points are a single pixel. To render pixel point sprites less than 1.0, you must use either FVF TL (transformed and lit) vertices or software vertex processing (D3DCREATE_SOFTWARE_VERTEXPROCESSING), in which case the Direct3D run time emulates the point sprite rendering.

A hardware device that does vertex processing and supports point sprites—MaxPointSize set to greater than 1.0f—is required to perform the size computation for nontransformed sprites and is required to properly set the per-vertex or D3DRS_POINTSIZE for TL vertices.

For information about rendering rules for points, lines, and triangles, see Triangle Rasterization Rules.


Matrix Stacks
Microsoft DirectX 9.0 SDK Update (October 2004)

Matrix Stacks

The D3DX utility library provides the ID3DXMatrixStack interface. It supplies a mechanism to enable matrices to be pushed onto and popped off of a matrix stack. Implementing a matrix stack is an efficient way to track matrices while traversing a transform hierarchy.

The D3DX utility library uses a matrix stack to store transformations as matrices. The various methods of the ID3DXMatrixStack interface deal with the current matrix, or the matrix located on top of the stack. You can clear the current matrix with the ID3DXMatrixStack::LoadIdentity method. To explicitly specify a certain matrix to load as the current transformation matrix, use the ID3DXMatrixStack::LoadMatrix method. Then you can call either the ID3DXMatrixStack::MultMatrix method or the ID3DXMatrixStack::MultMatrixLocal method to multiply the current matrix by the specified matrix.

The ID3DXMatrixStack::Pop method enables you to return to the previous transformation matrix and the ID3DXMatrixStack::Push method adds a transformation matrix to the stack.

The individual matrices on the matrix stack are represented as 4×4 homogeneous matrices, defined by the D3DX utility library D3DXMATRIX structure.

The D3DX utility library provides a matrix stack through a Component Object Model (COM) object.

Implementing a Scene Hierarchy

A matrix stack simplifies the construction of hierarchical models, in which complicated objects are constructed from a series of simpler objects.

A scene, or transform, hierarchy is usually represented by a tree data structure. Each node in the tree data structure contains a matrix. A particular matrix represents the change in coordinate systems from the node's parent to the node. For example, if you are modeling a human arm, you might implement the following hierarchy.

Hierarchy of modeling of a human arm

In this hierarchy, the Body matrix places the body in the world. The UpperArm matrix contains the rotation of the shoulder, the LowerArm matrix contains the rotation of the elbow, and the Hand matrix contains the rotation of the wrist. To determine where the hand is relative to the world, you multiply all the matrices from Body down through Hand together.

The previous hierarchy is overly simplistic, because each node has only one child. If you begin to model the hand in more detail, you will probably add fingers and a thumb. Each digit can be added to the hierarchy as children of Hand.

Hierarchy of modeling of a human hand

If you traverse the complete graph of the arm in depth-first order—traversing as far down one path as possible before moving on to the next path—to draw the scene, you perform a sequence of segmented rendering. For example, to render the hand and fingers, you implement the following pattern.

  1. Push the Hand matrix onto the matrix stack.
  2. Draw the hand.
  3. Push the Thumb matrix onto the matrix stack.
  4. Draw the thumb.
  5. Pop the Thumb matrix off the stack.
  6. Push the Finger 1 matrix onto the matrix stack.
  7. Draw the first finger.
  8. Pop the Finger 1 matrix off the stack.
  9. Push the Finger 2 matrix onto the matrix stack. You continue in this manner until all the fingers and thumb are rendered.

After you have completed rendering the fingers, you would pop the Hand matrix off the stack.

You can follow this basic process in code with the following examples. When you encounter a node during the depth-first search of the tree data structure, push the matrix onto the top of the matrix stack.

MatrixStack->Push();

MatrixStack->MultMatrix(pNode->matrix);

When you are finished with a node, pop the matrix off the top of the matrix stack.

MatrixStack->Pop();

In this way, the matrix on the top of the stack always represents the world-transform of the current node. Therefore, before drawing each node, you should set the Microsoft Direct3D matrix.

pD3DDevice->SetTransform(D3DTS_WORLDMATRIX(0), *MatrixStack->GetTop());

For more information about the specific methods that you can perform on a D3DX matrix stack, see the ID3DXMatrixStack reference topic.


Pixel Pipeline
Microsoft DirectX 9.0 SDK Update (October 2004)

Pixel Pipeline

This is a list of advanced topics that are implemented by pixel processing.

  • Scissor Test
  • Depth Bias
  • Stencil Buffer Techniques
  • Shadowing
  • Bump Mapping
  • Environment Mapping
  • Antialiasing
  • Multiple Render Targets
  • Multielement Textures


Scissor Test
Microsoft DirectX 9.0 SDK Update (October 2004)

Scissor Test

The scissor rectangle is managed by a device render state. A scissor test is enabled or disabled by setting the renderstate to TRUE or FALSE. This test is performed after the fragment color is computed but before alpha testing. IDirect3DDevice9::SetRenderTarget resets the scissor rectangle to the full render target, analogous to the viewport reset. IDirect3DDevice9::SetScissorRect is recorded by stateblocks, and IDirect3DDevice9::CreateStateBlock with the all state setting (D3DSBT_ALL value in D3DSTATEBLOCKTYPE). The scissor test also affects the device IDirect3DDevice9::Clear operation.

// Methods
HRESULT IDirect3DDevice9::SetScissorRect(CONST RECT* pRect);
HRESULT IDirect3DDevice9::GetScissorRect(RECT* pRect);

// New RenderState, values are TRUE or FALSE
D3DRS_SCISSORTESTENABLE

// New hardware cap
D3D9CAPS.RasterCaps -> D3DPRASTERCAPS_SCISSORTEST;

The default scissor rectangle is the full viewport.

Scissor testing is done just after pixel processing is completed by a pixel shader or the fixed function pipeline, as shown below.

Scissor test flowchart


Depth Bias
Microsoft DirectX 9.0 SDK Update (October 2004)

Depth Bias

Polygons that are coplanar in your 3-D space can be made to appear as if they are not coplanar by adding a z-bias to each one. This is a technique commonly used to ensure that shadows in a scene are displayed properly. For instance, a shadow on a wall will likely have the same depth value as the wall does. If you render the wall first and then the shadow, the shadow might not be visible, or depth artifacts might be visible. You can reverse the order in which you render the coplanar objects in hopes of reversing the effect, but depth artifacts are still likely.

An application can help ensure that coplanar polygons are rendered properly by adding a bias to the z-values that the system uses when rendering the sets of coplanar polygons. To add a z-bias to a set of polygons, call the IDirect3DDevice9::SetRenderState method just before rendering them, setting the State parameter to D3DRS_DEPTHBIAS, and the Value parameter to a value between 0-16 inclusive. A higher z-bias value increases the likelihood that the polygons you render will be visible when displayed with other coplanar polygons.

Offset = m * D3DRS_SLOPESCALEDEPTHBIAS + D3DRS_DEPTHBIAS

where m is the maximum depth slope of the triangle being rendered.

m = max(abs(delta z / delta x), abs(delta z / delta y))

The units for the D3DRS_DEPTHBIAS and D3DRS_SLOPESCALEDEPTHBIAS render states depend on whether z-buffering or w-buffering is enabled. The application must provide suitable values.

The bias is not applied to any line and point primitive. However, this bias needs to be applied to triangles drawn in wireframe mode.

    // RenderStates
    D3DRS_SLOPESCALEDEPTHBIAS, // Defaults to zero
    D3DRS_DEPTHBIAS,           // Defaults to zero

    // Caps
    D3DPRASTERCAPS_DEPTHBIAS
    D3DPRASTERCAPS_SLOPESCALEDEPTHBIAS


Stencil Buffer Techniques
Microsoft DirectX 9.0 SDK Update (October 2004)

Stencil Buffer Techniques

Applications use the stencil buffer to mask pixels in an image. The mask controls whether the pixel is drawn. Some of the more common effects are shown below.

  • Compositing
  • Decaling
  • Dissolves, Fades, and Swipes
  • Outlines and Silhouettes
  • Two-Sided Stencil

The stencil buffer enables or disables drawing to the rendering target surface on a pixel-by-pixel basis. At its most fundamental level, it enables applications to mask sections of the rendered image so that they are not displayed. Applications often use stencil buffers for special effects such as dissolves, decaling, and outlining.

Stencil buffer information is embedded in the z-buffer data. Your application can use the IDirect3D9::CheckDeviceFormat method to check for hardware stencil support, as shown in the following code example.

// Reject devices that cannot perform 8-bit stencil buffering.
// The following example assumes that pCaps is a valid pointer
// to an initialized D3DCAPS9 structure.

if( FAILED( m_pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal,
                                       pCaps->DeviceType,
                                       Format,
                                       D3DUSAGE_DEPTHSTENCIL,
                                       D3DRTYPE_SURFACE,
                                       D3DFMT_D24S8 ) ) )
        return E_FAIL;

IDirect3D9::CheckDeviceFormat allows you to choose a device to create based on the capabilities of that device. In this case, devices that do not support 8-bit stencil buffers are rejected. Note that this is only one possible use for IDirect3D9::CheckDeviceFormat; for details see Determining Hardware Support.

How the Stencil Buffer Works

Microsoft Direct3D performs a test on the contents of the stencil buffer on a pixel-by-pixel basis. For each pixel in the target surface, it performs a test using the corresponding value in the stencil buffer, a stencil reference value, and a stencil mask value. If the test passes, Direct3D performs an action. The test is performed using the following steps.

  1. Perform a bitwise AND operation of the stencil reference value with the stencil mask.
  2. Perform a bitwise AND operation of the stencil buffer value for the current pixel with the stencil mask.
  3. Compare the result of step 1 to the result of step 2, using the comparison function.

These steps are shown in the following code example.

(StencilRef & StencilMask) CompFunc (StencilBufferValue & StencilMask)

StencilBufferValue is the contents of the stencil buffer for the current pixel. This code example uses the ampersand (&) symbol to represent the bitwise AND operation. StencilMask represents the value of the stencil mask, and StencilRef represents the stencil reference value. CompFunc is the comparison function.

The current pixel is written to the target surface if the stencil test passes, and is ignored otherwise. The default comparison behavior is to write the pixel, no matter how each bitwise operation turns out (D3DCMP_ALWAYS). You can change this behavior by changing the value of the D3DRS_STENCILFUNC render state, passing a member of the D3DCMPFUNC enumerated type to identify the desired comparison function.

Your application can customize the operation of the stencil buffer. It can set the comparison function, the stencil mask, and the stencil reference value. It can also control the action that Direct3D takes when the stencil test passes or fails. For more information, see Stencil Buffer State.


Compositing
Microsoft DirectX 9.0 SDK Update (October 2004)

Compositing

Your application can use the stencil buffer to composite 2-D or 3-D images onto a 3-D scene. A mask in the stencil buffer is used to occlude an area of the rendering target surface. Stored 2-D information, such as text or bitmaps, can then be written to the occluded area. Alternately, your application can render additional 3-D primitives to the stencil-masked region of the rendering target surface. It can even render an entire scene.

Games often composite multiple 3-D scenes together. For instance, driving games typically display a rear-view mirror. The mirror contains the view of the 3-D scene behind the driver. It is essentially a second 3-D scene composited with the driver's forward view.


Decaling
Microsoft DirectX 9.0 SDK Update (October 2004)

Decaling

Microsoft Direct3D applications use decaling to control which pixels from a particular primitive image are drawn to the rendering target surface. Applications apply decals to the images of primitives to enable coplanar polygons to render correctly.

For instance, when applying tire marks and yellow lines to a roadway, the markings should appear directly on top of the road. However, the z values of the markings and the road are the same. Therefore, the depth buffer might not produce a clean separation between the two. Some pixels in the back primitive may be rendered on top of the front primitive and vice versa. The resulting image appears to shimmer from frame to frame. This effect is called z-fighting or flimmering.

To solve this problem, use a stencil to mask the section of the back primitive where the decal will appear. Turn off z-buffering and render the image of the front primitive into the masked-off area of the render-target surface.

Although multiple texture blending can be used to solve this problem, doing so limits the number of other special effects that your application can produce. Using the stencil buffer to apply decals frees up texture blending stages for other effects.


Dissolves, Fades, and Swipes
Microsoft DirectX 9.0 SDK Update (October 2004)

Dissolves, Fades, and Swipes

Increasingly, applications employ special effects that are commonly used in movies and video, such as dissolves, swipes, and fades.

In a dissolve, one image is gradually replaced by another in a smooth sequence of frames. Although Microsoft Direct3D provides methods of using multiple texture blending to achieve the same effect, applications that use the stencil buffer for dissolves can use texture-blending capabilities for other effects while they do a dissolve.

When your application performs a dissolve, it must render two different images. It uses the stencil buffer to control which pixels from each image are drawn to the rendering target surface. You can define a series of stencil masks and copy them into the stencil buffer on successive frames. Alternately, you can define a base stencil mask for the first frame and alter it incrementally.

At the beginning of the dissolve, your application sets the stencil function and stencil mask so that most of the pixels from the starting image pass the stencil test. Most of the pixels from the ending image should fail the stencil test. On successive frames, the stencil mask is updated so that fewer and fewer of the pixels in the starting image pass the test. As the frames progress, fewer and fewer of the pixels in the ending image fail the test. In this manner, your application can perform a dissolve using any arbitrary dissolve pattern.

Fading in or fading out is a special case of dissolving. When fading in, the stencil buffer is used to dissolve from a black or white image to a rendering of a 3-D scene. Fading out is the opposite, your application starts with a rendering of a 3-D scene and dissolves to black or white. The fade can be done using any arbitrary pattern you want to employ.

Direct3D applications use a similar technique for swipes. For example, when an application performs a left-to-right swipe, the ending image appears to slide gradually on top of the starting image from left to right. As in a dissolve, you must define a series of stencil masks that are loaded into the stencil buffer on successive frames, or successively modify the starting stencil mask. The stencil masks are used to disable the writing of pixels from the starting image and to enable the writing of pixels from the ending image.

A swipe is somewhat more complex than a dissolve in that your application must read pixels from the ending image in the reverse order of the swipe. That is, if the swipe is moving from left to right, your application must read pixels from the ending image from right to left.


Outlines and Silhouettes
Microsoft DirectX 9.0 SDK Update (October 2004)

Outlines and Silhouettes

You can use the stencil buffer for more abstract effects, such as outlining and silhouetting.

If your application applies a stencil mask to the image of a primitive that is the same shape but slightly smaller, the resulting image contains only the primitive's outline. The application can then fill the stencil-masked area of the image with a solid color, giving the primitive an embossed look.

If the stencil mask is the same size and shape as the primitive you are rendering, the resulting image contains a hole where the primitive should be. Your application can then fill the hole with black to produce a silhouette of the primitive.


Two-Sided Stencil
Microsoft DirectX 9.0 SDK Update (October 2004)

Two-Sided Stencil

Shadow Volumes are used for drawing shadows with the stencil buffer. The application computes the shadow volumes cast by occluding geometry, by computing the silhouette edges and extruding them away from the light into a set of 3-D volumes. These volumes are then rendered twice into the stencil buffer.

The first render draws forward-facing polygons, and increments the stencil-buffer values. The second render draws the back-facing polygons of the shadow volume, and decrements the stencil buffer values. Normally, all incremented and decremented values cancel each other out. However, the scene was already rendered with normal geometry causing some pixels to fail the z-buffer test as the shadow volume is rendered. Values left in the stencil buffer correspond to pixels that are in the shadow. These remaining stencil-buffer contents are used as a mask, to alpha-blend a large, all-encompassing black quad into the scene. With the stencil buffer acting as a mask, the result is to darken pixels that are in the shadows.

This means that the shadow geometry is drawn twice per light source, hence putting pressure on the vertex throughput of the GPU. The two-sided stencil feature has been designed to mitigate this situation. In this approach, there are two sets of stencil state (named below), one set each for the front-facing triangles and the other for the back-facing triangles. This way, only a single pass is drawn per shadow volume, per light.

The application programming interface (API) changes are restricted to a new set of render states. The new render state D3DRS_TWOSIDEDSTENCILMODE can be set to TRUE or FALSE. It is false by default, meaning current (Microsoft DirectX 8.x) behavior. When this is set to TRUE (it will work only if D3DSTENCILCAPS_TWOSIDED is set), the following render states will apply only to the front-facing (clockwise) triangles.

Render state | Description
D3DRS_STENCILFAIL | D3DSTENCILOP to do if stencil test fails.
D3DRS_STENCILZFAIL | D3DSTENCILOP to do if stencil test passes and z-test fails.
D3DRS_STENCILPASS | D3DSTENCILOP to do if both stencil and z-tests pass.
D3DRS_STENCILFUNC | D3DCMPFUNC fn. Stencil Test passes if ((ref & mask) stencilfn (stencil & mask)) is true.

A new set of render states apply to the back-facing (counterclockwise) triangles.

Render state | Description
D3DRS_CCW_STENCILFAIL | D3DSTENCILOP to do if stencil test fails.
D3DRS_CCW_STENCILZFAIL | D3DSTENCILOP to do if stencil test passes and z-test fails.
D3DRS_CCW_STENCILPASS | D3DSTENCILOP to do if both stencil and z-tests pass.
D3DRS_CCW_STENCILFUNC | D3DCMPFUNC function. Stencil test passes if ((ref & mask) stencilfn (stencil & mask)) is true.

The remaining stencil render states always apply to both clockwise and counterclockwise triangles.

D3DRS_TWOSIDEDSTENCILMODE is ignored for lines and point sprites, which means that the behavior is unchanged from DirectX 8.x. The D3DRS_CCW_STENCIL* render states are ignored.

A new cap bit indicates if the device supports this feature. Drivers that do not support this feature are expected to ignore these new render states. All other stencil cap bits apply to both modes of stencil buffering. Because TWOSIDEDSTENCIL implies the ability to draw with D3DCULLMODE_NONE set, the corresponding cap must be set by the driver if it supports this new stencil mode. Microsoft Windows Hardware Quality Labs (WHQL) should enforce this.

New render states:

    D3DRS_TWOSIDEDSTENCILMODE // BOOL (default is FALSE)
    D3DRS_CCW_STENCILFAIL     // Same default as D3DRS_STENCILFAIL
    D3DRS_CCW_STENCILZFAIL    // Same default as D3DRS_STENCILZFAIL
    D3DRS_CCW_STENCILPASS     // Same default as D3DRS_STENCILPASS
    D3DRS_CCW_STENCILFUNC     // Same default as D3DRS_STENCILFUNC

New cap:

    D3DSTENCILCAPS_TWOSIDED // a flag on D3DCAPS9.StencilCaps

Related Topics

  • D3DRENDERSTATETYPE


Shadowing
Microsoft DirectX 9.0 SDK Update (October 2004)

Shadowing

Stencil buffers are a depth-buffer technique that can be updated as geometry is rendered, and used again as a mask for drawing more geometry. Common effects include mirrors, shadows (an advanced technique), dissolves, and so on. The ShadowVolume Sample uses stencil buffers to implement real-time shadows. Additional information is contained in Two-Sided Stencil.


Bump Mapping
Microsoft DirectX 9.0 SDK Update (October 2004)

Bump Mapping

Bump mapping is a special form of specular or diffuse environment mapping that simulates the reflections of finely tessellated objects without requiring extremely high polygon counts. Bump mapping implemented by Microsoft Direct3D can be accurately described as per-pixel texture coordinate perturbation of specular or diffuse environment maps, because you provide information about the contour of the bump map in terms of delta values, which the system applies to the u and v texture coordinates of an environment map in the next texture stage. The delta values are encoded in the pixel format of the bump map surface (see Bump Map Pixel Formats).

Bump mapping relies on blending multiple textures. This means the device must support at least two blending stages; one for the bump map and another for an environment map. A minimum of three texture blending stages are required to apply an additional base texture map, which is the most common case. This figure shows the relationships between the base texture, the bump map, and the environment map in the texture blending cascade:

Texture blending cascade used to generate polygon texture

You must prepare the texture stages appropriately to enable bump mapping. The following topics introduce bump mapping, and provide details about how you can use it in your applications:

  • Bump Map Pixel Formats
  • Bump Mapping Formulas
  • Using Bump Mapping

Direct3D does not natively support height maps; they are merely a convenient format in which to store and visualize contour data. Your application can store contour information in any format, or even generate a procedural bump map.


Bump Map Pixel Formats
Microsoft DirectX 9.0 SDK Update (October 2004)

Bump Map Pixel Formats

A bump map is an IDirect3DTexture9 object that uses a specialized pixel format. Rather than storing red, green, and blue color components, each pixel in a bump map stores the delta values for u and v (DU and DV) and sometimes a luminance component, L. These values are applied by the system as described in the Bump Mapping Formulas topic.

You can specify a bump map pixel format by setting the format to one of the following: D3DFMT_CxV8U8, D3DFMT_V8U8, D3DFMT_L6V5U5, D3DFMT_X8L8V8U8, D3DFMT_Q8W8V8U8, or D3DFMT_V16U16. For descriptions, see D3DFORMAT.

The DU and DV components of a pixel are signed values that range from –1.0 to +1.0. The luminance component, when used, is an unsigned integer value that ranges from 0 to 255.

Note Before picking a bump map pixel format, check if the particular format is supported. For more information, see Using Bump Mapping.


Bump Mapping Formulas
Microsoft DirectX 9.0 SDK Update (October 2004)

Bump Mapping Formulas

Microsoft Direct3D applies the following formulas to the DU and DV components in each bump map pixel.

Formula for bump mapping matrix transformation

In these formulas, the DU and DV variables are taken directly from a bump map pixel and transformed by a 2x2 matrix to produce the output delta values DU' and DU'. The system uses the output values to modify the texture coordinates that address the environment map in the next texture stage. The coefficients of the transformation matrix are set though the D3DTSS_BUMPENVMAT00, D3DTSS_BUMPENVMAT10, D3DTSS_BUMPENVMAT01, and D3DTSS_BUMPENVMAT11 texture stage states.

In addition to the u and v delta values, the system can compute a luminance value that it uses to modulate the color of the environment map in the next blending stage.

Formula for output luminance, computed from scale factor and offset

In this formula, L' is the output luminance being computed. The L variable is the luminance value taken from a bump map pixel, which is multiplied by the scaling factor, S, and offset by the value in the variable O. The D3DTSS_BUMPENVLSCALE and D3DTSS_BUMPENVLOFFSET texture stage states control the values for the S and O variables in the formula. This formula is only applied when the texture blending operation for the stage that contains the bump map is set to D3DTOP_BUMPENVMAPLUMINANCE. When using D3DTOP_BUMPENVMAP, the system uses a value of 1.0 for L'.

After computing the output delta values DU' and DV', the system adds them to the texture coordinates in the next texture stage, and modulates the chosen color by the luminance to produce the color applied to the polygon.


Using Bump Mapping
Microsoft DirectX 9.0 SDK Update (October 2004)

Using Bump Mapping

Detecting Support for Bump Mapping

A device can perform bump mapping if it supports either the D3DTOP_BUMPENVMAP or D3DTOP_BUMPENVMAPLUMINANCE texture blending operation. Use IDirect3D9::CheckDeviceFormat with D3DUSAGE_QUERY_LEGACYBUMPMAP to see if a format is supported for bump mapping.

Additionally, applications should check the device capabilities to make sure the device supports an appropriate number of blending stages, usually at least three, and exposes at least one bump-mapping pixel format.

The following code example checks device capabilities to detect support for bump mapping in the current device, using the given criteria.

BOOL SupportsBumpMapping()
{
    D3DCAPS9 d3dCaps;

    d3dDevice->GetDeviceCaps( &d3dCaps );

    // Does this device support the two bump mapping blend operations?
    if ( 0 == d3dCaps.TextureOpCaps & ( D3DTEXOPCAPS_BUMPENVMAP |
                                         D3DTEXOPCAPS_BUMPENVMAPLUMINANCE ))
        return FALSE;

    // Does this device support up to three blending stages?
    if( d3dCaps.MaxTextureBlendStages < 3 )
        return FALSE;

    return TRUE;
}

Creating a Bump Map Texture

You create a bump map texture like any other texture. Your application verifies support for bump mapping and retrieves a valid pixel format, as discussed in Detecting Support for Bump Mapping.

After the surface is created, you can load each pixel with the appropriate delta values, and luminance, if the surface format includes luminance. The values for each pixel component are described in Bump Map Pixel Formats.

Configuring Bump Mapping Parameters

When your application has created a bump map and set the contents of each pixel, you can prepare for rendering by configuring bump mapping parameters. Bump mapping parameters include setting the required textures and their blending operations, as well as the transformation and luminance controls for the bump map itself.

  1. Set the base texture map if used, bump map, and environment map textures into texture blending stages.
  2. Set the color and alpha blending operations for each texture stage.
  3. Set the bump map transformation matrix.
  4. Set the luminance scale and offset values as needed.

The following code example sets three textures (the base texture map, the bump map, and a specular environment map) to the appropriate texture blending stages.

// Set the three textures.
d3dDevice->SetTexture( 0, d3dBaseTexture );
d3dDevice->SetTexture( 1, d3dBumpMap );
d3dDevice->SetTexture( 2, d3dEnvMap );

After setting the textures to their blending stages, the following code example prepares the blending operations and arguments for each stage.

// Set the color operations and arguments to prepare for
//   bump mapping.

// Stage 0: The base texture
d3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
d3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
d3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 );
d3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, 1 );

// Stage 1: The bump map - Use luminance for this example.
d3dDevice->SetTextureStageState( 1, D3DTSS_TEXCOORDINDEX, 1 );
d3dDevice->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_BUMPENVMAPLUMINANCE);
d3dDevice->SetTextureStageState( 1, D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState( 1, D3DTSS_COLORARG2, D3DTA_CURRENT );

// Stage 2: A specular environment map
d3dDevice->SetTextureStageState( 2, D3DTSS_TEXCOORDINDEX, 0 );
d3dDevice->SetTextureStageState( 2, D3DTSS_COLOROP, D3DTOP_ADD );
d3dDevice->SetTextureStageState( 2, D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState( 2, D3DTSS_COLORARG2, D3DTA_CURRENT );

When the blending operations and arguments are set, the following code example sets the 2x2 bump mapping matrix to the identity matrix by setting the D3DTSS_BUMPENVMAPMAT00 and the D3DTSS_BUMPENVMAPMAT11 members of D3DTEXTURESTAGESTATETYPE to 1.0. Setting the matrix to the identity causes the system to use the delta values in the bump map unmodified, but this is not a requirement.

// Set the bump mapping matrix.
//
// Note  These calls rely on the following inline shortcut function:
//   inline DWORD F2DW( FLOAT f ) { return *((DWORD*)&f); }
d3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVMAT00, F2DW(1.0f) );
d3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVMAT01, F2DW(0.0f) );
d3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVMAT10, F2DW(0.0f) );
d3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVMAT11, F2DW(1.0f) );

If you set the bump mapping operation to include luminance (D3DTOP_BUMPENVMAPLUMINANCE), you must set the luminance controls. The luminance controls configure how the system computes luminance before modulating the color from the texture in the next stage. For details, see Bump Mapping Formulas.

// Set luminance controls. This is only needed when using
// a bump map that contains luminance, and when the
// D3DTOP_BUMPENVMAPLUMINANCE texture blending operation is
// being used.
//
// Note  These calls rely on the following inline shortcut function:
//   inline DWORD F2DW( FLOAT f ) { return *((DWORD*)&f); }
d3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVLSCALE, F2DW(0.5f) );
d3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVLOFFSET, F2DW(0.0f) );

After your application configures bump mapping parameters, it can render as normal, and the rendered polygons receive bump mapping effects.

Note that the preceding example shows parameters set for specular environment mapping. When performing diffuse light mapping, applications set the texture blending operation for the last stage to D3DTOP_MODULATE. For more information, see Diffuse Light Maps.


Environment Mapping
Microsoft DirectX 9.0 SDK Update (October 2004)

Environment Mapping

Environment mapping is a technique that simulates highly reflective surfaces without using ray tracing. In practice, environment mapping applies a special texture map that contains an image of the scene surrounding an object to the object itself. The result approximates the appearance of a reflective surface, close enough to fool the eye, without incurring any of the complex computations involved in ray tracing.

The following image demonstrates a type of environment mapping called spherical environment mapping. For details, see Spherical Environment Mapping.

Teapot image with applied texture that simulates reflection of the surroundings

The teapot in this image appears to reflect its surroundings; this is actually a texture being applied to the object. Because environment mapping uses a texture, combined with specially computed texture coordinates, it can be performed in real-time.

This section provides information about performing two common types of environment mapping with Microsoft Direct3D. There are many types of environment mapping in use throughout the graphics industry, but the following topics target the two most common forms: cubic environment mapping and spherical environment mapping.

  • Cubic Environment Mapping
  • Spherical Environment Mapping


Cubic Environment Mapping
Microsoft DirectX 9.0 SDK Update (October 2004)

Cubic Environment Mapping

Cubic environment maps—sometimes referred to as cube maps—are textures that contain image data representing the scene surrounding an object, as if the object were in the center of a cube. Each face of the cubic environment map covers a 90-degree field of view in the horizontal and vertical, and there are six faces per cube map. The orientation of the faces is given in the following illustration.

Cube with central coordinate axes perpendicular to cube faces

Each face of the cube is oriented perpendicular to the x/y, y/z, or x/z plane, in world space. The following figure shows how each plane corresponds to a face.

Faces of cube with coordinate projections on each face

Cubic environment maps are implemented as a series of texture objects. Applications can use static images for cubic environment mapping, or they can render into the faces of the cube map to perform dynamic environment mapping. This technique requires that the cube-map surfaces be valid render-target surfaces, created with the D3DUSAGE_RENDERTARGET flag set.

The faces of a cube map don't need to contain extremely detailed renderings of the surrounding scene. In most cases, environment maps are applied to curved surfaces. Given the amount of curvature used by most applications, the resulting reflective distortion makes extreme detail in the environment map wasteful in terms of memory and rendering overhead.

Mipmapped Cubic Environment Maps

Cube maps can be mipmapped. To create a mipmapped cube map, set the Levels parameter of the IDirect3DDevice9::CreateCubeTexture method to the number of levels that you want. You can envision the topography of these surfaces as shown in the following graphic.

Mipmapped cube map with n mip levels

Applications that create mipmapped cubic environment maps can access each face by calling the IDirect3DCubeTexture9::GetCubeMapSurface method. Start by setting the appropriate value from the D3DCUBEMAP_FACES enumerated type, as discussed in Creating Cubic Environment Map Surfaces. Next, select the level to retrieve by setting the IDirect3DCubeTexture9::GetCubeMapSurface level parameter to the mipmap level that you want. Remember that 0 corresponds with the top-level image.

Texture Coordinates for Cubic Environment Maps

Texture coordinates that index a cubic environment map aren't simple u, v style coordinates, as used when standard textures are applied. In fact, cubic environment maps don't use texture coordinates at all. In place of a set of texture coordinates, cubic environment maps require a 3-D vector. You must take care to specify a proper vertex format. In addition to telling the system how many sets of texture coordinates your application uses, you must provide information about how many elements are in each set. Microsoft Direct3D offers the D3DFVF_TEXCOORDSIZEn set of macros for this purpose. These macros accept a single parameter, identifying the index of the texture coordinate set for which the size is being described. In the case of a 3-D vector, you include the bit pattern created by the D3DFVF_TEXCOORDSIZE3 macro. The following code example shows how this macro is used.

// Create a flexible vertex format descriptor for a vertex that contains
//   a position, normal, and one set of 3-D texture coordinates.

DWORD dwFVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1 | D3DFVF_TEXCOORDSIZE3(0);

In some cases, such as diffuse light mapping, you use the camera-space vertex normal for the vector. In other cases, like specular environment mapping, you use a reflection vector. Because transformed vertex normals are widely understood, the information here concentrates on computing a reflection vector.

Computing a reflection vector on your own requires understanding of the position of each vertex, and of a vector from the viewpoint to that vertex. Direct3D can automatically compute the reflection vectors for your geometry. Using this feature saves memory because you don't need to include texture coordinates for the environment map. It also reduces bandwidth and, in the case of a TnLHAL Device, it can be significantly faster than the computations that your application can make on its own. To use this feature, in the texture stage that contains the cubic environment map, set the D3DTSS_TEXCOORDINDEX texture stage state to a combination of the D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR member of D3DTEXTURESTAGESTATETYPE and the index of a texture coordinate set. In some situations, like diffuse light mapping, you might use the D3DTSS_TCI_CAMERASPACENORMAL member of D3DTEXTURESTAGESTATETYPE, which causes the system to use the transformed, camera-space, vertex normal as the addressing vector for the texture. The index is only used by the system to determine the wrapping mode for the texture.

The following code example shows how this value is used.

// The m_d3dDevice variable is a valid pointer
// to an IDirect3DDevice9 interface.

// Automatically generate texture coordinates for stage 2.
// This assumes that stage 2 is assigned a cube map.
// Use the wrap mode from the texture coordinate set at index 1.

m_d3dDevice->SetTextureStageState( 2, D3DTSS_TEXCOORDINDEX,
                                   D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR | 1);

When you enable automatic texture coordinate generation, the system uses one of two formulas to compute the reflection vector for each vertex. When the D3DRS_LOCALVIEWER render state is set to TRUE, the formula used is the following:

R = 2(ExN)N-E

In the preceding formula, R is the reflection vector being computed, E is the normalized position-to-eye vector, and N is the camera-space vertex normal.

When the D3DRS_LOCALVIEWER render state is set to FALSE, the system uses the following formula.

R = 2NzN-I

The R and N elements in this formula are identical to the previous formula. The NZ element is the world-space z of the vertex normal, and I is the vector (0,0,1) of an infinitely distant viewpoint. The system uses the reflection vector from either formula to select and address the appropriate face of the cube map.

Note In most cases, applications should enable automatic normalization of vertex normals. To do this, set D3DRS_NORMALIZENORMALS to TRUE. If you do not enable this render state, the appearance of the environment map will be drastically different than you might expect.

Additional information is contained in the following topic.

  • Creating Cubic Environment Map Surfaces


Creating Cubic Environment Map Surfaces
Microsoft DirectX 9.0 SDK Update (October 2004)

Creating Cubic Environment Map Surfaces

You create a cubic environment map texture by calling the IDirect3DDevice9::CreateCubeTexture method. Cubic environment map textures must be square, with dimensions that are a power of two.

The following code example shows how your C++ application might create a simple cubic environment map.

// Init m_d3dDevice to point to an IDirect3DDevice9 interface

LPDIRECT3DCUBETEXTURE9 m_pCubeMap;

m_d3dDevice->CreateCubeTexture(256, 1, D3DUSAGE_RENDERTARGET, D3DFMT_R8G8B8,
                                D3DPOOL_DEFAULT, &m_pCubeMap);

Accessing Cubic Environment Map Faces

You can navigate between faces of a cubic environment map by using the IDirect3DCubeTexture9::GetCubeMapSurface method.

The following code example uses IDirect3DCubeTexture9::GetCubeMapSurface to retrieve the cube-map surface used for the positive y-face (face 2).

// Init m_pCubeMap to point to an IDirect3DCubeTexture9 interface

LPDIRECT3DSURFACE9 pFace2;
m_pCubeMap->GetCubeMapSurface(D3DCUBEMAP_FACE_POSITIVE_Y, 0, &pFace2);

The first parameter that IDirect3DCubeTexture9::GetCubeMapSurface accepts is a D3DCUBEMAP_FACES enumerated value that describes the attached surface that the method should retrieve. The second parameter tells Microsoft Direct3D which level of a mipmapped cube texture to retrieve. The third parameter accepted is the address of the IDirect3DSurface9 interface, representing the returned cube texture surface. Because this cube-map is not mipmapped, 0 is used here.

Note

After calling this method, the internal reference count on the IDirect3DSurface9 interface is increased. When you are done using this surface, be sure to call the IUnknown::Release method on this IDirect3DSurface9 interface or you will have a memory leak.

Rendering to Cubic Environment Maps

You can copy images to the individual faces of the cube map just like you would any other texture or surface object. The most important thing to do before rendering to a face is set the transformation matrices so that the camera is positioned properly and points in the proper direction for that face: forward (+z), backward (-z), left (-x), right (+x), up (+y), or down (-y).

The following C++ code example prepares and sets a view matrix according to the face being rendered.

// Init pCubeMap to point to an IDirect3DCubeTexture9 interface
// Init d3dDevice to point to an IDirect3DDevice9 interface

void RenderFaces()
{
    // Save transformation matrices of the device
    D3DXMATRIX matProjSave, matViewSave;
    d3dDevice->GetTransform(D3DTS_VIEW,       &matViewSave ;
    d3dDevice->GetTransform(D3DTS_PROJECTION, &matProjSave);

    // Store the current back buffer and z-buffer
    LPDIRECT3DSURFACE9 pBackBuffer, pZBuffer;
    d3dDevice->GetRenderTarget(&pBackBuffer);
    d3dDevice->GetDepthStencilSurface(&pZBuffer);

Remember, each face of a cubic environment map represents a 90-degree field of view. Unless your application requires a different field of view angle—for special effects, for example—take care to set the projection matrix accordingly.

This code example creates and sets a projection matrix for the most common case.

    // Use 90-degree field of view in the projection
    D3DMATRIX matProj;
    D3DXMatrixPerspectiveFovLH(matProj, D3DX_PI/2, 1.0f, 0.5f, 1000.0f);
    d3dDevice->SetTransform(D3DTS_PROJECTION, &matProj);

    // Loop through the six faces of the cube map
    for(DWORD i=0; i<6; i++)
    {
        // Standard view that will be overridden below
        D3DVECTOR vEnvEyePt = D3DVECTOR(0.0f, 0.0f, 0.0f);
        D3DVECTOR vLookatPt, vUpVec;

        switch(i)
        {
            case D3DCUBEMAP_FACE_POSITIVE_X:
                vLookatPt = D3DVECTOR(1.0f, 0.0f, 0.0f);
                vUpVec    = D3DVECTOR(0.0f, 1.0f, 0.0f);
                break;
            case D3DCUBEMAP_FACE_NEGATIVE_X:
                vLookatPt = D3DVECTOR(-1.0f, 0.0f, 0.0f);
                vUpVec    = D3DVECTOR( 0.0f, 1.0f, 0.0f);
                break;
            case D3DCUBEMAP_FACE_POSITIVE_Y:
                vLookatPt = D3DVECTOR(0.0f, 1.0f, 0.0f);
                vUpVec    = D3DVECTOR(0.0f, 0.0f,-1.0f);
                break;
            case D3DCUBEMAP_FACE_NEGATIVE_Y:
                vLookatPt = D3DVECTOR(0.0f,-1.0f, 0.0f);
                vUpVec    = D3DVECTOR(0.0f, 0.0f, 1.0f);
                break;
            case D3DCUBEMAP_FACE_POSITIVE_Z:
                vLookatPt = D3DVECTOR( 0.0f, 0.0f, 1.0f);
                vUpVec    = D3DVECTOR( 0.0f, 1.0f, 0.0f);
                break;
            case D3DCUBEMAP_FACE_NEGATIVE_Z:
                vLookatPt = D3DVECTOR(0.0f, 0.0f,-1.0f);
                vUpVec    = D3DVECTOR(0.0f, 1.0f, 0.0f);
                break;
        }

         D3DMATRIX matView;
         D3DXMatrixLookAtLH(matView, vEnvEyePt, vLookatPt, vUpVec);
         d3dDevice->SetTransform(D3DTS_VIEW, &matView);

When the camera is in position and the projection matrix set, you can render the scene. Each object in the scene should be positioned as you would normally position them. The following code example, provided for completeness, outlines this task.

        // Get pointer to surface in order to render to it
        LPDIRECT3DSURFACE9 pFace;
        pCubeMap->GetCubeMapSurface((D3DCUBEMAP_FACES)i, 0, &pFace);
        d3dDevice->SetRenderTarget (pFace , pZBuffer);
        SAFE_RELEASE(pFace);

        d3dDevice->BeginScene();
        // Render scene here
        ...
        d3dDevice->EndScene();
    }

    // Change the render target back to the main back buffer.
    d3dDevice->SetRenderTarget(pBackBuffer, pZBuffer);
    SAFE_RELEASE(pBackBuffer);
    SAFE_RELEASE(pZBuffer);

    // Restore the original transformation matrices
    d3dDevice->SetTransform(D3DTS_VIEW,       &matViewSave);
    d3dDevice->SetTransform(D3DTS_PROJECTION, &matProjSave);
}

Note the call to the IDirect3DDevice9::SetRenderTarget method. When rendering to the cube map faces, you must assign the face as the current render-target surface. Applications that use depth buffers can explicitly create a depth-buffer for the render-target, or reassign an existing depth-buffer to the render-target surface. The code sample above uses the latter approach.


Spherical Environment Mapping
Microsoft DirectX 9.0 SDK Update (October 2004)

Spherical Environment Mapping

Spherical environment maps, or sphere maps, are special textures that contain an image of the scene surrounding an object, or the lighting effects around the object. Unlike cubic environment maps, sphere maps don't directly represent an object's surroundings. The teapot image in Environment Mapping topic shows the reflection effects you can achieve with sphere mapping. A sphere map is a 2-D representation of the full 360-degree view of the scene surrounding of an object, as if taken through a fish-eye lens.

Sphere map of the inside of a building

Texture Coordinates for Spherical Environment Maps

The texture coordinates that you specify for each vertex receiving an environment mapping should address the texture as a function of the reflective distortion created by the curvature of the surface. Applications must compute these texture coordinates for each vertex to achieve the desired effect. One simple and effective way to generate texture coordinates uses the vertex normal as input. Although several methods exist, the following formula is common among applications that perform environment mapping with sphere maps.

Formula for computing texture coordinates for a sphere map

In these formulas, u and v are the texture coordinates being computed, and NX and NY are the x and y components of the camera-space vertex normal. The formula is simple but effective. If the normal has a positive x component, the normal points to the right, and the u coordinate is adjusted to address the texture appropriately. Likewise for the v coordinate: positive y indicates that the normal points up. The opposite is true for negative values in each component.

If the normal points directly at the camera, the resulting coordinates should receive no distortion. The +0.5 bias to both coordinates places the point of zero-distortion at the center of the sphere map, and a vertex normal of (0, 0, z) addresses this point. This formula doesn't account for the z component of the normal, but applications that use the formula can optimize computations by skipping vertices with a normal that has a positive z element. This works for flat-shaded objects because, in camera space, if the normal points away from the camera (positive z), the vertex is culled when the object is rendered. For Gouraud-shaded objects, a normal can point away from the camera (positive x), and the triangle containing the vertex can still be visible. If you don't compute u and v for this vertex, the face might still be used, resulting in unexpected behavior.

Applying Spherical Environment Maps

You apply an environment map to objects in the same manner as for any other texture, by setting the texture to the appropriate texture stage with the IDirect3DDevice9::SetTexture method. Set the first parameter to the index for the desired texture stage, and set the second parameter to the address of the IDirect3DDevice9 interface returned when you created the texture for the environment map. You can set the color and alpha blending operations and arguments as needed to achieve the desired texture blending effects.


Antialiasing
Microsoft DirectX 9.0 SDK Update (October 2004)

Antialiasing

Antialiasing is a technique you can use to reduce the appearance of stair-step pixels when drawing any line that is not exactly horizontal or vertical. In three-dimensional scenes, this artifact is most noticeable on the boundaries between polygons of different colors. Antialiasing effectively blends the pixels at these boundaries to produce a more natural look to the scene.

  • Full-Scene Antialiasing
  • Motion Blur


Full-Scene Antialiasing
Microsoft DirectX 9.0 SDK Update (October 2004)

Full-Scene Antialiasing

Full-scene antialiasing refers to blurring the edges of each polygon in the scene as it is rasterized in a single pass; no second pass is required. Full-scene antialiasing, when supported, affects only triangles and groups of triangles. Lines cannot be antialiased by using Microsoft Direct3D services. Full-scene antialiasing is done in Direct3D by using multisampling on each pixel. When multisampling is enabled, all subsamples of a pixel are updated in one pass but when used for other effects that involve multiple rendering passes, the application can specify that only some subsamples are to be affected by a given rendering pass. This latter approach enables simulation of motion blur, depth-of-field focus effects, reflection blur, and so on.

In both cases, the various samples recorded for each pixel are blended together and output to the screen. This enables the improved image quality of antialiasing or other effects.

Before creating a device with the IDirect3D9::CreateDevice method, you need to determine if full-scene antialiasing is supported. Do this by calling the IDirect3D9::CheckDeviceMultiSampleType method as shown in the code example below.

/*
 * The code below assumes that pD3D is a valid pointer
 *   to a IDirect3D9 interface.
 */

if( SUCCEEDED(pD3D->CheckDeviceMultiSampleType( D3DADAPTER_DEFAULT,
                     D3DDEVTYPE_HAL , D3DFMT_R8G8B8, FALSE,
                     D3DMULTISAMPLE_2_SAMPLES, NULL ) ) )
// Full-scene antialiasing is supported. Enable it here.

The first parameter that IDirect3D9::CheckDeviceMultiSampleType accepts is an ordinal number that denotes the display adapter to query. This sample uses D3DADAPTER_DEFAULT to specify the primary display adapter. The second parameter is a value from the D3DDEVTYPE enumerated type, specifying the device type. The third parameter specifies the format of the surface. The fourth parameter tells Direct3D whether to inquire about full-windowed multisampling (TRUE) or full-scene antialiasing (FALSE). This sample uses FALSE to tell Direct3D that it is inquiring about full-scene antialiasing. The last parameter specifies the multisampling technique that you want to test. Use a value from the D3DMULTISAMPLE_TYPE enumerated type. This sample tests to see if two levels of multisampling are supported.

If the device supports the level of multisampling that you want to use, the next step is to set the presentation parameters by filling in the appropriate members of the D3DPRESENT_PARAMETERS structure to create a multisample rendering surface. After that, you can create the device. The sample code below shows how to set up a device with a multisampling render surface.

/*
 * The example below assumes that pD3D is a valid pointer
 * to a IDirect3D9 interface, d3dDevice is a pointer to a
 * IDirect3DDevice9 interface, and hWnd is a valid handle
 * to a window.
 */

D3DPRESENT_PARAMETER d3dPP
ZeroMemory( &d3dPP, sizeof( d3dPP ) );
d3dPP.Windowed        = FALSE
d3dPP.SwapEffect      = D3DSWAPEFFECT_DISCARD;
d3dPP.MultiSampleType = D3DMULTISAMPLE_2_SAMPLES;
pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                   D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                   &d3dpp, &d3dDevice)

To use multisampling, the SwapEffect member of D3DPRESENT_PARAMETER must be set to D3DSWAPEFFECT_DISCARD.

The last step is to enable multisampling antialiasing by calling the IDirect3DDevice9::SetRenderState method and setting the D3DRS_MULTISAMPLEANTIALIAS to TRUE. After setting this value to TRUE, any rendering that you do will have multisampling applied to it. You might want to enable and disable multisampling, depending on what you are rendering.


Motion Blur
Microsoft DirectX 9.0 SDK Update (October 2004)

Motion Blur

You can enhance the perceived speed of an object in a 3-D scene by blurring the object and leaving a blurred trail of object images behind the object. Microsoft Direct3D applications accomplish this by rendering the object multiple times per frame.

Recall that Direct3D applications typically render scenes into an off-screen buffer. The contents of the buffer are displayed on the screen when the application calls the IDirect3DDevice9::Present method. Your Direct3D application can render the object multiple times into a scene before it displays the frame on the screen.

Programmatically, your application makes multiple calls to a DrawPrimitive method, repeatedly passing the same 3-D object. Before each call, the position of the object is updated slightly, producing a series of blurred object images on the target rendering surface. If the object has one or more textures, your application can enhance the motion blur effect by rendering the first image of the object with all its textures nearly transparent. Each time the object renders, the transparency of the object's texture decreases. When your application renders the object in its final position, it should render the object's textures without transparency. The exception is if you're adding motion blur to another effect that requires texture transparency. In any case, the initial image of the object in the frame should be the most transparent. The final image should be the least transparent.

After your application renders the series of object images onto the target rendering surface and renders the rest of the scene, it should call the IDirect3DDevice9::Present method to display the frame on the screen.

If your application is simulating the effect of the user moving through a scene at high speed, it can add motion blur to the entire scene. In this case, your application renders the entire scene multiple times per frame. Each time the scene renders, your application must move the viewpoint slightly. If the scene is highly complex, the user may see a visible performance degradation as acceleration is increased because of the increasing number of scene renderings per frame.


Multiple Render Targets
Microsoft DirectX 9.0 SDK Update (October 2004)

Multiple Render Targets

Many implementations support a less restrictive form of multiple render targets. The biggest relaxation is the ability to have multiple render targets that can be created independently. These render targets must be of identical dimensions but can have different formats. The pipeline supports a single render target that can be set using IDirect3DDevice9::SetRenderTarget. This has been extended to allow multiple render targets to be simultaneously present in the device. A new cap expresses this ability.

Multiple render targets have the following restrictions:

  • Some implementations might require all surfaces of multiple render targets to have the same bit depth but allow different formats. Implementations that do not have this limitation indicate so by setting the cap D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS.

    If the D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS cap is set, the device can support all mixed formats regardless of format type or bit depth. If the D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS cap is not set, the device can support mixed format types for surfaces containing the same bit depth above 16 bits. The mixing of different format types for 16-bit depth surfaces is undefined.

  • All surfaces of a multiple render target should have the same width and height.
  • Some implementations cannot perform post-pixel shader operations on multiple render targets, including: no dithering, alpha test, no fogging, no blending or masking, except the z-test and stencil test. Devices that can support post-pixel shader operations set the cap bit to D3DPMISCCAPS_MRTPOSTPIXELSHADERBLENDING. When the D3DPMISCCAPS_MRTPOSTPIXELSHADERBLENDING cap is not set, the device is expected to turn off all post-pixel shader blending operations, regardless of what the specific surface IDirect3D9::CheckDeviceFormat with USAGE_QUERY_POSTPIXELSHADER_BLENDING is.

    When the D3DPMISCCAPS_MRTPOSTPIXELSHADERBLENDING cap is set, you must first consult the IDirect3D9::CheckDeviceFormat with the USAGE_QUERY_POSTPIXELSHADER_BLENDING result for the specific surface format. If false, no post-pixel shader blending operations will be available for that specific surface format. If true, the device is expected to apply the same state to all simultaneous render targets as follows:

    • Alpha blend: The color value in oCi is blended with the ith render target.
    • Alpha test: Comparison will happen with oC0. If the comparison fails, the pixel test is terminated for all render targets.
    • Fog: Render target 0 will get fogged. Other render targets are undefined. Implementations can choose to fog them all using the same state.
    • Dithering: Undefined.
  • No antialiasing is supported.
  • Some of the implementations do not apply the output write mask (D3DRS_COLORWRITEENABLE). Those that can, have independent color write masks. This is expressed using a new capability bit. The number of independent color write masks available will be equal to the maximum number of elements the device is capable of.
  • IDirect3DDevice9::Clear clears all surfaces of the multiple render target.
Note In the past, this application programming interface (API) was used to set the depth stencil as well. In Microsoft DirectX 9.0 however, this API has been split up as documented in the IDirect3DDevice9::SetRenderTarget and IDirect3DDevice9::SetDepthStencilSurface sections.

New hardware caps:

D3DCAPS9.NumSimultaneousRTs
// The value is 1 for all hardware except those that
//   can support this feature. It is never 0.
D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS - True if the hardware can support it
D3DPMISCCAPS_MRTPOSTPIXELSHADERBLENDING - True if the hardware can support it


Multielement Texture
Microsoft DirectX 9.0 SDK Update (October 2004)

Multielement Texture

Traditional textures are considered to be single-element textures. Multielement textures enable applications to write out to multiple elements of a texture, simultaneously, from the pixel shader. The result in the next rendering pass is that an application can use one or more of the elements as a single-element texture—that is, as inputs to the pixel shader. These additional elements can be thought of as a temporary store for intermediate results that will be used in a later pass by the application. The first generation of hardware that exposes this feature has the following restrictions.

  • All multielement texture surfaces will be allocated automatically. This limitation is addressed by treating this as a new type of surface format with multiple RGBA channels interleaved.
  • All elements of the multielement texture can have the same bit depth. This limitation is expressed by the name of the new surface formats.
  • Multielement texture cannot be the primary/displayable. In other words, it must be off-screen only. This limitation is expressed by the surface-format enumeration.
  • No dithering, alpha test, fogging, blending, raster-op, or masking is allowed. No post-pixel shader processing is done, except the z-test and stencil test.
  • It cannot be a mipmap. Creation of the mip chain will fail.
  • The same element cannot be set as a texture at the same time it is a render target. However, different elements of the same multielement texture surface can simultaneously be textures and render targets.
  • No antialiasing is supported.
  • Multielement texture surfaces, when used as a texture, cannot be filtered. This limitation can be verified using IDirect3D9::CheckDeviceFormat.
  • Multielement texture surfaces cannot be locked.
  • Multiple multielement texture surfaces can be used simultaneously, by assigning each to various stages, like normal textures.
  • Multielement texture surfaces support gamma 2.2 -> 1.0 conversion on read, just like other texture formats.
  • Some of the implementations do not apply the output write mask (D3DRS_COLORWRITEENABLE). Those that can, have independent color write masks. This is expressed using a new capability bit. The number of independent color write masks available will be equal to the maximum number of elements the device is capable of.
  • IDirect3DDevice9::Clear clears all elements of the multielement texture, set as the render target.

The usage is documented in the following list.

  • Applications discover support for this feature by checking for the availability of multielement texture formats.
  • The application creates these surfaces by calling IDirect3DDevice9::CreateTexture.
  • The application sets the surface as a render target using the IDirect3DDevice9::SetRenderTarget call. The pixel shader outputs to the surfaces using the mov instruction.
  • IDirect3DDevice9::SetTexture is called to set a multielement texture surface to a particular stage. Like other textures, the same surface is allowed to be set to multiple stages at once.
  • IDirect3DDevice9::SetSamplerState is called to set D3DSAMP_ELEMENTINDEX to the appropriate element number in the multielement texture that the sampler samples from. Default value for this state is 0, which means non-multielement textures will work. Setting this state to an inappropriate number results in an undefined behavior. For example, if the multielement texture is only two elements wide but the sampler is asked to sample from the fourth element.

API Changes

The following are the proposed application programming interface (API) changes to support this feature. New surface formats like the ones shown here express the interleaved nature of the format.

A new interleaved surface format:

D3DFMT_MULTI2_ARGB8    = MAKEFOURCC('M','E','T','1'),

A new sampler state to indicate which element to pick up:

D3DSAMP_ELEMENTINDEX

New render states:

D3DRS_COLORWRITEENABLE1
D3DRS_COLORWRITEENABLE2
D3DRS_COLORWRITEENABLE3

D3DRS_COLORWRITEENABLE applies to render target (or element) zero.

New hardware caps:

D3DPMISCCAPS_INDEPENDENTWRITEMASKS // True if they can support it


Frame Buffer
Microsoft DirectX 9.0 SDK Update (October 2004)

Frame Buffer

  • Fog Types
  • Alpha Examples
  • Gamma


Fog Types
Microsoft DirectX 9.0 SDK Update (October 2004)

Fog Types

There are two ways to add fog to a scene: with pixel fog and/or vertex fog. The following topics illustrate the formulas used in fog equations, as well as implementing vertex and pixel fog. An application can implement fog with a vertex shader, and pixel fog simultaneously if desired.

  • Fog Formulas
  • Fog Parameters
  • Fog Blending
  • Fog Color
  • Vertex Fog
  • Pixel Fog

Fog blending is controlled by render states; it is not part of the programmable pixel pipeline.


Fog Formulas
Microsoft DirectX 9.0 SDK Update (October 2004)

Fog Formulas

C++ applications can control how fog affects the color of objects in a scene by changing how Microsoft Direct3D computes fog effects over distance. The D3DFOGMODE enumerated type contains members that identify the three fog formulas. All formulas calculate a fog factor as a function of distance, given parameters that your application sets.

Linear Fog

This is set with D3DFOG_LINEAR.

Direct3D linear fog equation

where

  • start is the distance at which fog effects begin.
  • end is the distance at which fog effects no longer increase.
  • d represents depth, or the distance from the viewpoint. For range based fog, the value for d is the distance between the camera position and a vertex. For non-range based fog, the value for d is the absolute value of the Z-coordinate in camera space.

Exponential Fog

Linear and exponential formulas are supported for both pixel fog and vertex fog.

This is set with D3DFOG_EXP.

Direct3D exponential fog equation

where

  • e is the base of natural logarithms (approximately 2.71828).
  • density is an arbitrary fog density that can range from 0.0 to 1.0.
  • d represents depth, or the distance from the viewpoint, as stated earlier.

This is set with D3DFOG_EXP2.

Direct3D exponential fog equation

where

  • e is the base of natural logarithms as stated above.
  • density is an arbitrary fog density that can range from 0.0 to 1.0 as stated above.
  • d represents depth, or the distance from the viewpoint, as stated above.
Note The system stores the fog factor in the alpha component of the specular color for a vertex. If your application performs its own transformation and lighting, you can insert fog factor values manually, to be applied by the system during rendering.

The following illustration graphs these formulas, using common values as in the formula parameters.

D3DFOG_LINEAR is 1.0 at start and 0.0 at end. It is not measured relative to the near or far planes.

When Direct3D calculates fog effects, it uses the fog factor from one of the preceding equations in a blending formula, shown here.

This formula effectively scales the color of the current polygon C by the fog factor f, and adds the product to the fog color C, scaled by the bitwise inverse of the fog factor. The resulting color value is a blend of the fog color and the original color, as a factor of distance. The formula applies to all devices supported in Microsoft DirectX 7.0 and later. For the legacy ramp device, the fog factor scales the diffuse and specular color components, clamped to the range of 0.0 and 1.0, inclusive. The fog factor typically starts at 1.0 for the near plane and decreases to 0.0 at the far plane.


Fog Parameters
Microsoft DirectX 9.0 SDK Update (October 2004)

Fog Parameters

Fog parameters are controlled through device render states. Both pixel and vertex fog types support all the fog formulas introduced in Fog Formulas. The D3DFOGMODE enumerated type defines constants that you can use to identify the fog formula you want Microsoft Direct3D to use. The D3DRS_FOGTABLEMODE render state controls the fog mode that Direct3D uses for pixel fog, and the D3DRS_FOGVERTEXMODE render state controls the mode for vertex fog.

When using the linear fog formula, you set the starting and ending distances through the D3DRS_FOGSTART and D3DRS_FOGEND render states. How the system interprets these values depends on the type of fog your application uses—pixel or vertex fog—and, when using pixel fog, if z-based or w-based depth is being used. The following table summarizes fog types and their start and end units.

Fog type | Fog start/end units
Pixel (Z) | Device space [0.0,1.0]
Pixel (W) | Camera space
Vertex | Camera space

The D3DRS_FOGDENSITY render state controls the fog density applied when an exponential fog formula is enabled. Fog density is essentially a weighting factor, ranging from 0.0 to 1.0 (inclusive), that scales the distance value in the exponent.

The color that the system uses for fog blending is controlled through the D3DRS_FOGCOLOR device render state. For more information, see Fog Color and Fog Blending.


Fog Blending
Microsoft DirectX 9.0 SDK Update (October 2004)

Fog Blending

Fog blending refers to the application of the fog factor to the fog and object colors to produce the final color that appears in a scene, as discussed in Fog Formulas. The D3DRS_FOGENABLE render state controls fog blending. Set this render state to TRUE to enable fog blending as shown in the following example code. The default is FALSE.

// For this example, g_pDevice is a valid pointer
// to an IDirect3DDevice9 interface.
HRESULT hr;
hr = g_pDevice->SetRenderState(
                     D3DRS_FOGENABLE,
                     TRUE);
if FAILED(hr)
    return hr;

You must enable fog blending for both pixel fog and vertex fog. For information about using these types of fog, see Pixel Fog and Vertex Fog.


Fog Color
Microsoft DirectX 9.0 SDK Update (October 2004)

Fog Color

Fog color for both pixel and vertex fog is set through the D3DRS_FOGCOLOR render state. The render state values can be any RGB color, specified as an RGBA color. The alpha component is ignored.

The following C++ example sets the fog color to white.

/* For this example, the d3dDevice variable is
 * a valid pointer to an IDirect3DDevice9 interface.
 */
HRESULT hr;
hr = d3dDevice->SetRenderState(
                    D3DRS_FOGCOLOR,
                    0x00FFFFFF); // Highest 8 bits are not used.
if(FAILED(hr))
    return hr;

Fog is applied differently by the fixed function pipeline and the programmable pipeline.

  1. If the driver supports D3DPMISCCAPS_FOGANDSPECULARALPHA:
    • If the fixed function pipeline is used and D3DRS_FOGCOLOR is set, v1.w (in the pixel shader) equals the value set in fog renderstate.
    • If the programmable pipeline is used, then v1.w (in the pixel shader) equals 0, even if oD1.w is explicitly written in a vertex shader.
  2. If the driver does NOT support D3DPMISCCAPS_FOGANDSPECULARALPHA:
    • If the fixed function pipeline is used and D3DRS_FOGCOLOR is set, then v1.w (in the pixel shader) equals value set in fog renderstate.
    • If oFog is explicitly written in a vertex shader, v1.w (in the pixel shader) equals oFog, clamped between 0 and 1.
    • If neither of the above two cases applies, v1.w (in the pixel shader) equals 0, even if oD1.w is explicitly written in a vertex shader.

For more information, see D3DPMISCCAPS.


Vertex Fog
Microsoft DirectX 9.0 SDK Update (October 2004)

Vertex Fog

When the system performs vertex fogging, it applies fog calculations at each vertex in a polygon, and then interpolates the results across the face of the polygon during rasterization. Vertex fog effects are computed by the Microsoft Direct3D lighting and transformation engine. For more information, see Fog Parameters.

If your application does not use Direct3D for transformation and lighting, the application must perform fog calculations. In this case, place the fog factor that is computed in the alpha component of the specular color for each vertex. You are free to use whatever formulas you want—range-based, volumetric, or otherwise. Direct3D uses the supplied fog factor to interpolate across the face of each polygon. Applications that perform their own transformation and lighting must also perform their own vertex fog calculations. As a result, such an application need only enable fog blending and set the fog color through the associated render states, as described in Fog Blending and Fog Color.

Note When using a vertex shader, you must use vertex fog. This is accomplished by using the vertex shader to write the per-vertex fog intensity to the oFog register. After the pixel shader completes, the oFog data is used to linearly interpolate with the fog color. This intensity is not available in a pixel shader.

Range-Based Fog

Note Direct3D uses range-based fog calculations only when using vertex fog with the Direct3D transformation and lighting engine. This is because pixel fog is implemented in the device driver, and no hardware currently exists to support per-pixel range-based fog. If your application performs its own transformation and lighting, it must perform its own fog calculations, range-based or otherwise.

Sometimes, using fog can introduce graphic artifacts that cause objects to be blended with the fog color in nonintuitive ways. For example, imagine a scene in which there are two visible objects: one distant enough to be affected by fog, and the other near enough to be unaffected. If the viewing area rotates in place, the apparent fog effects can change, even if the objects are stationary. The following illustration shows a top-down view of such a situation.

Effects on fog of changing the viewpoint

Range-based fog is another, more accurate, way to determine the fog effects. In range-based fog, Direct3D uses the actual distance from the viewpoint to a vertex for its fog calculations. Direct3D increases the effect of fog as the distance between the two points increases, rather than the depth of the vertex within in the scene, thereby avoiding rotational artifacts.

If the current device supports range-based fog, it will set the D3DPRASTERCAPS_FOGRANGE value in the RasterCaps member of D3DCAPS9 when you call the IDirect3DDevice9::GetDeviceCaps method. To enable range-based fog, set the D3DRS_RANGEFOGENABLE render state to TRUE.

Range-based fog is computed by Direct3D during transformation and lighting. Applications that don't use the Direct3D transformation and lighting engine must also perform their own vertex fog calculations. In this case, provide the range-based fog factor in the alpha component of the specular component for each vertex.

Using Vertex Fog

Use the following steps to enable vertex fog in your application.

  1. Enable fog blending by setting D3DRS_FOGENABLE to TRUE.
  2. Set the fog color in the D3DRS_FOGCOLOR render state.
  3. Choose the desired fog formula by setting the D3DRS_FOGVERTEXMODE render state to a member of the D3DFOGMODE enumerated type.
  4. Set the fog parameters as desired for the selected fog formula in the render states.

The following example, written in C++, shows what these steps might look like in code.

// For brevity, error values in this example are not checked
//   after each call. A real-world application should check
//   these values appropriately.
//
// For the purposes of this example, g_pDevice is a valid
//   pointer to an IDirect3DDevice9 interface.
void SetupVertexFog(DWORD Color, DWORD Mode, BOOL UseRange, FLOAT Density)
{
    float Start = 0.5f,    // Linear fog distances
          End   = 0.8f;

    // Enable fog blending.
    g_pDevice->SetRenderState(D3DRS_FOGENABLE, TRUE);

    // Set the fog color.
    g_pDevice->SetRenderState(D3DRS_FOGCOLOR, Color);

    // Set fog parameters.
    if(D3DFOG_LINEAR == Mode)
    {
        g_pDevice->SetRenderState(D3DRS_FOGVERTEXMODE, Mode);
        g_pDevice->SetRenderState(D3DRS_FOGSTART, *(DWORD *)(&Start));
        g_pDevice->SetRenderState(D3DRS_FOGEND,   *(DWORD *)(&End));
    }
    else
    {
        g_pDevice->SetRenderState(D3DRS_FOGVERTEXMODE, Mode);
        g_pDevice->SetRenderState(D3DRS_FOGDENSITY, *(DWORD *)(&Density));
    }

    // Enable range-based fog if desired (only supported for
    //   vertex fog). For this example, it is assumed that UseRange
    //   is set to a nonzero value only if the driver exposes the
    //   D3DPRASTERCAPS_FOGRANGE capability.
    // Note: This is slightly more performance intensive
    //   than non-range-based fog.
    if(UseRange)
        g_pDevice->SetRenderState(D3DRS_RANGEFOGENABLE, TRUE);
}

Some fog parameters are required as floating-point values, even though the IDirect3DDevice9::SetRenderState method only accepts DWORD values in the second parameter. This example successfully provides the floating-point values to these methods without data translation by casting the addresses of the floating-point variables as DWORD pointers, and then dereferencing them.


Pixel Fog
Microsoft DirectX 9.0 SDK Update (October 2004)

Pixel Fog

Pixel fog gets its name from the fact that it is calculated on a per-pixel basis in the device driver. This is different from vertex fog, which is computed by the pipeline during transformation and lighting calculations. Pixel fog is sometimes called table fog because some drivers use a precalculated lookup table to determine the fog factor, using the depth of each pixel to apply in blending computations. It can be applied using any fog formula identified by members of the D3DFOGMODE enumerated type. The implementations of these formulas are driver-specific. If a driver doesn't support a complex fog formula, it should degrade to a less complex formula.

Eye-Relative vs. Z-Based Depth

To alleviate fog-related graphic artifacts caused by uneven distribution of z-values in a depth buffer, most hardware devices use eye-relative depth instead of z-based depth values for pixel fog. Eye-relative depth is essentially the w element from a homogeneous coordinate set. Microsoft Direct3D takes the reciprocal of the RHW element from a device space coordinate set to reproduce true w. If a device supports eye-relative fog, it sets the D3DPRASTERCAPS_WFOG flag in the RasterCaps member of the D3DCAPS9 structure when you call the IDirect3DDevice9::GetDeviceCaps method. With the exception of the reference rasterizer, software devices always use z to calculate pixel fog effects.

When eye-relative fog is supported, the system automatically uses eye-relative depth rather than z-based depth if the provided projection matrix produces z-values in world space that are equivalent to w-values in device space. You set the projection matrix by calling the IDirect3DDevice9::SetTransform method, using the D3DTS_PROJECTION value and passing a D3DMATRIX structure that represents the desired matrix. If the projection matrix isn't compliant with this requirement, fog effects are not applied properly. For details about producing a compliant matrix, see A W-Friendly Projection Matrix.

Direct3D uses the currently set projection matrix in its w-based depth calculations. As a result, an application must set a compliant projection matrix to receive the desired w-based features, even if it does not use the Direct3D transformation pipeline.

Direct3D checks the fourth column of the projection matrix. If the coefficients are [0,0,0,1] (for an affine projection) the system will use z-based depth values for fog. In this case, you must also specify the start and end distances for linear fog effects in device space, which ranges from 0.0 at the nearest point to the user, and 1.0 at the farthest point.

Using Pixel Fog

Use the following steps to enable pixel fog in your application.

  1. Enable fog blending by setting the D3DRS_FOGENABLE render state to TRUE.
  2. Set the desired fog color in the D3DRS_FOGCOLOR render state.
  3. Choose the fog formula to use by setting the D3DRS_FOGTABLEMODE render state to the corresponding member of the D3DFOGMODE enumerated type.
  4. Set the fog parameters as desired for the selected fog mode in the associated render states. This includes the start and end distances for linear fog, and fog density for exponential fog mode.

The following example shows what these steps might look like in code.

// For brevity, error values in this example are not checked
//   after each call. A real-world application should check
//   these values appropriately.
//
// For the purposes of this example, g_pDevice is a valid
//   pointer to an IDirect3DDevice9 interface.
void SetupPixelFog(DWORD Color, DWORD Mode)
{
    float Start   = 0.5f;    // For linear mode
    float End     = 0.8f;
    float Density = 0.66f;   // For exponential modes

    // Enable fog blending.
    g_pDevice->SetRenderState(D3DRS_FOGENABLE, TRUE);

    // Set the fog color.
    g_pDevice->SetRenderState(D3DRS_FOGCOLOR, Color);

    // Set fog parameters.
    if( Mode == D3DFOG_LINEAR )
    {
        g_pDevice->SetRenderState(D3DRS_FOGTABLEMODE, Mode);
        g_pDevice->SetRenderState(D3DRS_FOGSTART, *(DWORD *)(&Start));
        g_pDevice->SetRenderState(D3DRS_FOGEND,   *(DWORD *)(&End));
    }
    else
    {
        g_pDevice->SetRenderState(D3DRS_FOGTABLEMODE, Mode);
        g_pDevice->SetRenderState(D3DRS_FOGDENSITY, *(DWORD *)(&Density));
    }

Some fog parameters are required as floating-point values, even though the IDirect3DDevice9::SetRenderState method accepts only DWORD values in the second parameter. The preceding example provides the floating-point values to IDirect3DDevice9::SetRenderState without data translation by casting the addresses of the floating-point variables as DWORD pointers, and then dereferencing them.


Alpha Examples
Microsoft DirectX 9.0 SDK Update (October 2004)

Alpha Examples

Alpha blending is used to display an image that has transparent or semi-transparent pixels. In addition to a red, green, and blue color channel, each pixel in an alpha bitmap has a transparency component known as its alpha channel. The alpha channel typically contains as many bits as a color channel. For example, an 8-bit alpha channel can represent 256 levels of transparency, from 0 (the entire pixel is transparent) to 255 (the entire pixel is opaque). The list below shows some special effects you can create using alpha blending.

  • Billboarding
  • Clouds, Smoke, and Vapor Trails
  • Fire, Flares, and Explosions


Billboarding
Microsoft DirectX 9.0 SDK Update (October 2004)

Billboarding

When creating 3-D scenes, an application can sometimes gain performance advantages by rendering 2-D objects in a way that makes them appear to be 3-D objects. This is the basic idea behind the technique of billboarding.

A billboard in the normal sense of the word is a sign along a roadway. Microsoft Direct3D applications can create and render this type of billboard by defining a rectangular solid and applying a texture to it. Billboarding in the more specialized sense of 3-D graphics is an extension of this. The goal is to make 2-D objects appear to be 3-D. The technique is to apply a texture that contains the object's image to a rectangular primitive. The primitive is rotated so that it always faces the user. It doesn't matter if the object's image is not rectangular. Portions of the billboard can be made transparent, so the parts of the billboard image that you don't want seen are not visible.

Many games employ billboarding for animated sprites. For instance, when the user is moving through a 3-D maze, he or she may see weapons or rewards that can be picked up. These are typically 2-D images textured on a rectangular primitive. Billboarding is often used in games to render images of trees, bushes, and clouds.

When an image is applied to a billboard, the rectangular primitive must first be rotated so that the resulting image faces the user. Your application must then translate it into position. The application can then apply a texture to the primitive.

Billboarding works best for symmetrical objects, especially objects that are symmetrical along the vertical axis. It also requires that the altitude of the viewpoint doesn't increase too much. If the user is allowed to view the billboarded from above, it becomes readily apparent that the object is 2-D rather than 3-D.


Clouds, Smoke, and Vapor Trails
Microsoft DirectX 9.0 SDK Update (October 2004)

Clouds, Smoke, and Vapor Trails

Clouds, smoke, and vapor trails can all be created by an extension of the billboarding technique. See Billboarding. By rotating the billboard on two axes instead of one, your application can enable the user to view a billboard from any angle. Typically, an application rotates the billboard on the horizontal and vertical axes.

To make a simple cloud, your application can rotate a rectangular primitive on one or two axes so that the primitive faces the user. A cloud-like texture can then be applied to the primitive with transparency. For details on applying transparent textures to primitives, see Texture Blending. You can animate the cloud by applying a series of textures over time.

An application can create more complex clouds by forming them from a group of primitives. Each part of the cloud is a rectangular primitive. The primitives can be moved independently over time to give the appearance of a dynamic mist. This concept is illustrated in the following figure.

Formation from a group of primitives

The appearance of smoke is displayed in a manner similar to clouds. It typically requires multiple billboards, like complex clouds. Smoke usually billows and rises over time, so the billboards that make up the smoke plume need to move accordingly. You may need to add more billboards as the plume rises and disperses.

A vapor trail is a smoke plume that doesn't rise. However, like a smoke plume, it disperses over time. The following figure illustrates the technique of using billboards to simulate a vapor trail.


Fire, Flares, and Explosions
Microsoft DirectX 9.0 SDK Update (October 2004)

Fire, Flares, and Explosions

You can use Microsoft Direct3D to simulate natural phenomena involving energy releases. For instance, an application can generate the appearance of fire by applying flame-like textures to a set of billboards. This is especially effective if the application uses a sequence of fire textures to animate the flames on each billboard in the fire. Varying the speed of the animation playback from billboard to billboard increases the appearance of real flames. The semblance of intermingled 3-D flames can be achieved by layering the billboards and the textures on the billboards.

You can simulate flares and flashes by applying successively brighter light maps to all primitives in a scene. Although this is a computationally high-overhead technique, it allows your application to simulate a localized flare or flash. That is, the portion of the scene where the flare or flash originates can brighten first.

Another technique is to position a billboard in front of the scene so that the entire render-target area is covered. The application applies successively whiter textures to the billboard and decreases the transparency over time. The entire scene fades to white as time passes. This is a low overhead method of creating a flare. However, using this technique, it can be difficult to generate the appearance of a bright flash from a single point light source.

Explosions can be displayed in a 3-D scene procedure similar to those used for fire, flashes, and flares. For instance, your application might use a billboard to display a shock wave and rising plume of smoke when the explosion occurs. At the same time, your application can use a set of billboards to simulate flames. In addition, it can position a single billboard in front of the scene to add a flare of light to the entire scene.

Energy beams can be simulated using billboards. Your application can also display them using primitives that are defined as line lists or line strips. For details, see Line Lists and Line Strips.

Your application can create force fields using billboards or primitives defined as triangle lists. To create a force field from triangle lists, define a set of disjoint triangles in a triangle list equally spaced over the region covered by the force field. The gaps between the triangles allow the user to see the scene behind the triangles, as you might expect when looking at a force field. Apply a texture to the triangle list that gives the triangles the appearance of glowing with energy. For further information, see Triangle Lists.


Gamma
Microsoft DirectX 9.0 SDK Update (October 2004)

Gamma

Texture content is often stored in sRGB format. Details of this format can be found at http://www.srgb.com World Wide Web link. Traditionally, pixel pipelines assumed the colors to be linear so blending operations were performed in linear space. However, since sRGB content is gamma corrected, blending operations in linear space will produce incorrect results. Video cards can now fix this problem by undoing the gamma correction when they read any sRGB content, and convert pixel data back to the sRGB format when writing out pixels. In this case, all operations inside the pixel pipeline are performed in the linear space.

Gamma Correction

Microsoft DirectX 9.0 can:

  • Indicate whether a texture is gamma 2.2 corrected or not (sRGB or not). The driver will either convert to a linear gamma for blending operations at SetTexture time, or the sampler will convert it to linear data at lookup time.
  • Indicate whether the pixel pipeline should gamma correct back to sRGB space when writing out to the render target.

All other colors (clear color, material color, vertex color, etc.) are assumed to be in linear space. Applications can gamma-correct the colors written into the frame buffer using pixel shader instructions. The linearization should be applied only to the RGB channels and not to the alpha channel.

Not all surface formats can be linearized. Only the formats that pass IDirect3D9::CheckDeviceFormat with D3DUSAGE_QUERY_SRGBREAD can be linearized. The sampler state D3DSAMP_SRGBTEXTURE is ignored for the rest. Only unsigned texture formats are expected to support this conversion. Unsigned texture formats include only R, G, B, and L components. If the alpha channel is present, it is ignored. If mixed formats support sRGB linearization, only the unsigned channels are affected. Ideally, hardware should perform the linearization before filtering but in DirectX 9.0, hardware is allowed to perform the linearization after filtering.

Not all surface formats can be written in sRGB space. Only the formats that pass the IDirect3D9::CheckDeviceFormat with the usage flag D3DUSAGE_QUERY_SRGBWRITE can be linearized. The render state D3DRS_SRGBWRITEENABLE is ignored for the rest. Eight bits per channel RGB unsigned formats are expected to expose this ability.

Ideally, hardware should perform the frame buffer blending operations in the linear space, but hardware is allowed to perform it after the pixel shader but before the frame buffer blender. This means that the frame buffer blending operations that take place in sRGB space will produce incorrect results. D3DRS_SRGBWRITEENABLE is honored while performing a clear of the render target. For hardware that supports Multiple Render Targets or Multielement Textures, only the first render target or element is written.

API Changes

// New sampler state (DWORD)
// If this is nonzero, the texture is linearized on lookup.
D3DSAMP_SRGBTEXTURE       // Default FALSE

// New render state (DWORD)
D3DRS_SRGBWRITEENABLE     // Default FALSE

// New usage flags
D3DUSAGE_QUERY_SRGBWRITE
D3DUSAGE_QUERY_SRGBREAD

Windowed Swap Chains

It is valuable for applications to keep the back buffers of their swap chains in linear space in order to enable correct blending operations. Since the desktop is typically not in linear space, a gamma correction is required before the contents of the back buffer can be presented. The application can effect this correction itself by allocating an additional buffer and performing its own correcting copy from the linear buffer to the back buffer. This necessitates an extra copy which can be avoided if the driver performs gamma correction as part of the presentation blit.

In DirectX 9.0 a new flag, D3DPRESENT_LINEAR_CONTENT, is available for IDirect3DSwapChain9::Present that allows the presentation to implicitly convert from linear space to sRGB/gamma 2.2.


Precomputed Radiance Transfer
Microsoft DirectX 9.0 SDK Update (October 2004)

Precomputed Radiance Transfer

Using Precomputed Radiance Transfer

There are several forms of complexity present in interesting scenes, including how the lighting environment is modeled (that is, area lighting models versus point/directional ones) and what kind of global effects are modeled (for example, shadows, interreflections, subsurface scattering.) Traditional interactive rendering techniques model a limited amount of this complexity. Precomputed radiance transfer (PRT) enables these effects with some significant restrictions:

  • Objects are assumed to be rigid (that is, no deformations).
  • It is an object-centric approach (unless objects are moved together, these global effects are not maintained between them).
  • Only low-frequency lighting is modeled (resulting in soft shadows.) For high-frequency lights (sharp shadows), traditional techniques would have to be employed.

PRT requires either of the following, but not both:

  • highly-tessellated models and vs_1_1
  • ps_2_0

Standard Diffuse Lighting versus PRT

The following picture is rendered using the traditional (n • l) lighting model. Sharp shadows could be enabled using another pass and some form of shadowing technique (shadow depth maps or shadow volumes). Adding multiple lights would require either multiple passes (if shadows are to be used) or more complex shaders with traditional techniques.

The next picture is rendered with PRT using the best approximation of a single directional light that it can resolve. This results in soft shadows that would be difficult to produce with traditional techniques. Because PRT always models complete lighting environments adding multiple lights or using an environment map, you would only change the values (but not the number) of constants used by the shader.

PRT with Interreflections

Direct lighting reaches the surface directly from the light. Interreflections are light reaching the surface after bouncing off some other surface some number of times. PRT can model this behavior without changing the performance at run time by simply running the simulator with different parameters.

The following image is created using direct PRT only (0 bounces with no interreflections).

This image is created using PRT with interreflections (2 bounces with interreflections).

PRT with Subsurface Scattering

Subsurface scattering is a technique that models how light passes through certain materials. As an example, press a lit flashlight against the palm of your hand. The light from the flashlight passes through your hand, bounces around (changing color in the process), and exits from the other side of your hand. This can also be modeled with simple changes to the simulator and no changes to the runtime.

The following image demonstrates PRT with subsurface scattering.

How PRT Works

The following terms are useful for understanding how PRT works, as illustrated in Figure 1 below.

Source Radiance: The source radiance represents the lighting environment as a whole. In PRT an arbitrary environment is approximated using the spherical harmonic (SH) basis - this lighting is assumed to be distant relative to the object (the same assumption that is made with environment maps.)

Exit Radiance: Exit radiance is the light leaving from a point on the surface from any possible source (reflected radiance, subsurface scattering, emission).

Transfer Vectors: Transfer vectors map Source Radiance into exit radiance and are precomputed offline using a complex light transport simulation.

Figure 1: PRT Conceptual Diagram

PRT factors the rendering process into two stages:

  1. An expensive light transport simulation precomputes transfer coefficients that can be used at run time.
  2. A relatively lightweight run-time stage first approximates the lighting environment using the SH basis, then uses these lighting coefficients and the precomputed transfer coefficients (from stage 1) with a simple shader, resulting in exit radiance (the light leaving the object).

Figure 2: Simplified PRT Data Flow

How to Use the PRT API

  1. Compute the transfer vectors with one of the Compute... methods of ID3DXPRTEngine.

    Directly dealing with these transfer vectors requires a significant amount of memory and shader computation. Compression significantly reduces the amount of memory and shader computation required.

    The final lighting values are calculated in a vertex shader that implements the following compressed rendering equation:

    Where:

    Parameter | Description
    Rp | A single channel of exit radiance at vertex p and is evaluated at every vertex on the mesh.
    Mk | The mean for cluster k. This is an Order2 vector of coefficients.
    k | The cluster identifier (ID) for vertex p.
    L' | The approximation of the source radiance into the SH basis functions. This is an Order2 vector of coefficients.
    j | An integer that sums over the number of PCA vectors.
    wpj | The jth PCA weight for point p. This is a single coefficient.
    Bkj | The jth PCA basis vector for cluster k. This is an Order2 vector of coefficients.

    The Extract... methods of ID3DXPRTCompBuffer provide access to compressed data from the simulation.

  2. Compute the source radiance.

    There are several helper functions in the application programming interface (API) to handle a variety of common lighting scenarios.

    Function | Purpose
    D3DXSHEvalDirectionalLight | Approximates a conventional directional light.
    D3DXSHEvalSphericalLight | Approximates local spherical light sources. (Note that PRT only works with distance lighting environments.)
    D3DXSHEvalConeLight | Approximates a distant area light source. An example would be the sun (very small cone angle).
    D3DXSHEvalHemisphereLight | Evaluates a light that is a linear interpolation between two colors (one on each pole of a sphere).

  3. Compute the exit radiance.

    Equation 1 now has to be evaluated at every point using either a vertex or pixel shader. Before the shader can be evaluated, constants have to be precomputed and loaded into the constant table (see PRTPerVertex Sample for details). The shader itself is a straightforward implementation of this equation.

    struct VS_OUTPUT
{
    float4 Position   : POSITION;   // vertex position
    float2 TextureUV  : TEXCOORD0;  // vertex texture coordinates
    float4 Diffuse    : COLOR0;     // vertex diffuse color
};

VS_OUTPUT Output;
Output.Position = mul(vPos, mWorldViewProjection);

float4 vExitR = float4(0,0,0,0);
float4 vExitG = float4(0,0,0,0);
float4 vExitB = float4(0,0,0,0);

for (int i=0; i < (NUM_PCA_VECTORS/4); i++)
{
   vExitR += vPCAWeights[i] *
       vClusteredPCA[iClusterOffset+i+1+(NUM_PCA_VECTORS/4)*0];
   vExitG += vPCAWeights[i] *
       vClusteredPCA[iClusterOffset+i+1+(NUM_PCA_VECTORS/4)*1];
   vExitB += vPCAWeights[i] *
       vClusteredPCA[iClusterOffset+i+1+(NUM_PCA_VECTORS/4)*2];
}

float4 vExitRadiance = vClusteredPCA[iClusterOffset];
vExitRadiance.r += dot(vExitR,1);
vExitRadiance.g += dot(vExitG,1);
vExitRadiance.b += dot(vExitB,1);

Output.Diffuse = vExitRadiance;

References

For more information about PRT and SH, see the following papers:

Precomputed Radiance Transfer for Real-Time Rendering in Dynamic,
Low-Frequency Lighting Environments
P.-P. Sloan, J. Kautz, J. Snyder
SIGGRAPH 2002

Clustered Principal Components for Precomputed Radiance Transfer
P.-P. Sloan, J. Hall, J. Hart, J. Snyder
SIGGRAPH 2003

Efficient Evaluation of Irradiance Environment Maps
P.-P. Sloan
ShaderX 2,  W. Engel

Spherical Harmonic Lighting: The Gritty Details
R. Green
GDC 2003

An Efficient Representation for Irradiance Environment Maps
R. Ramamoorthi, P. Hanrahan

A Practical Model for Subsurface Light Transport
H. W. Jensen, S. R. Marschner, M. Levoy, and P. Hanrahan
SIGGRAPH 2001

Bi-Scale Radiance Transfer
P.-P. Sloan, X. Liu, H.-Y. Shum, J. Snyder
SIGGRAPH 2003

Fast, Arbitrary BRDF Shading for Low-Frequency Lighting Using Spherical
Harmonics
J. Kautz, P.-P. Sloan, J. Snyder
12th Eurographics Workshop on Rendering

Precomputing Interactive Dynamic Deformable Scenes
D. James, K. Fatahalian
SIGGRAPH 2003

All-Frequency Shadows Using Non-linear Wavelet Lighting Approximation
R. Ng, R. Ramamoorth, P. Hanrahan
SIGGRAPH 2003

Matrix Radiance Transfer
J. Lehtinen, J. Kautz
SIGGRAPH 2003

Math World
E. W. Weisstein, Wolfram Research, Inc.

Quantum Theory of Angular Momentum
D. A. Varshalovich, A.N. Moskalev, V.K. Khersonskii

Related Topics

  • ID3DXPRTBuffer
  • ID3DXPRTCompBuffer
  • ID3DXPRTEngine
  • ID3DXTextureGutterHelper
  • Precomputed Radiance Transfer Functions
  • D3DXSHxxx Functions


PRT Equations
Microsoft DirectX 9.0 SDK Update (October 2004)

PRT Equations

To fully understand a shader that implements precomputed radiance transfer (PRT), it is useful to derive the formula the shader uses to calculate exit radiance.

To start off, the general equation to calculate exit radiance resulting from direct lighting on a diffuse object with arbitrary distant lighting is:

where:

Parameter | Description
Rp | The exit radiance at vertex p. Evaluated at every vertex on the mesh.
pd | The albedo of the surface.
pi | A constant, used as an energy conservation normalization factor.
L(s) | The lighting environment (source radiance).
Vp(s) | A binary visibility function for point p. It is 1 if the point can see the light, 0 if not.
Hnp(s) | The cosine term from Lambert's law. Equal to max((Np • s), 0) where Np is the surface normal at point p.
s | The variable that integrates over the sphere.

Using spherical basis functions, such as spherical harmonics (SH), the formula to approximate the lighting environment is:

where:

Parameter | Description
L(s) | The lighting environment (source radiance).
i | An integer that sums over the number of basis functions.
O | The order of spherical harmonics.
li | A coefficient.
Yi(s) | Some basis function over the sphere.

The collection of these coefficients, L', provides the optimal approximation for function L(s) with the basis functions Y(s). Substituting and distributing yields:

The integral of Yi(s)Vp(s)Hnp(s) is a transfer coefficient tpi that the simulator precomputes for every vertex on the mesh. Substituting this yields:

Changing this to vector notation yields the uncompressed formula to calculate exit radiance for each channel:

where:

Parameter | Description
Rp | The exit radiance at vertex p.
pd | The albedo of the surface.
L' | The vector of li, and is the projection of the source radiance into the SH basis functions. This is an order2 vector of SH coefficients.
Tp | An order2 transfer vector for vertex p. The simulator divides the transfer coefficients by p.

Both of these vectors are an order2 vector of SH coefficients, so notice that this is simply a dot product. Depending on the order, the dot can be expensive so compression can be used. An algorithm called Clustered Principal Component Analysis (CPCA) efficiently compresses the data. This enables the use of a higher-order SH approximation which results in sharper shadows.

CPCA provides this approximation for the transfer vector:

where:

Parameter | Description
Tp | The transfer vector for vertex p.
Mk | The mean for cluster k.
j | An integer that sums over the number of PCA vectors.
N | The number of PCA vectors.
wpj | The jth PCA weight for point p.
Bkj | The jth PCA basis vector for cluster k.

A cluster is simply some number of vertices that share the same mean vector. How to get the cluster mean, the PCA weights, the PCA basis vectors, and the cluster identifiers (IDs) for the vertices is discussed below.

Substituting these two equations yields:

Then distributing the dot product yields:

Because both (Mk • L') and (Bkj • L') are constant per vertex, the sample calculates these values with the CPU and passes them as constants into the vertex shader; because wpj changes for each vertex, the sample stores this per-vertex data in the vertex buffer.


HDR Lighting
Microsoft DirectX 9.0 SDK Update (October 2004)

HDR Lighting

Lighting in the real world contains a very high dynamic range (HDR) of luminance values. The real world has about 10 orders of dynamic range (DR) for luminance values spread across the spectrum of darkness to brightness. On the other hand, a computer screen has a very limited display gamut (or range of luminance values): approximately two orders of dynamic range. The challenge to producing HDR rendered images is to map the real world HDR values into the limited gamut of a computer screen.

Tone mapping is the technique used by Microsoft DirectX for mapping HDR information into a more limited range. Tone mapping applied to CGI rendering can dramatically improve the amount of lighting detail rendered, allowing details in the darkest areas to be seen, and providing contrast in areas that are so bright, they appear burned. The resulting scenes render with far more visible lighting detail.

HDRLighting Sample is a software development kit (SDK) sample that demonstrates HDR lighting.

Tone Mapping

Tone mapping generally simulates optical phenomena that can not be caused by the DR of the monitor. Examples of this are flares or blooming (which are mostly properties of lenses), the blue shift that happens in the human eye in low light conditions, and other adaptations that are a result of the biochemistry of the eye. If the DR of the display were large enough, tone mapping would not be as neccessary, except for providing artistic effects or some of the properties of a camera lens or a charge coupled device (CCD).

Tone mapping divides the range of luminance values in a scene into a set of zones. Each zone encompasses a range of luminance values.

HDR uses the following terms:

  • Zone - range of luminance values
  • Middle gray - middle brightness region of the scene
  • Dynamic range - ratio of the highest scene luminance to the lowest scene luminance
  • Key - subjective measurement of scene lighting: this varies from light to moderate to dark

To calculate luminance from RGB values, use this:

L = 0.27R + 0.67G + 0.06B;

The log-average luminance is a useful approximation for the key of a scene. A general equation looks like this:

Lw = exp[ 1 / N( sum[ log( delta + Lw( x, y ) ) ] ) ]

Where:

  • Lw - log-average luminance
  • N - number of pixels in the image
  • delta - a small factor to avoid problems with black pixels
  • Lw( x, y ) - the world space luminance for pixel ( x, y )

To map this to a middle-gray value, here is a luminance scaling operator:

L( x, y ) = a * Lw( x, y ) / Lw

Where:

  • L( x, y ) - scaled luminance for pixel ( x, y )
  • a - image key value after applying the scaling

And finally, here is a simple tone mapping operator for compressing the high luminances:

Ld( x, y ) = L( x, y ) / ( 1 + L( x, y ) )

Where:

  • Ld( x, y ) - compressed and scaled luminance for pixel ( x, y )
  • a - image key value after applying the scaling

This operator scales high luminances by 1/L and low luminances by 1. For more details, see the paper referenced below.

"Photographic Tone Reproduction for Digital Images" Eric Reinhard, Michael Stark, Peter Shirley, James Ferwerda


Accurately Profiling Direct3D API Calls
Microsoft DirectX 9.0 SDK Update (October 2004)

Accurately Profiling Direct3D API Calls

  • Accurately Profiling Direct3D Is Difficult
  • How to Accurately Profile a Direct3D Render Sequence
  • Profiling Direct3D State Changes
  • Summary
  • Appendix

Once you have a functional Microsoft Direct3D application and you want to improve its performance, you generally use an off-the-shelf profiling tool or some custom measurement technique to measure the time it takes to execute one or more application programming interface (API) calls. If you have done this but are getting timing results that vary from one render sequence to the next, or you are making hypotheses that do not hold up to actual experiment results, the following information may help you to understand why.

The information provided here is based upon the assumption that you have knowledge of and experience with the following:

  • C/C++ programming
  • Direct3D API programming
  • Measuring API timing
  • The video card and its software driver
  • Possible unexplainable results from previous profiling experience

Accurately Profiling Direct3D Is Difficult

A profiler reports on the amount of time spent in each API call. This is done to improve performance by finding and tuning away hot spots. There are different kinds of profilers and profiling techniques.

  • A sampling profiler sits idle much of the time, awakening at specific intervals to sample (or to record) the functions being executed. It returns the percentage of time spent in each call. Generally, a sampling profiler is not very invasive to the application and has minimal impact on the overhead for the application.
  • An instrumenting profiler measures the actual time it takes for a call to return. It requires compiling start and stop delimiters into an application. An instrumenting profiler is comparatively more invasive to an application than a sampling profiler.
  • It is also possible to use a custom profiling technique with a high-performance timer. This produces results very much like an instrumenting profiler.
The type of profiler or profiling technique used is only part of the challenge of generating accurate measurements.

Profiling gives you answers that help you budget performance. For instance, suppose you know that an API call averages one thousand clock cycles to execute. You can assert some conclusions about performance such as the following:

  • A 2 GHz CPU (which spends 50 percent of its time rendering) is limited to calling this API 1 million times a second.
  • To achieve 30 frames per second, you cannot call this API more than 33,000 times per frame.
  • You can only render 3.3K objects per frame (assuming 10 of these API calls for each object's render sequence).

In other words, if you had sufficient time per API call, you could answer a budgeting question such as the number of primitives that can be rendered interactively. But the raw numbers returned by an instrumenting profiler will not accurately answer the budgeting questions. This is because the graphics pipeline has complex design issues such as the number of components that need to do work, the number of processors that control how the work flows between components, and optimization strategies implemented in the runtime and in a driver that are designed to make the pipeline more efficient.

Each API Call Goes through Several Components

Each call is processed by several components on its way from the application to the video card. For instance, consider the following render sequence containing two calls for drawing a single triangle:

SetTexture(...);
DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);

The following conceptual diagram shows the different components through which the calls must pass:

The application invokes Direct3D which controls the scene, handles user interactions, and determines how rendering is done. All of this work is specified in the render sequence, which is sent to the runtime using Direct3D API calls. The render sequence is virtually hardware independent (that is, the API calls are hardware independent but an application has knowledge of what features a video card supports).

The runtime converts these calls into a device-independent format. The runtime handles all the communication between the application and the driver, so that an application will run on more than one compatible piece of hardware (depending on the features required). When measuring a function call, an instrumenting profiler measures the time it spent in a function as well as the time for the function to return. One limitation of an instrumenting profiler is that it may not include the time it takes a driver to send the resulting work to the video card nor the time for the video card to process the work. In other words, an off-the-shelf instrumenting profiler fails to attribute all of the work associated with each function call.

The software driver uses hardware specific knowledge about the video card to convert the device-independent commands into a sequence of video card commands. Drivers may also optimize the sequence of commands that are sent to the video card, so that rendering on the video card is done efficiently. These optimizations can cause profiling problems because the amount of work done is not what it appears to be (you may need to understand the optimizations to account for them). The driver typically returns control to the runtime before the video card has finished processing all the commands.

The video card performs the majority of the rendering by combining data from the vertex and index buffers, textures, render state information, and the graphics commands. When the video card finishes rendering, the work created from the render sequence is complete.

Each Direct3D API call must be processed by each component (the runtime, the driver, and the video card) to render anything.

There Is More than One Processor Controlling the Components

The relationship between these components is even more complex, as the application, runtime, and the driver are controlled by one processor and the video card is controlled by a separate processor. This figure shows two kinds of processors: a central processing unit (CPU) and a graphics processing unit (GPU).

PC systems have at least one CPU and one GPU, but can have more than one of either or both. The CPUs are located on the motherboard, and the GPUs are located either on the motherboard or on the video card. The speed of the CPU is determined by a clock chip on the motherboard, and the speed of the GPU is determined by a separate clock chip. The CPU clock controls the speed of the work done by the application, the runtime, and the driver. The application sends work to the GPU via the runtime and the driver.

The CPU and the GPU generally run at different speeds, independent of one another. The GPU may respond to the work as soon as the work is available (assuming the GPU has finished processing previous work). The GPU work is done in parallel with the CPU work as highlighted by the curved line in the figure above. A profiler generally measures the performance of the CPU, not the GPU. This makes profiling challenging, because the measurements made by an instrumenting profiler include the CPU time but may not include the GPU time.

The purpose of the GPU is to off-load processing from the CPU to a processor specifically designed for graphics work. On modern video cards, the GPU replaces much of the transform and lighting work in the pipeline from the CPU to the GPU. This greatly reduces the CPU workload, leaving more CPU cycles available for other processing. To tune a graphical application for peak performance, you need to measure the performance of both the CPU and the GPU, and balance the work between the two types of processors.

This document does not cover topics related to measuring the performance of the GPU or balancing the work between the CPU and the GPU. If you want to better understand the performance of a GPU (or a particular video card), visit the vendor's web site to look for more information about GPU performance. Instead, this document focuses on the work done by the runtime and the driver by reducing the GPU work to a negligible amount. This is, in part, based on experience that applications experiencing performance problems are generally CPU-limited.

Runtime and Driver Optimizations Can Mask API Measurements

The runtime has a performance optimization built into it that can overwhelm the measurement of an individual call. Here's an example scenario that demonstrates this problem. Consider the following render sequence:

  BeginScene();
    ...
    SetTexture(...);
    DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);
    ...
  EndScene();
  Present();

Example 1: Simple Render Sequence

Looking at the results for the two calls in the render sequence, an instrumenting profiler could return results similar to these:

Number of cycles for SetTexture       : 100
Number of cycles for DrawPrimitive    : 950,500

The profiler returns the number of CPU cycles required to process the work associated with each call (remember that the GPU isn't included in these numbers because the GPU hasn't started working on these commands yet). Because IDirect3DDevice9::DrawPrimitive required almost a million cycles to process, you could conclude that it is not very efficient. However, you'll soon see why this conclusion is incorrect and how you can generate results that can be used for budgeting.

Measuring State Changes Requires Careful Render Sequences

All calls other than IDirect3DDevice9::DrawPrimitive, IDirect3DDevice9::DrawIndexedPrimitive, or IDirect3DDevice9::Clear (such as IDirect3DDevice9::SetTexture, IDirect3DDevice9::SetVertexDeclaration, and IDirect3DDevice9::SetRenderState) produce a state change. Each state change sets pipeline state that controls how rendering will be done.

Optimizations in the runtime and/or the driver are designed to speed up rendering by reducing the amount of work required. The following are a couple of state change optimizations that may pollute profile averages:

  • A driver (or the runtime) could save a state change as a local state. Because the driver could operate in a "lazy" algorithm (postponing work until it is absolutely necessary), work associated with some state changes could get delayed.
  • The runtime (or a driver) may remove state changes by optimizing. An example of this might be to remove a redundant state change that disables lighting because lighting has previously been disabled.

There is no foolproof way to look at a render sequence and conclude which state changes will set a dirty bit and defer work, or will simply be removed by optimization. Even if you could identify optimized state changes in today's runtime or driver, tomorrow's runtime or driver is likely to be updated. You also don't readily know what the previous state was so it is difficult to identify redundant state changes. The only way to verify the cost of a state change is to measure the render sequence that includes the state changes.

As you can see, the complications caused by having multiple processors, commands being processed by more than one component, and optimizations built into the components make profiling difficult to predict. In the next section, each of these profiling challenges will be addressed. Sample Direct3D render sequences will be shown, with the accompanying measurement techniques. With this knowledge, you will be able to generate accurate, repeatable measurements on individual calls.

How to Accurately Profile a Direct3D Render Sequence

Now that some of the profiling challenges have been highlighted, this section will show you techniques that will help you generate profile measurements that can be used for budgeting. Accurate, repeatable profiling measurements are possible if you understand the relationship between the components controlled by the CPU, and how to avoid performance optimizations implemented by the runtime and the driver.

To begin, you need to be able to accurately measure the execution time of a single API call.

Pick an Accurate Measurement Tool Like QueryPerformanceCounter

The Microsoft Windows operating system includes a high-resolution timer that can be used to measure high-resolution elapsed times. The current value of one such timer (see High-Resolution Timer World Wide Web link) can be returned using QueryPerformanceCounter World Wide Web link. By invoking QueryPerformanceCounter before and after a render sequence to return start and stop values, the difference between the two values can be converted to the actual elapsed time in seconds using QueryPerformanceFrequency World Wide Web link.

The advantages of using QueryPerformanceCounter are that it is available in Windows and it is easy to use. Simply surround the calls with a QueryPerformanceCounter call and save the start and stop values. Therefore, this paper will demonstrate how to use QueryPerformanceCounter to profile execution times, similar to the way an instrumenting profiler would measure it. Here's an example that shows how to embed QueryPerformanceCounter in your source code:

  BeginScene();
    ...
    // Start profiling
    LARGE_INTEGER start, stop, freq;
    QueryPerformanceCounter(&start);

    SetTexture(...);
    DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);

    QueryPerformanceCounter(&stop);
    stop.QuadPart -= start.QuadPart;
    QueryPerformanceFrequency(&freq);
    // Stop profiling
    ...
  EndScene();
  Present();

Example 2: Custom Profiling Implementation with QPC

start and stop are two large integers that will hold the start and stop values returned by the high-performance timer. Notice that QueryPerformanceCounter(&start) is called just before IDirect3DDevice9::SetTexture and QueryPerformanceCounter(&stop) is called just after IDirect3DDevice9::DrawPrimitive. After getting the stop value, QueryPerformanceFrequency is called to return freq, which is the frequency of the high-resolution timer. In this hypothetical example, suppose you get the following results for start, stop, and freq:

Local Variable | Number of Ticks
start | 1792998845094
stop | 1792998845102
freq | 3579545

You could convert these values to the number of cycles it takes to execute the API calls like this:

# ticks = (stop - start) = 1792998845102 - 1792998845094 = 8 ticks

# cycles = CPU speed * number of ticks / QPF
# 4568   = 2 GHz      * 8              / 3,579,545

In other words, it takes about 4568 clock cycles to process IDirect3DDevice9::SetTexture and IDirect3DDevice9::DrawPrimitive on this 2 GHz machine. You could convert these values to the actual time it took to execute all the calls like this:

(stop - start)/ freq = elapsed time
8 ticks / 3,579,545 = 2.2E-6 seconds or between 2 and 3 microseconds.

Using QueryPerformanceCounter requires that you add start and stop measurements to your render sequence and use QueryPerformanceFrequency to convert the difference (number of ticks) to the number of CPU cycles or to actual time. Identifying the measurement technique is a good start for developing a custom profiling implementation. But before you jump in and start making measurements, you need to know how to deal with the video card.

Focus on CPU Measurements

As stated earlier, the CPU and the GPU work in parallel to process the work generated by the API calls. A real world application requires profiling both types of processors to find out if your application is CPU-limited or GPU-limited. Since GPU performance is vendor specific, it would be very challenging to produce results in this paper that cover the variety of video cards available.

Instead, this paper will focus only on profiling the work performed by the CPU by using a custom technique for measuring the runtime and driver work. The GPU work will be reduced to an insignificant amount, so that CPU results are more visible. One benefit of this approach is that this technique yields results in the Appendix that you should be able to correlate with your measurements. To reduce the work required by the video card to an insignificant level, simply reduce the rendering work to the least amount possible. This can be accomplished by limiting draw calls to render a single triangle, and can be further constrained so that each triangle only contains one pixel.

The unit of measure used in this paper for measuring CPU work will be the number of CPU clock cycles rather than actual time. CPU clock cycles has the advantage that it is more portable (for CPU-limited applications) than actual elapsed time across machines with different CPU speeds. This can easily be converted to actual time if desired.

This document does not cover topics related to balancing the work load between the CPU and the GPU. Remember, the goal of this paper is not to measure the overall performance of an application, but to show you how to accurately measure the time it takes the runtime and the driver to process API calls. With these accurate measurements, you can take on the task of budgeting the CPU to understand certain performance scenarios.

Controlling Runtime and Driver Optimizations

With a measurement technique identified, and a strategy for reducing GPU work, the next step is to understand the runtime and driver optimizations that get in the way when you are profiling.

The CPU work can be divided into three buckets: the application work, the runtime work, and the driver work. Ignore the application work since this is under programmer control. From the application's standpoint, the runtime and the driver are like black boxes, as the application has no control over what is implemented in them. The key is to understand the optimization techniques that may be implemented in the runtime and the driver. If you don't understand these optimizations, it is very easy to jump to the wrong conclusion about the amount of work the CPU is doing based on the profile measurements. In particular, there are two topics related to something called the command buffer and what it can do to obfuscate profiling. These topics are:

  • Runtime optimization with the Command Buffer. The command buffer is a runtime optimization that reduces the impact of a mode transition. To control the timing of the mode transition, see Controlling the Command Buffer.
  • Negating the timing effects of the Command Buffer. The elapsed time of a mode transition can have a big impact on profiling measurements. The strategy for this is to Make the Render Sequence Large Compared to the Mode Transition.

Controlling the Command Buffer

When an application makes an API call, the runtime converts the API call to a device-independent format (which we will call a command), and stores it in the command buffer. The command buffer is shown added to the block diagram:

Each time the application makes another API call, the runtime repeats this sequence and adds another command to the command buffer. At some point, the runtime empties the buffer (sending the commands to the driver). In Windows XP, emptying the command buffer causes a mode transition as the operating system switches from the runtime (running in user mode) to the driver (running in kernel mode).

  • user mode - The non-privileged processor mode that executes application code. User-mode applications cannot gain access to system data except through system services.
  • kernel mode - The privileged processor mode in which Windows-based executive code runs. A driver or thread running in kernel mode has access to all system memory, direct access to hardware, and the CPU instructions to perform I/O with the hardware.

The transition happens each time the CPU switches from user to kernel mode (and vice versa) and the number of cycles it requires is large compared to an individual API call. If the runtime sent each API call to the driver when it was invoked, every API call would incur the cost of a mode transition.

Instead, the command buffer is a runtime optimization designed to reduce the effective cost of the mode transition. The command buffer queues many driver commands in preparation for a single mode transition. When the runtime adds a command to the command buffer, control is returned to the application. A profiler has no way of knowing that the driver commands have probably not even been sent to the driver yet. As a result, the numbers returned by an off-the-shelf instrumenting profiler are misleading since it measures the runtime work but not the associated driver work.

Profile Results without a Mode Transition

Using the render sequence from example 2, here are some typical timing measurements that illustrate the magnitude of a mode transition. Assuming that IDirect3DDevice9::SetTexture and IDirect3DDevice9::DrawPrimitive calls do not cause a mode transition, an off-the-shelf instrumenting profiler could return results similar to these:

Number of cycles for SetTexture           : 100
Number of cycles for DrawPrimitive        : 900

Each of these numbers are the amount of time it takes for the runtime to add these calls to the command buffer. Since there is no mode transition, the driver has not done any work yet. The profiler results are accurate, but they do not measure all of the work that the render sequence will eventually cause the CPU to perform.

Profile Results with a Mode Transition

Now, look at what happens for the same example when a mode transition occurs. This time, assume IDirect3DDevice9::SetTexture and IDirect3DDevice9::DrawPrimitive cause a mode transition. Once again, an off-the-shelf instrumenting profiler could return results similar to these:

Number of cycles for SetTexture           : 98
Number of cycles for DrawPrimitive        : 946,900

The time measured for IDirect3DDevice9::SetTexture is about the same, however, the dramatic increase in the amount of time spent in IDirect3DDevice9::DrawPrimitive is due to the mode transition. Here's what is happening:

  1. Assume the command buffer has room for one command before our render sequence starts.
  2. IDirect3DDevice9::SetTexture is converted to a device-independent format and added to the command buffer. In this scenario, this call fills the command buffer.
  3. The runtime tries to add IDirect3DDevice9::DrawPrimitive to the command buffer but cannot, because it is full. Instead, the runtime empties the command buffer. This causes the kernel-mode transition. Assume the transition takes about 5000 cycles. This time contributes to time spent in IDirect3DDevice9::DrawPrimitive.
  4. The driver then processes the work associated with all the commands that were emptied from the command buffer. Assume that the driver time to process the commands that nearly filled the command buffer is about 935,000 cycles. Assume that the driver work associated with IDirect3DDevice9::SetTexture is about 2750 cycles. This time contributes to time spent in IDirect3DDevice9::DrawPrimitive.
  5. When the driver finishes its work, the user-mode transition returns control to the runtime. The command buffer is now empty. Assume the transition takes about 5000 cycles.
  6. The render sequence finishes by converting IDirect3DDevice9::DrawPrimitive and adding it to the command buffer. Assume this takes about 900 cycles. This time contributes to time spent in IDirect3DDevice9::DrawPrimitive.

Summarizing the results, you see:

DrawPrimitive = kernel-transition + driver work    + user-transition + runtime work
DrawPrimitive = 5000              + 935,000 + 2750 + 5000            + 900
DrawPrimitive = 947,950

Just like the measurement for IDirect3DDevice9::DrawPrimitive without the mode transition (900 cycles), the measurement for IDirect3DDevice9::DrawPrimitive with the mode transition (947,950 cycles) is accurate but useless in terms of budgeting CPU work. The result contains the correct runtime work, the driver work for IDirect3DDevice9::SetTexture, the driver work for any commands that preceded IDirect3DDevice9::SetTexture, and two mode transitions. However, the measurement is missing the IDirect3DDevice9::DrawPrimitive driver work.

A mode transition could happen in response to any call. It depends on what was previously in the command buffer. You need to control the mode transition to understand how much CPU work (runtime and driver) is associated with each call. To do that, you need a mechanism for controlling the command buffer and the timing of the mode transition.

The Query Mechanism

The query mechanism in Microsoft DirectX 9.0 was designed to allow the runtime to query the GPU for progress and return certain data from the GPU. While profiling, if the GPU work is minimized so that it has a negligible impact on performance, you can return status from the GPU to help measure the driver work. After all, the driver work is complete when the GPU has seen the driver commands. Additionally, the query mechanism can be coaxed into controlling two command buffer characteristics that are important to profiling: when the command buffer empties and how much work is in the buffer.

Here's the same render sequence using the query mechanism:

// 1. Create an event query from the current device
IDirect3DQuery9* pQuery;
m_pD3DDevice->CreateQuery(D3DQUERYTYPE_EVENT, &pQuery);

// 2. Add an end marker to the command buffer queue.
pEvent->Issue(D3DISSUE_END);

// 3. Empty the command buffer and wait until the GPU is idle.
while(S_FALSE == pEvent->GetData( NULL, 0, D3DGETDATA_FLUSH ))
    ;

// 4. Start profiling
LARGE_INTEGER start, stop;
QueryPerformanceCounter(&start);

// 5. Invoke the API calls to be profiled.
SetTexture(...);
DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);

// 6. Add an end marker to the command buffer queue.
pEvent->Issue(D3DISSUE_END);

// 7. Force the driver to execute the commands from the command buffer.
// Empty the command buffer and wait until the GPU is idle.
while(S_FALSE == pEvent->GetData( NULL, 0, D3DGETDATA_FLUSH ))
    ;

// 8. End profiling
QueryPerformanceCounter(&stop);

Example 3: Using a Query to Control the Command Buffer

Here is a more detailed explanation of each of these lines of code:

  1. Create an event query by creating a query object with D3DQUERYTYPE_EVENT.
  2. Add a query event marker to the command buffer by calling IDirect3DQuery9::Issue(D3DISSUE_END). This marker tells the driver to track when the GPU finishes executing whatever commands preceded the marker.
  3. The first call empties the command buffer because calling IDirect3DQuery9::GetData with D3DGETDATA_FLUSH forces the command buffer to be emptied. Each subsequent call is checking the GPU to see when it finishes processing all the command-buffer work. This loop does not return S_OK until the GPU is idle.
  4. Sample the start time.
  5. Invoke the API calls being profiled.
  6. Add a second query event marker to the command buffer. This marker will be used to track the completion of the calls.
  7. The first call empties the command buffer because calling IDirect3DQuery9::GetData with D3DGETDATA_FLUSH forces the command buffer to be emptied. When the GPU finishes processing all the command-buffer work, IDirect3DQuery9::GetData returns S_OK, and the loop is exited because the GPU is idle.
  8. Sample the stop time.

Here are the results measured with QueryPerformanceCounter and QueryPerformanceFrequency:

Local Variable | Number of Ticks
start | 1792998845060
stop | 1792998845090
freq | 3579545

Converting ticks to cycles once again (on a 2 GHz machine):

# ticks  = (stop - start) = 1792998845090 - 1792998845060 = 30 ticks
# cycles = CPU speed * number of ticks / QPF
# 16,450 = 2 GHz      * 30             / 3,579,545

Here is the breakdown of the number of cycles per call:

Number of cycles for SetTexture           : 100
Number of cycles for DrawPrimitive        : 900
Number of cycles for Issue                : 200
Number of cycles for GetData              : 16,450

The query mechanism has allowed us to control the runtime and the driver work that is being measured. To understand each of these numbers, here's what is happening in response to each of the API calls, along with the estimated timings:

  1. The first call empties the command buffer by calling IDirect3DQuery9::GetData with D3DGETDATA_FLUSH. When the GPU finishes processing all the command-buffer work, IDirect3DQuery9::GetData returns S_OK, and the loop is exited because the GPU is idle.
  2. The render sequence starts by converting IDirect3DDevice9::SetTexture to a device-independent format and adding it to the command buffer. Assume this takes about 100 cycles.
  3. IDirect3DDevice9::DrawPrimitive is converted and added to the command buffer. Assume this takes about 900 cycles.
  4. IDirect3DQuery9::Issue adds a query marker to the command buffer. Assume this takes about 200 cycles.
  5. IDirect3DQuery9::GetData causes the command buffer to be emptied which forces the kernel-mode transition. Assume this takes about 5000 cycles.
  6. The driver then processes the work associated with all four calls. Assume that the driver time to process IDirect3DDevice9::SetTexture is about 2964 cycles, IDirect3DDevice9::DrawPrimitive is about 3600 cycles, IDirect3DQuery9::Issue is about 200 cycles. So the total driver time for all four commands is about 6450 cycles.

    Note The driver also takes a little time to see what the status of the GPU is. Because the GPU work is trivial, the GPU should be done already. IDirect3DQuery9::GetData will return S_OK based on the likelihood that the GPU is finished.
  7. When the driver finishes its work, the user-mode transition returns control to the runtime. The command buffer is now empty. Assume this takes about 5000 cycles.

The numbers for IDirect3DQuery9::GetData include:

GetData = kernel-transition + driver work + user-transition
GetData = 5000              + 6450        + 5000
GetData = 16,450

driver work = SetTexture + DrawPrimitive + Issue =
driver work = 2964       + 3600          + 200   = 6450 cycles

The query mechanism used in combination with QueryPerformanceCounter measures all of the CPU work. This is done with a combination of query markers, and query status comparisons. Start and stop query markers added to the command buffer are used to control how much work is in the buffer. By waiting until the right return code is returned, the start measurement is made just before a clean render sequence starts, and the stop measurement is made just after the driver has finished the work associated with the command buffer contents. This effectively captures the CPU work done by the runtime as well as the driver.

Now that you know about the command buffer and the effect it can have on profiling, you should know that there are a few other conditions that can cause the runtime to empty the command buffer. You need to watch out for these in your render sequences. Some of these conditions are in response to API calls, others are in response to resource changes in the runtime. Any of the following conditions will cause a mode transition:

  • When one of the lock methods (IDirect3DVertexBuffer9::Lock) is called on a vertex buffer, index buffer, or texture (under certain conditions with certain flags).
  • When a device or vertex buffer, index buffer, or texture is created.
  • When a device or vertex buffer, index buffer, or texture is destroyed by the last release.
  • When IDirect3DDevice9::ValidateDevice is called.
  • When IDirect3DDevice9::Present is called.
  • When the command buffer fills up.
  • When IDirect3DQuery9::GetData is called with D3DGETDATA_FLUSH.

Be careful to watch for these conditions in your render sequences. Every time a mode transition is added, 10,000 cycles of driver work will be added to your profiling measurements. In addition, the command buffer is not statically sized. The runtime may change the buffer's size in response to the amount of work that is being generated by the application. This is yet another optimization that is dependent on a render sequence.

So be careful to control mode transitions during profiling. The query mechanism offers a robust method for emptying the command buffer so that you can control the timing of the mode transition as well as the amount of work the buffer contains. However, even this technique can be improved by reducing the mode transition time to make it insignificant with respect to the measured result.

Make the Render Sequence Large Compared to the Mode Transition

In the previous example, the the kernel-mode switch and the user-mode switch consume about 10,000 cycles that have nothing to do with runtime and driver work. Since the mode transition is built into the operating system, it cannot be reduced to zero. To make the mode transition insignificant, the render sequence needs to adjusted so that the driver and runtime work are an order of magnitude larger than the mode switches. You could try to do a subtraction to remove the transitions, but amortizing the cost over a much larger render sequence cost is more reliable.

The strategy for reducing the mode transition until it becomes insignificant is to add a loop to the render sequence. For example, let look at the profiling results if a loop is added that will repeat the render sequence 1500 times:

// Initialize the array with two textures, same size, same format
IDirect3DTexture* texArray[2];

CreateQuery(D3DQUERYTYPE_EVENT, pEvent);
pEvent->Issue(D3DISSUE_END);
while(S_FALSE == pEvent->GetData( NULL, 0, D3DGETDATA_FLUSH ))
    ;

LARGE_INTEGER start, stop;
// Now start counting because the video card is ready
QueryPerformanceCounter(&start);

// Add a loop to the render sequence
for(int i = 0; i < 1500; i++)
{
  SetTexture(taxArray[i%2]);
  DrawPrimitive(D3DPT_TRIANGLELIST, i*3, 1);
}

pEvent->Issue(D3DISSUE_END);

while(S_FALSE == pEvent->GetData( NULL, 0, D3DGETDATA_FLUSH ))
    ;
QueryPerformanceCounter(&stop);

Example 4: Add a Loop to the Render Sequence

Here are the results measured with QueryPerformanceCounter and QueryPerformanceFrequency:

Local Variable | Number of Tics
start | 1792998845000
stop | 1792998847084
freq | 3579545

Using QueryPerformanceCounter measures 2,840 ticks now. Converting ticks to cycles is the same as we have already shown:

# ticks  = (stop - start) = 1792998847084 - 1792998845000 = 2840 ticks
# cycles    = machine speed * number of ticks / QPF
# 6,900,000 = 2 GHz          * 2840           / 3,579,545

In other words, it takes about 6.9 million cycles on this 2 GHz machine to process the 1500 calls in the render loop. Of the 6.9 million cycles, the amount of time in the mode transitions is approximately 10k, so now the profile results are almost entirely measuring work associated with IDirect3DDevice9::SetTexture and IDirect3DDevice9::DrawPrimitive.

Notice that the code sample requires an array of two textures. To avoid a runtime optimization that would remove IDirect3DDevice9::SetTexture if it sets the same texture pointer every time it is called, simply use an array of two textures. That way, each time through the loop, the texture pointer changes, and the full work associated with IDirect3DDevice9::SetTexture is performed. Be sure that both textures are the same size and format, so that no other state will change when the texture does.

And now you have a technique for profiling Direct3D. It relies on the high performance counter (QueryPerformanceCounter) to record the number of ticks it takes the CPU to process work. The work is carefully controlled to be the runtime and driver work associated with API calls using the query mechanism. A query provides two means of control: first to empty the command buffer before the render sequence starts, and secondly to return when the GPU work is finished.

So far, this paper has shown how to profile a render sequence. Each render sequence has been fairly simple, containing a single IDirect3DDevice9::DrawPrimitive call and a IDirect3DDevice9::SetTexture call. This was done to focus on the command buffer and the use of the query mechanism to control it. Here is a brief summary of how to profile an arbitrary render sequence:

  • Use a high performance counter like QueryPerformanceCounter to measure the time it takes to process each API call. Use QueryPerformanceFrequency and the CPU clock rate to convert this to the number of CPU cycles per API call.
  • Minimize the amount of GPU work by rendering triangle lists, where each triangle contains one pixel.
  • Use the query mechanism to empty the command buffer before the render sequence. This guarantees that profiling will capturing the correct amount of runtime and driver work associated with the render sequence.
  • Control the amount of work added to the command buffer with query event markers. This same query detects when the GPU finishes its work. Since the GPU work is trivial, this is virtually equivalent to measuring when the driver work is completed.

All of these techniques are used to profile state changes. Assuming that you have read and understood how to control the command buffer, and have successfully completed baseline measurements on IDirect3DDevice9::DrawPrimitive (watch out for this optimization problem - Watch Out for DrawPrimitive Optimizations), you are ready to add state changes to your render sequences. There are a few additional profiling challenges when adding state changes to a render sequence. If you intend to add state changes to your render sequences, be sure to continue into the next section.

Profiling Direct3D State Changes

Direct3D uses many render states to control almost every aspect of the pipeline. The APIs that cause state changes include any function or method other than the Draw*Primitive calls.

State changes are tricky because you may not be able to see the cost of a state change without rendering. This is a result of the lazy algorithm that the driver and the GPU use to defer work until it absolutely has to be done. In general, you should follow these steps to measure a single state change:

  1. Profile IDirect3DDevice9::DrawPrimitive first.
  2. Add one state change to the render sequence and profile the new sequence.
  3. Subtract the difference between the two sequences to get the cost of the state change.

Naturally, everything you have learned about using the query mechanism and putting the render sequence in a loop to negate the cost of the mode transition still applies.

Profiling a Simple State Change

Starting with a render sequence that contains IDirect3DDevice9::DrawPrimitive, here is the code sequence for measuring the cost of adding IDirect3DDevice9::SetTexture:

// Get the start counter value as shown in Example 4

// Initialize a texture array as shown in Example 4
IDirect3DTexture* texArray[2];

// Render sequence loop
for(int i = 0; i < 1500; i++)
{
  SetTexture(0, texArray[i%2];

  // Force the state change to propogate to the GPU
  DrawPrimitive(D3DPT_TRIANGLELIST, i*3, 1);
}

// Get the stop counter value as shown in Example 4

Example 5: Measuring One State Change API Call

Notice that the loop contains two calls, IDirect3DDevice9::SetTexture and IDirect3DDevice9::DrawPrimitive. The render sequence loops 1500 times and generates results similar to these:

Local Variable | Number of Tics
start | 1792998860000
stop | 1792998870260
freq | 3579545

Converting ticks to cycles once again yields:

# ticks  = (stop - start) = 1792998870260 - 1792998860000 = 10,260 ticks
# cycles    = machine speed * number of ticks / QPF
5,775,000   = 2 GHz          * 10,260         / 3,579,545

Dividing by the number of iterations in the loop yields:

5,775,000 cycles / 1500 iterations = 3850 cycles for one iteration

Each iteration of the loop contains a state change and a draw call. Subtracting out the result of the IDirect3DDevice9::DrawPrimitive render sequence leaves:

3850 - 1100 = 2750 cycles for SetTexture

This is the average number of cycles to add IDirect3DDevice9::SetTexture to this render sequence. This same technique can be applied to other state changes.

Why is IDirect3DDevice9::SetTexture called a simple state change? Because the state that is being set is constrained so that the pipeline does the same amount of work each time the state is changed. Constraining both textures to the same size and format assures the same amount of work for each IDirect3DDevice9::SetTexture call.

Profiling a State Change that Needs to Be Toggled

There are other state changes that cause the amount of work performed by the graphics pipeline to change for every iteration of the render loop. For example, if z-testing is enabled, each pixel color updates a render target only after the new pixel's z value is tested against the z-value for the existing pixel. If z-testing is disabled, this per-pixel test is not done and the output is written much faster. Enabling or disabling the z-test state dramatically changes the amount of work done (by the CPU as well as the GPU) during rendering.

IDirect3DDevice9::SetRenderState requires a particular render state and a state value to enable or disable z-testing. The particular state value is evaluated at runtime to determine how much work is necessary. It is difficult to measure this state change in a render loop and still precondition the pipeline state so that it switches. The only solution is to toggle the state change during the render sequence.

For example, the profiling technique needs to be repeated twice as follows:

  1. Start by profiling the IDirect3DDevice9::DrawPrimitive render sequence. Call this the baseline.
  2. Profile a second render sequence that toggles the state change. The render sequence loop contains:
    • A state change to set the state into a "false" condition.
    • IDirect3DDevice9::DrawPrimitive just like the original sequence.
    • A state change to set the state into a "true" condition.
    • A second IDirect3DDevice9::DrawPrimitive to force the second state change to be realized.
  3. Find the difference between the two render sequences. This is done by:
    • Multiply the baseline IDirect3DDevice9::DrawPrimitive sequence by 2 because there are two IDirect3DDevice9::DrawPrimitive calls in the new sequence.
    • Subtract the result of the new sequence from the original sequence.
    • Divide the result by 2 to get the average cost of both the "false" and the "true" state change.

With the looping technique used in the render sequence, the cost of changing pipeline state needs to be measured by toggling the state from a "true" to a "false" condition and vice versa, for each iteration in the render sequence. The meaning of "true" and "false" here are not literal, this simply means that the state needs to be set into opposing conditions. This causes both state changes to be measured during profiling. Of course everything you have learned about using the query mechanism and putting the render sequence in a loop to negate the cost of the mode transition still applies.

For example, here is the code sequence for measuring the cost of toggling z-testing on or off:

// Get the start counter value as shown in Example 4

// Add a loop to the render sequence
for(int i = 0; i < 1500; i++)
{
  // Precondition the pipeline state to the "false" condition
  SetRenderState(D3DRS_ZENABLE, FALSE);

  // Force the state change to propogate to the GPU
  DrawPrimitive(D3DPT_TRIANGLELIST, (2*i + 0)*3, 1);

  // Set the pipeline state to the "true" condition
  SetRenderState(D3DRS_ZENABLE, TRUE);

  // Force the state change to propogate to the GPU
  DrawPrimitive(D3DPT_TRIANGLELIST, (2*i + 1)*3, 1);
}

// Get the stop counter value as shown in Example 4

Example 5: Measuring a Toggling State Change

The loop toggles the state by executing two IDirect3DDevice9::SetRenderState calls. The first IDirect3DDevice9::SetRenderState call disables z-testing and the second IDirect3DDevice9::SetRenderState enables z-testing. Each IDirect3DDevice9::SetRenderState is followed by IDirect3DDevice9::DrawPrimitive so that the work associated with the state change is processed by the driver instead of only setting a dirty bit in the driver.

These numbers are reasonable for this render sequence:

Local Variable | Number of Ticks
start | 1792998845000
stop | 1792998861740
freq | 3579545

Converting ticks to cycles once again yields:

# ticks  = (stop - start) = 1792998861740 - 1792998845000 = 15,120 ticks
# cycles    = machine speed * number of ticks / QPF
 9,300,000  = 2 GHz          * 16,740         / 3,579,545

Dividing by the number of iterations in the loop yields:

9,300,000 cycles / 1500 iterations = 6200 cycles for one iteration

Each iteration of the loop contains two state changes and two draw calls. Subtracting out the draw calls (assuming 1100 cycles) leaves:

6200 - 1100 - 1100 = 4000 cycles for both state changes

This is the average number of cycles for both state changes so the average time for each state change is:

4000 / 2  = 2000 cycles for each state change

Therefore, the average number of cycles to enable or disable z-testing is 2000 cycles. It is worth noting that QueryPerformanceCounter is measuring z-enable half the time and z-disable half of the time. This technique actually measures the average of both state changes. In other words, you are measuring the time to toggle a state. Using this technique, you have no way of knowing if the enable and disable times are equivalent since you have measured the average of both of them. Nevertheless, this is a reasonable number to use when budgeting a toggling state as an application that causes this state change can only do so by toggling this state.

So now you can apply these techniques and profile all the state changes you want, right? Not quite. You still need to be careful about optimizations that are designed to reduce the amount of work that needs to be done. There are two types of optimizations that you should be aware of when designing your render sequences.

Watch Out for State Change Optimizations

The previous section show how to profile both kinds of state changes: a simple state change that is constrained to generate the same amount of work for each iteration, and a toggling state change that dramatically changes the amount of work done. What happens if you take the previous render sequence and add another state change to it? For instance, this example takes the z-enable render sequence and adds a z-func comparison to it:

// Add a loop to the render sequence
for(int i = 0; i < 1500; i++)
{
  // Precondition the pipeline state to the opposite condition
  SetRenderState(D3DRS_ZFUNC, D3DCMP_NEVER);

  // Precondition the pipeline state to the opposite condition
  SetRenderState(D3DRS_ZENABLE, FALSE);

  // Force the state change to propogate to the GPU
  DrawPrimitive(D3DPT_TRIANGLELIST, (2*i + 0)*3, 1);

  // Now set the state change you want to measure
  SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);

  // Now set the state change you want to measure
  SetRenderState(D3DRS_ZENABLE, TRUE);

  // Force the state change to propogate to the GPU
  DrawPrimitive(D3DPT_TRIANGLELIST, (2*i + 1)*3, 1);
}

The z-func state sets the comparison level when writing to the z-buffer (between the z-value of a current pixel with the z-value of a pixel in the depth buffer). D3DCMP_NEVER turns off the z-testing comparison while XREFD3DCMP_ALWAYS sets the comparison to happen every time z-testing is done.

Profiling either one of these state changes in a render sequence with IDirect3DDevice9::DrawPrimitive generates results similar to these:

Single State Change | Average Number of Cycles
D3DRS_ZENABLE only | 2000

or

Single State Change | Average Number of Cycles
D3DRS_ZFUNC only | 600

But, if you profile both D3DRS_ZENABLE and D3DRS_ZFUNC in the same render sequence you could see results like these:

Both State Changes | Average Number of Cycles
D3DRS_ZENABLE + D3DRS_ZFUNC | 2000

You could expect the result to be to be the sum of 2000 and 600 (or 2600) cycles because the driver is doing all the work associated with setting both render states. Instead, the average is 2000 cycles.

This result reflects a state change optimization implemented in the runtime, the driver, or the GPU. In this case, the driver could see the first IDirect3DDevice9::SetRenderState and set a dirty state which would postpone the work until later. When the driver sees the second IDirect3DDevice9::SetRenderState, the same dirty state could be redundantly set and the same work would be postponed once again. When IDirect3DDevice9::DrawPrimitive is called, the work associated with the dirty state is finally processed. The driver executes the work one time, which means that the first two state changes are effectively consolidated by the driver. Similarly, the third and fourth state changes are effectively consolidated by the driver into a single state change when the second IDirect3DDevice9::DrawPrimitive is called. The net result is that the driver and the GPU process a single state change for each draw call.

This is a good example of a sequence-dependent driver optimization. The driver postponed work twice by setting a dirty state, and then performed the work once to clear the dirty state. This is a good example of the kind of efficiency improvement that can take place when work is deferred until absolutely necessary.

How do you know which state changes set a dirty state internally and therefore postpone work until later? Only by testing render sequences (or talking to driver writers). Drivers are updated and improved periodically so the list of optimizations is not static. There is only one way to absolutely know what a state change costs in a given render sequence, on a particular set of hardware; and that is to measure it.

Watch Out for DrawPrimitive Optimizations

In addition to state change optimizations, the runtime will attempt to optimize the number of draw calls that the driver has to process. For example, consider these back to back draw calls:

DrawPrimitive(D3DPT_TRIANGLELIST, 0, 3); // Draw 3 primitives, vertices 0 - 8
DrawPrimitive(D3DPT_TRIANGLELIST, 9, 4); // Draw 4 primitives, vertices 9 - 20

Example 5a: Two Draw Calls

This sequence contains two draw calls, which the runtime will consolidate into a single call equivalent to:

DrawPrimitive(D3DPT_TRIANGLELIST, 0, 7); // Draw 7 primitives, vertices 0 - 20

Example 5b: A Single Concatenated Draw Call

The runtime will concatenate both of these particular draw calls into a single call, which reduces the driver work by 50 percent because the driver will now only need to process one draw call.

In general, the runtime will concatenate two or more back-to-back IDirect3DDevice9::DrawPrimitive calls when:

  1. The primitive type is a triangle list (D3DPT_TRIANGLELIST).
  2. Each successive IDirect3DDevice9::DrawPrimitive call must reference consecutive vertices within the vertex buffer.

Similarly, the right conditions for concatenating two or more back-to-back IDirect3DDevice9::DrawIndexedPrimitive calls are:

  1. The primitive type is a triangle list (D3DPT_TRIANGLELIST).
  2. Each successive IDirect3DDevice9::DrawIndexedPrimitive call must sequential reference consecutive indices within the index buffer.
  3. All IDirect3DDevice9::DrawIndexedPrimitive primitives must use the same value for BaseVertexIndex.

To prevent concatenation during profiling, modify the render sequence so that the primitive type is not a triangle list, or modify the render sequence so that there are no back to back draw calls the use consecutive vertices (or indices).

Here is a more subtle example of draw call concatenation that is easy to overlook when you are profiling. Assume the render sequence looks like this:

  for(int i = 0; i < 1500; i++)
  {
    SetTexture(...);
    DrawPrimitive(D3DPT_TRIANGLELIST, i*3, 1);
  }

Example 5c: One State Change and One Draw Call

The loop iterates through 1500 triangles, setting a texture and drawing each triangle. This render loop takes approximately 2750 cycles for IDirect3DDevice9::SetTexture and 1100 cycles for IDirect3DDevice9::DrawPrimitive as shown in previous sections. You might intuitively expect that moving IDirect3DDevice9::SetTexture outside the render loop should reduce the amount of work done by the driver by 1500 * 2750 cycles, which is the amount of work associated with calling IDirect3DDevice9::SetTexture 1500 times. The code snippet would look like this:

  SetTexture(...); // Set the state outside the loop
  for(int i = 0; i < 1500; i++)
  {
//    SetTexture(...);
    DrawPrimitive(D3DPT_TRIANGLELIST, i*3, 1);
  }

Example 5d: Example 5c with the State Change Outside the Loop

Moving IDirect3DDevice9::SetTexture outside the render loop does reduce the amount of work associated with IDirect3DDevice9::SetTexture since it is called once instead of 1500 times. A less obvious secondary effect is that the work for IDirect3DDevice9::DrawPrimitive is also reduced from 1500 calls to 1 call because all of the conditions for concatenating draw calls are satisfied. When the render sequence is processed, the runtime will process 1500 calls into a single driver call. By moving this one line of code, the amount of driver work has been reduced dramatically:

total work done = runtime + driver work

Example 5c: with SetTexture in the loop:
runtime work = 1500 SetTextures + 1500 DrawPrimitives
driver  work = 1500 SetTextures + 1500 DrawPrimitives

Example 5d: with SetTexture outside of the loop:
runtime work = 1 SetTexture + 1 DrawPrimitive + 1499 Concatenated DrawPrimitives
driver  work = 1 SetTexture + 1 DrawPrimitive

These results are entirely correct, but are very misleading in the context of the original question. The draw call optimization has caused the amount of driver work to be dramatically reduced. This is a common problem when doing custom profiling. When eliminating calls from a render sequence, be careful to avoid draw call concatenation. In fact, this scenario is a powerful example of the amount of improvement in driver performance possible by this runtime optimization.

So now you know how to measure state changes. Start by profiling IDirect3DDevice9::DrawPrimitive. Then add each additional state change to the sequence (in some cases adding one call and in other cases adding two calls) and measure the difference between the two sequences. You can convert the results to ticks or cycles or time. Just like measuring render sequences with QueryPerformanceCounter, measuring individual state changes relies on the query mechanism to control the command buffer, and putting the state changes in a loop to minimize the impact of the mode transitions. This technique measures the cost of toggling a state, since the profiler returns the average of enabling and disabling the state.

With this capability, you can start generating arbitrary rendering sequences and accurately measuring the associated runtime and driver work. The numbers can then be used to answer budgeting questions like "how many more of these calls" can be made in the render sequence while still maintaining a reasonable frame rate, assuming CPU-limited scenarios.

Summary

This paper demonstrates how to control the command buffer so that individual calls can be accurately profiled. The profiling numbers can be generated in ticks, cycles, or absolute time. They represent the amount of runtime and driver work associated with each API call.

Start by profiling a Draw*Primitive call in a render sequence. Remember to:

  1. Use QueryPerformanceCounter to measure the number of ticks per API call. Use QueryPerformanceFrequency to convert the results to cycles or time if you like.
  2. Use the query mechanism to empty the command buffer before starting.
  3. Include the render sequence in a loop to minimize the impact of the mode transition.
  4. Use the query mechanism to measure when the GPU has completed its work.
  5. Watch out for runtime concatenation that will have a major impact on the amount of work done.

This gives you a baseline performance for IDirect3DDevice9::DrawPrimitive that can be used to build from. To profile one state change, follow these additional tips:

  1. Add the state change to a known render sequence profile the new sequence. Since the testing is done in a loop, this requires setting the state twice into opposite values (like enable and disable for instance).
  2. Compare the difference in cycle times between the two sequences.
  3. For state changes that significantly change the pipeline (like IDirect3DDevice9::SetTexture), subtract the difference between the two sequences to get the time for state change.
  4. For state changes that significantly change the pipeline (and therefore require toggling states like IDirect3DDevice9::SetRenderState), subtract the difference between the render sequences and divide by 2. This will generate the average number of cycles for each state change.

But be careful of optimizations that cause unexpected results when profiling. State change optimizations may set dirty states which causes work to be deferred. This can cause profile results which are not as intuitive as expected. Draw calls that are concatenated will dramatically reduce driver work which can lead to misleading conclusions. Carefully planned render sequences are used to prevent state change and draw call concatenations from occuring. The trick is to prevent the optimizations from happening during profiling so that the numbers you generate are reasonable budgeting numbers.

Note Duplicating this profiling strategy in an application without the query mechanism is more difficult. Prior to DirectX 9.0 the only predictable way to empty the command buffer is to lock an active surface (such as a render target) to wait until the GPU is idle. This is because locking a surface forces the runtime to empty the command buffer in case there are any rendering commands in the buffer that should update the surface before it gets locked, in addition to waiting for the GPU to finish. This technique is functional, although it is more obtrusive that using the query mechanism introduced in DirectX 9.0.

Appendix

The numbers in this table are a range of approximations for the amount of runtime and driver work associated with each of these state changes. The approximations are based on actual measurements made on drivers using the techniques shown in the paper. These numbers were generated using the DirectX 9.0 runtime and are driver-dependent.

The techniques in this paper are designed to measure runtime and driver work. In general, it is impractical to provide results that match the performance of the CPU and the GPU in every application as this would require an exhaustive array of render sequences. In addition, it is particularly difficult to benchmark performance of the GPU because it is highly dependent on the state setup in the pipeline before the render sequence. For instance, enabling alpha blending does little to affect the amount of CPU work necessary, but can have a big impact on the amount of work done by the GPU. Therefore, the techniques in this paper constrain the GPU work to the minimum amount possible by limiting the amount of data that needs to be rendered. This means that the numbers in the table will most closely match the results attained from applications that are CPU limited (as opposed to an application that is limited by the GPU).

You are encouraged to use the techniques presented to cover the scenarios and configurations most important to you. The values in the table can be used to compare with the numbers you generate. Since each driver varies, the only way to generate the actual numbers you will see is to generate profiling results using your scenarios.

API Call | Average number of Cycles
SetVertexDeclaration | 6500 - 11250
SetFVF | 6400 - 11200
SetVertexShader | 3000 - 12100
SetPixelShader | 6300 - 7000
SPECULARENABLE | 1900 - 11200
SetRenderTarget | 6000 - 6250
SetPixelShaderConstant (1 Constant) | 1500 - 9000
NORMALIZENORMALS | 2200 - 8100
LightEnable | 1300 - 9000
SetStreamSource | 3700 - 5800
LIGHTING | 1700 - 7500
DIFFUSEMATERIALSOURCE | 900 - 8300
AMBIENTMATERIALSOURCE | 900 - 8200
COLORVERTEX | 800 - 7800
SetLight | 2200 - 5100
SetTransform | 3200 - 3750
SetIndices | 900 - 5600
AMBIENT | 1150 - 4800
SetTexture | 2500 - 3100
SPECULARMATERIALSOURCE | 900 - 4600
EMISSIVEMATERIALSOURCE | 900 - 4500
SetMaterial | 1000 - 3700
ZENABLE | 700 - 3900
WRAP0 | 1600 - 2700
MINFILTER | 1700 - 2500
MAGFILTER | 1700 - 2400
SetVertexShaderConstant (1 Constant) | 1000 - 2700
COLOROP | 1500 - 2100
COLORARG2 | 1300 - 2000
COLORARG1 | 1300 - 1980
CULLMODE | 500 - 2570
CLIPPING | 500 - 2550
DrawIndexedPrimitive | 1200 - 1400
ADDRESSV | 1090 - 1500
ADDRESSU | 1070 - 1500
DrawPrimitive | 1050 - 1150
SRGBTEXTURE | 150 - 1500
STENCILMASK | 570 - 700
STENCILZFAIL | 500 - 800
STENCILREF | 550 - 700
ALPHABLENDENABLE | 550 - 700
STENCILFUNC | 560 - 680
STENCILWRITEMASK | 520 - 700
STENCILFAIL | 500 - 750
ZFUNC | 510 - 700
ZWRITEENABLE | 520 - 680
STENCILENABLE | 540 - 650
STENCILPASS | 560 - 630
SRCBLEND | 500 - 685
TWOSIDEDSTENCILMODE | 450 - 590
ALPHATESTENABLE | 470 - 525
ALPHAREF | 460 - 530
ALPHAFUNC | 450 - 540
DESTBLEND | 475 - 510
COLORWRITEENABLE | 465 - 515
CCW_STENCILFAIL | 340 - 560
CCW_STENCILPASS | 340 - 545
CCW_STENCILZFAIL | 330 - 495
SCISSORTESTENABLE | 375 - 440
CCW_STENCILFUNC | 250 - 480
SetScissorRect | 150 - 340


Queries
Microsoft DirectX 9.0 SDK Update (October 2004)

Queries

There are several types of queries which are designed to query the status of resources. The status of a given resource includes graphics processing unit (GPU) status, driver status, or runtime status. To understand the difference between the different query types, you need to understand the query states. Here's a state transition diagram that explains each of the query states:

The diagram shows three states, each defined by circles. Each of the solid lines are application-driven events that cause a state transition. The dashed line is a resource-driven event that switches a query from the issued state to the signaled state. Each of these states has a different purpose:

  • The signaled state is like an idle state. The query object has been generated and is waiting for the application to issue the query. Once a query has completed and transitioned back to the signaled state, the answer to the query can be retrieved.
  • The building state is like a staging area for a query. From the building state, a query has been issued (by calling D3DISSUE_BEGIN) but has not yet transitioned to the issued state. When an application issues a query end (by calling D3DISSUE_END), the query transitions to the issued state.
  • The issued state means that the resource being queried has control of the query. Once the resource finishes its work, the resource transitions the state machine to the signaled state. During the issued state, the application must poll to detect the transition to the signaled state. Once the transition to the signaled state occurs, IDirect3DQuery9::GetData returns the query result (through an argument) to the application.

The following table lists the available query types.

Query Type | Issue Event | GetData buffer | Runtime | Implicit beginning of query
BANDWIDTHTIMINGS | D3DISSUE_BEGIN, D3DISSUE_END | D3DDEVINFO_D3D9BANDWIDTHTIMINGS | Retail/Debug | N/A
CACHEUTILIZATION | D3DISSUE_BEGIN, D3DISSUE_END | D3DDEVINFO_D3D9CACHEUTILIZATION | Retail/Debug | N/A
EVENT | D3DISSUE_END | BOOL | Retail/Debug | IDirect3D9::CreateDevice
INTERFACETIMINGS | D3DISSUE_BEGIN, D3DISSUE_END | D3DDEVINFO_D3D9INTERFACETIMINGS | Retail/Debug | N/A
OCCLUSION | D3DISSUE_BEGIN, D3DISSUE_END | DWORD | Retail/Debug | N/A
PIPELINETIMINGS | D3DISSUE_BEGIN, D3DISSUE_END | D3DDEVINFO_D3D9PIPELINETIMINGS | Retail/Debug | N/A
RESOURCEMANAGER | D3DISSUE_END | D3DDEVINFO_RESOURCEMANAGER | Debug only | IDirect3DDevice9::Present
TIMESTAMP | D3DISSUE_END | UINT64 | Retail/Debug | N/A
TIMESTAMPDISJOINT | D3DISSUE_BEGIN, D3DISSUE_END | BOOL | Retail/Debug | N/A
TIMESTAMPFREQ | D3DISSUE_END | UINT64 | Retail/Debug | N/A
VCACHE | D3DISSUE_END | D3DDEVINFO_VCACHE | Retail/Debug | IDirect3D9::CreateDevice
VERTEXSTATS | D3DISSUE_END | D3DDEVINFO_D3DVERTEXSTATS | Debug only | IDirect3DDevice9::Present
VERTEXTIMINGS | D3DISSUE_BEGIN, D3DISSUE_END | D3DDEVINFO_D3D9STAGETIMINGS | Retail/Debug | N/A

Some of the queries require a begin and end event, while others only require an end event. The queries that only require an end event begin when another implicit event occurs (which is listed in the table). All queries return an answer, except the event query whose answer is always TRUE. An application uses either the state of the query or the return code of IDirect3DQuery9::GetData.

Create a Query

Before you create a query, you can check to see if the runtime supports queries by calling IDirect3DDevice9::CreateQuery with a NULL pointer like this:

IDirect3DQuery9* pQuery;

// Create a device pointer m_pd3dDevice

// Create a query object
HRESULT hr = m_pd3dDevice->CreateQuery(D3DQUERYTYPE_EVENT, NULL);

This method returns a success code if a query can be created; otherwise it returns an error code. Once IDirect3DDevice9::CreateQuery succeeds, you can create a query object like this:

IDirect3DQuery9* pQuery;
m_pd3dDevice->CreateQuery(D3DQUERYTYPE_EVENT, &pQuery);

If this call succeeds, a query object is created. The query is essentially idle in the signaled state (with an uninitialized answer) waiting to be issued. When you are finished with the query, release it like any other interface.

Issue a Query

An application changes a query state by issuing a query. Here is an example of issuing a query:

IDirect3DQuery9* pQuery;
m_pD3DDevice->CreateQuery(D3DQUERYTYPE_EVENT, &pQuery);

// Issue a Begin event
pEvent->Issue(D3DISSUE_BEGIN);

or

// Issue an End event
pEvent->Issue(D3DISSUE_END);

A query in the signaled state will transition like this when issued:

Issue Type | Query Transitions to the . . .
D3DISSUE_BEGIN | Building state.
D3DISSUE_END | Issued state.

A query in the building state will transition like this when issued:

Issue Type | Query Transitions to the . . .
D3DISSUE_BEGIN | (No transition, stays in the building state. Restarts the query bracket.)
D3DISSUE_END | Issued state.

An query in the issued state will transition like this when issued:

Issue Type | Query Transitions to the . . .
D3DISSUE_BEGIN | Building state and restarts the query bracket.
D3DISSUE_END | Issued state after abandoning the existing query.

Check the Query State and Get the Answer to the Query

IDirect3DQuery9::GetData does two things:

  1. Returns the query state in the return code.
  2. Returns the answer to the query in pData.
From each of the three query states, here are the IDirect3DQuery9::GetData return codes:

Query State | GetData return code
Signaled | S_OK
Building | Error code
Issued | S_FALSE

For example, when a query is in the issued state and the answer to the query is not available, IDirect3DQuery9::GetData returns S_FALSE. When the resource finishes its work and the application has issued a query end, the resource transitions the query to the signaled state. From the signaled state, IDirect3DQuery9::GetData returns S_OK which means that the answer to the query is also returned in pData. For instance, here is the sequence of events to return the number of pixels drawn in a render sequence:

  • Create the query.
  • Issue a begin event.
  • Draw something.
  • Issue an end event.

The following is the corresponding sequence of code:

IDirect3DQuery9* pQuery;
DWORD numberOfPixelsDrawn;

m_pD3DDevice->CreateQuery(D3DQUERYTYPE_OCCLUSION, &pQuery);

// Add an end marker to the command buffer queue.
pEvent->Issue(D3DISSUE_BEGIN);

// API render loop
...
Draw(...)
...

// Add an end marker to the command buffer queue.
pEvent->Issue(D3DISSUE_END);

// Force the driver to execute the commands from the command buffer.
// Empty the command buffer and wait until the GPU is idle.
while(S_FALSE == pEvent->GetData( &numberOfPixelsDrawn,
                                  sizeof(DWORD), D3DGETDATA_FLUSH ))
    ;

These lines of code do several things:

  • Call IDirect3DQuery9::GetData to return the number of pixels drawn.
  • Specify D3DGETDATA_FLUSH to enable the resource to transition the query to the signaled state.
  • Poll the query resource by calling IDirect3DQuery9::GetData from a loop. As long as IDirect3DQuery9::GetData returns S_FALSE, this means the resource has not returned the answer yet.

The return value of IDirect3DQuery9::GetData essentially tells you in what state the query is. Possible values are S_OK, S_FALSE, and an error. Do not call IDirect3DQuery9::GetData on a query that is in the building state.

  • S_OK means the resource (GPU or driver, or runtime) is finished. The query is returning to the signaled state. The answer (if any) is being returned by IDirect3DQuery9::GetData.
  • S_FALSE means the resource (GPU or driver, or runtime) cannot return an answer yet. This could be because the GPU is not finished or has not seen the work yet.
  • An error means that the query has generated an error from which it cannot recover. This could be the case if the device is lost during a query. Once a query has generated an error (other than S_FALSE), the query must be recreated which will restart the query sequence from the signaled state.

Instead of specifying GETDATA_FLUSH, which provides more up-to-date information, you could supply zero which is a more light-weight check if the query is in the issued state. Since the runtime queues up work in the command buffer, GETDATA_FLUSH is a mechanism for flushing the command buffer to the driver (and hence the GPU; see Accurately Profiling Direct3D API Calls). During the command buffer flush, a query may transition to the signaled state.

Example: An Event Query

An event query does not support a begin event.

  • Create the query.
  • Issue an end event.
  • Poll until the GPU is idle.
  • Issue an end event.
IDirect3DQuery9* pQuery;
m_pD3DDevice->CreateQuery(D3DQUERYTYPE_EVENT, &pQuery);

// Add an end marker to the command buffer queue.
pEvent->Issue(D3DISSUE_END);

// Empty the command buffer and wait until the GPU is idle.
while(S_FALSE == pEvent->GetData( NULL, 0, D3DGETDATA_FLUSH ))
    ;

... // API calls

// Add an end marker to the command buffer queue.
pEvent->Issue(D3DISSUE_END);

// Force the driver to execute the commands from the command buffer.
// Empty the command buffer and wait until the GPU is idle.
while(S_FALSE == pEvent->GetData( NULL, 0, D3DGETDATA_FLUSH ))
    ;

This is the sequence of commands an event query uses to profile application programming interface (API) calls (see Accurately Profiling Direct3D API Calls). This sequence uses markers to help control the amount of work in the command buffer.


Efficiently Drawing Multiple Instances of Geometry
Microsoft DirectX 9.0 SDK Update (October 2004)

Efficiently Drawing Multiple Instances of Geometry

Given a scene that contains many objects that use the same geometry, you can draw many instances of that geometry at different orientations, sizes, colors, and so on with dramatically better performance by reducing the amount of data you need to supply to the renderer.

This can be accomplished through the use of two techniques: the first for drawing indexed geometry and the second for non-indexed geometry. Both techniques use two vertex buffers: one to supply geometry data and one to supply per-object instance data. The instance data can be a wide variety of information such as a transform, color data, or lighting data—basically anything that you can describe in a vertex declaration. Drawing many instances of geometry with these techniques can dramatically reduce the amount of data sent to the renderer.

  • Drawing Indexed Geometry
  • Drawing Non-Indexed Geometry
  • Related Topics

Drawing Indexed Geometry

The vertex buffer contains per-vertex data that is defined by a vertex declaration. Suppose that part of each vertex contains geometry data, and part of each vertex contains per-object instance data. This would look like this:

Figure 1: Indexed Geometry Vertex Buffer Layout

This technique requires a device that supports the 3_0 vertex shader model. This technique works with any programmable shader but not with the fixed function pipeline.

For the vertex buffers shown above, here are the corresponding vertex buffer declarations:

const D3DVERTEXELEMENT9 g_VBDecl_Geometry[] =
{
{0,  0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0},
{0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL,   0},
{0, 24, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT,  0},
{0, 36, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BINORMAL, 0},
{0, 48, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0},
D3DDECL_END()
};

const D3DVERTEXELEMENT9 g_VBDecl_InstanceData[] =
{
{1, 0,  D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1},
{1, 16, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2},
{1, 32, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3},
{1, 48, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4},
{1, 64, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR,    0},
D3DDECL_END()
};

These declarations define two vertex buffers. The first declaration (for stream 0, indicated by the zeros in column 1) defines the geometry data which consists of: position, normal, tangent, binormal, and texture coordinate data.

The second declaration (for stream 1, indicated by the ones in column 1) defines the per-object instance data. Each instance is defined by four four-component floating point numbers, and a four-component color. The first four values could be used to initialize a 4x4 matrix, which means that this data will uniquely size, position, and rotate each instance of the geometry. The first four components use a texture coordinate semantic which, in this case, means "this is a general four-component number." When you use arbitrary data in a vertex declaration, use a texture coordinate semantic to mark it. The last element in the stream is used for color data. This could be applied in the vertex shader to give each instance a unique color.

Before rendering, you need to call IDirect3DDevice9::SetStreamSourceFreq to bind the vertex buffer streams to the device. Here is an example that binds both vertex buffers:

// Set up the geometry data stream
pd3dDevice->SetStreamSourceFreq(0,
    (D3DSTREAMSOURCE_INDEXEDDATA | g_numInstancesToDraw));
pd3dDevice->SetStreamSource(0, g_VB_Geometry, 0,
    D3DXGetDeclVertexSize( g_VBDecl_Geometry, 0 ));

// Set up the instance data stream
pd3dDevice->SetStreamSourceFreq(1,
    (D3DSTREAMSOURCE_INSTANCEDATA | 1));
pd3dDevice->SetStreamSource(1, g_VB_InstanceData, 0,
    D3DXGetDeclVertexSize( g_VBDecl_InstanceData, 1 ));

IDirect3DDevice9::SetStreamSourceFreq uses D3DSTREAMSOURCE_INDEXEDDATA to identify the the indexed geometry data. In this case, stream 0 contains the indexed data that describes the object geometry. This value is logically combined with the number of instances of the geometry to draw.

In the second call, IDirect3DDevice9::SetStreamSourceFreq uses D3DSTREAMSOURCE_INSTANCEDATA to identify the stream containing the instance data. This value is logically combined with 1 since each vertex contains one set of instance data.

The last two calls to IDirect3DDevice9::SetStreamSource bind the vertex buffer pointers to the device.

When you are finished rendering the instance data, be sure to reset the vertex stream frequency back to its default state (which does not use instancing). Because this example used two streams, set both streams as shown below:

pd3dDevice->SetStreamSourceFreq(0,1);
pd3dDevice->SetStreamSourceFreq(1,1);

Indexed Geometry Performance Comparison

While it is not possible to make a single conclusion about how much this technique could reduce the render time in every application, consider the difference in the amount of data streamed into the runtime and the number of state changes that will be reduced if you use the instancing technique. This render sequence takes advantage of drawing multiple instances of the same geometry:

if( SUCCEEDED( pd3dDevice->BeginScene() ) )
{
    // Set up the geometry data stream
    pd3dDevice->SetStreamSourceFreq(0,
               (D3DSTREAMSOURCE_INDEXEDDATA | g_numInstancesToDraw));
    pd3dDevice->SetStreamSource(0, g_VB_Geometry, 0,
                D3DXGetDeclVertexSize( g_VBDecl_Geometry, 0 ));

    // Set up the instance data stream
    pd3dDevice->SetStreamSourceFreq(1,
               (D3DSTREAMSOURCE_INSTANCEDATA | 1));
    pd3dDevice->SetStreamSource(1, g_VB_InstanceData, 0,
                D3DXGetDeclVertexSize( g_VBDecl_InstanceData, 1 ));

    pd3dDevice->SetVertexDeclaration( ... );
    pd3dDevice->SetVertexShader( ... );
    pd3dDevice->SetIndices( ... );

    pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0,
                g_dwNumVertices, 0, g_dwNumIndices/3 );

    pd3dDevice->EndScene();
}

Notice that the render loop is called once, the geometry data is streamed once, and n instances are streamed once. This next render sequence is identical in functionality, but does not take advantage of instancing:

if( SUCCEEDED( pd3dDevice->BeginScene() ) )
{
    for(int i=0; i < g_numObjects; i++)
    {
        // Set up the geometry data stream
        pd3dDevice->SetStreamSourceFreq(0,
               (D3DSTREAMSOURCE_INDEXEDDATA | g_numInstancesToDraw));
        pd3dDevice->SetStreamSource(0, g_VB_Geometry, 0,
                D3DXGetDeclVertexSize( g_VBDecl_Geometry, 0 ));

        // Set up the instance data stream
        pd3dDevice->SetStreamSourceFreq(1,
               (D3DSTREAMSOURCE_INSTANCEDATA | 1));
        pd3dDevice->SetStreamSource(1, g_VB_InstanceData, 0,
                D3DXGetDeclVertexSize( g_VBDecl_InstanceData, 1 ));

        pd3dDevice->SetVertexDeclaration( ... );
        pd3dDevice->SetVertexShader( ... );
        pd3dDevice->SetIndices( ... );

        pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0,
                g_dwNumVertices, 0, g_dwNumIndices/3 );
    }

    pd3dDevice->EndScene();
}

Notice that the entire render loop is wrapped by a second loop to draw each object. Now the geometry data is streamed into the renderer n times (instead of once) and any pipeline states may also be set redundantly for each object drawn. This render sequence is very likely to be significantly slower. Notice also that the parameters to IDirect3DDevice9::DrawIndexedPrimitive have not changed between the two render loops.

Drawing Non-Indexed Geometry

In Drawing Indexed Geometry, vertex buffers were configured to draw multiple instances of indexed geometry with greater efficiency. You can also use IDirect3DDevice9::SetStreamSourceFreq to draw non-indexed geometry. This requires a different vertex buffer layout and has different constraints. To draw non-indexed geometry, prepare your vertex buffers like this:

Figure 2: Non-Indexed Geometry Vertex Buffer Layout

This technique is not supported by hardware acceleration on any device. It is only supported by software vertex processing and will work only with vs_3_0 shaders.

Because this technique works with non-indexed geometry, there is no index buffer. As the diagram shows, the vertex buffer that contains geometry contains n copies of the geometry data. For each instance drawn, the geometry data is read from the first vertex buffer and the instance data is read from the second vertex buffer.

Here are the corresponding vertex buffer declarations:

const D3DVERTEXELEMENT9 g_VBDecl_Geometry[] =
{
{0,  0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0},
{0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL,   0},
{0, 24, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT,  0},
{0, 36, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BINORMAL, 0},
{0, 48, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0},
D3DDECL_END()
};

const D3DVERTEXELEMENT9 g_VBDecl_InstanceData[] =
{
{1, 0,  D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1},
{1, 16, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2},
{1, 32, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3},
{1, 48, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 4},
{1, 64, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR,    0},
D3DDECL_END()
};

These declarations are identical to the declarations made in the indexed geometry example. Once again, the first declaration (for stream 0) defines the geometry data and the second declaration (for stream 1) defines the per-object instance data. When you create the first vertex buffer, be sure to load it with the number of instances of the geometry data that you will be drawing.

Before rendering, you need to set up the divider which tells the runtime how to divide up the first vertex buffer into n instances. Then set the divider using IDirect3DDevice9::SetStreamSourceFreq like this:

// Given n instances, m vertices per instance
float fDivider = n / m;

// Set the divider
pd3dDevice->SetStreamSourceFreq(0, fDivider);
// Bind the stream to the vertex buffer
pd3dDevice->SetStreamSource(0, g_VB_Geometry, 0,
        D3DXGetDeclVertexSize( g_VBDecl_Geometry, 0 ));

// Set up the instance data stream
pd3dDevice->SetStreamSourceFreq(1, m);
pd3dDevice->SetStreamSource(1, g_VB_InstanceData, 0,
        D3DXGetDeclVertexSize( g_VBDecl_InstanceData, 1 ));

The first call to IDirect3DDevice9::SetStreamSourceFreq says that stream 0 uses fDivider to identify the stride of the data in vertex buffer 1. Recall that the first buffer contains n instances of m vertices. IDirect3DDevice9::SetStreamSourceFreq then binds stream 0 to the geometry vertex buffer.

In the second call, IDirect3DDevice9::SetStreamSourceFreq identifies stream 1 as the source of the instance data. The second parameter is the number of vertices in each object (m). Remember that the instance data stream must always be declared as the second stream. IDirect3DDevice9::SetStreamSourceFreq then binds stream 1 to the vertex buffer that contains the instance data.

In general, the vertex offset (in the vertex buffer) is computed as follows:

VertexOffset = StartVertex / Divider * StreamStride +
               VertexIndex / Divider * StreamStride + StreamOffset

Note that the division in this equation is an integer division. The range of the frequency divider is:

0 < Divider <= 216 - 1

When you are finished rendering the instance data, be sure to reset the vertex stream frequency back to its default state. Because this example used two streams, set both streams as shown below:

pd3dDevice->SetStreamSourceFreq(0,1);
pd3dDevice->SetStreamSourceFreq(1,1);

Non-Indexed Geometry Performance Comparison

The major advantage of this instancing style is that it can be used on non-indexed geometry. While it is not possible to make a single conclusion about how much this technique could reduce the render time in every application, consider the difference in the amount of data streamed into the runtime, and the number of state changes that will be reduced for the following render sequence:

if( SUCCEEDED( pd3dDevice->BeginScene() ) )
{
 // Given n instances, m vertices per instance
    float fDivider = n / m;

    // Set the divider
    pd3dDevice->SetStreamSourceFreq(0, fDivider);
    pd3dDevice->SetStreamSource(0, g_VB_Geometry, 0,
                D3DXGetDeclVertexSize( g_VBDecl_Geometry, 0 ));

    // Set up the instance data stream
    pd3dDevice->SetStreamSourceFreq(1, m));
    pd3dDevice->SetStreamSource(1, g_VB_InstanceData, 0,
                D3DXGetDeclVertexSize( g_VBDecl_InstanceData, 1 ));

    pd3dDevice->SetVertexDeclaration( ... );
    pd3dDevice->SetVertexShader( ... );
    pd3dDevice->SetIndices( ... );

    pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0,
                g_dwNumVertices, 0, g_dwNumIndices/3 );

    pd3dDevice->EndScene();
}

Notice that the render loop is called once. The geometry data is streamed once although there are n instances of the geometry being streamed. The data from the instance vertex buffer is streamed once. This next render sequence is identical in functionality, but does not take advantage of instancing:

if( SUCCEEDED( pd3dDevice->BeginScene() ) )
{
    for(int i=0; i < g_numObjects; i++)
    {
     // Given n instances, m vertices per instance
        float fDivider = n / m;

        // Set the divider
        pd3dDevice->SetStreamSourceFreq(0, fDivider);
        pd3dDevice->SetStreamSource(0, g_VB_Geometry, 0,
                D3DXGetDeclVertexSize( g_VBDecl_Geometry, 0 ));

        // Set up the instance data stream
        pd3dDevice->SetStreamSourceFreq(1, m));
        pd3dDevice->SetStreamSource(1, g_VB_InstanceData, 0,
                D3DXGetDeclVertexSize( g_VBDecl_InstanceData, 1 ));

        pd3dDevice->SetVertexDeclaration( ... );
        pd3dDevice->SetVertexShader( ... );
        pd3dDevice->SetIndices( ... );

        pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0,
                g_dwNumVertices, 0, g_dwNumIndices/3 );
    }

    pd3dDevice->EndScene();
}

Without instancing, the render loop needs to be wrapped by a second loop to draw each object. By eliminating the second render loop, you should expect better performance due to fewer render state changes that are called inside the loop.

Overall, it is reasonable to expect the indexed technique (Drawing Indexed Geometry) to perform better than the non-indexed technique (Drawing Non-Indexed Geometry) because the indexed technique only streams one copy of the geometry data. Notice that the parameters to IDirect3DDevice9::DrawIndexedPrimitive have not changed for any of the render sequences.

Related Topics

  • Instancing Sample


Programming Tips
Microsoft DirectX 9.0 SDK Update (October 2004)

Programming Tips

This section contains information to help you develop Microsoft DirectX Graphics applications efficiently. The following topics are covered.

  • Asynchronous Notification
  • Driver Internal Errors
  • Multihead
  • Multithreading Issues
  • Performance Optimizations
  • Presenting Multiple Views in Windowed Mode
  • Troubleshooting
  • Working with Device Windows
  • Working with Earlier Drivers
  • Working with Multiple Monitor Systems
  • Working with Mouse Cursors


Asynchronous Notification
Microsoft DirectX 9.0 SDK Update (October 2004)

Asynchronous Notification

There are number of interesting queries on a driver that an application can make if there is no performance cost. In Microsoft DirectX 7.0 and DirectX 8.x, a synchronous query mechanism, GetInfo, worked well for things like statistics, but no performance-critical queries were added. There are other things (like fences) that are inherently asynchronous. This is a simple application programming interface (API) to make both synchronous and asynchronous queries. GetInfo will be retired in DirectX 9.0.

Create a query using IDirect3DDevice9::CreateQuery. This method takes a D3DQUERYTYPE, which defines what kind of query to make and returns a pointer to an IDirect3DQuery9 object. If the query type is not supported, the call returns an error D3DERR_NOTAVAILABLE. Using the query object, the application submits the query to the runtime using IDirect3DQuery9::Issue, and polls the query status using IDirect3DQuery9::GetData. If the query result is available, S_OK is returned; otherwise, S_FALSE is returned. The application is expected to pass an appropriately sized buffer for the query results.

The application has an option to force the runtime to flush the query down to the driver by using D3DGETDATA_FLUSH with IDirect3DQuery9::GetData. It causes a flush, forcing the driver to see the query. In this case, D3DERR_DEVICELOST is returned if the device becomes lost.

All queries are lost when the device is lost, the application has to re-create them. If the device does not support the query and the pQueryID is NULL, the query creation will fail with D3DERR_INVALIDCALL.

The following table summaries important information about each query type.

QuertyType | Valid issue flag | GetData buffer | Runtime | Implicit beginning of query
D3DQUERYTYPE_VCACHE | D3DISSUE_END | D3DDEVINFO_VCACHE | Retail/Debug | CreateDevice
D3DQUERYTYPE_RESOURCEMANAGER | D3DISSUE_END | D3DDEVINFO_RESOURCEMANAGER | Debug only | Present
D3DQUERYTYPE_VERTEXSTATS | D3DISSUE_END | D3DDEVINFO_D3DVERTEXSTATS | Debug only | Present
D3DQUERYTYPE_EVENT | D3DISSUE_END | BOOL | Retail/Debug | CreateDevice
D3DQUERYTYPE_OCCLUSION | D3DISSUE_BEGIN,D3DISSUE_END | DWORD | Retail/Debug | N/A

Flags field for IDirect3DQuery9::Issue:

#define D3DISSUE_END (1 << 0)
// Tells the runtime to issue the end of a query, changing its state to
//   "non-signaled"

#define D3DISSUE_BEGIN (1 << 1) // Tells the runtime to issue the
// beginng of a query.

Flags field for IDirect3DQuery9::GetData:

#define D3DGETDATA_FLUSH (1 << 0) // Tells the runtime to flush
// if the query is outstanding.


Driver Internal Errors
Microsoft DirectX 9.0 SDK Update (October 2004)

Driver Internal Errors

In Microsoft DirectX 9.0, Microsoft Direct3D will allow the driver to return error codes such as E_OUTOFMEMORY, D3DERR_OUTOFVIDEOMEMORY, and D3DERR_UNSUPPORTEDCOLORARG so that an application would be able to respond to them. However, sometimes the application programming interface (API) calls that generated these return types get loaded into a command buffer and are batched up to be sent to the graphics processing unit (GPU) (see Controlling Runtime and Driver Optimizations). In this case, the errors cannot be relayed to the application when action needs to be taken, so the error code is consumed by the runtime and a note is made on the device object that this happened. Later when the application invokes IDirect3DDevice9::Present, IDirect3DDevice9::Present will return D3DERR_DRIVERINTERNALERROR. This is why the best approach for an application to take when receiving a D3DERR_DRIVERINTERNALERROR from IDirect3DDevice9::Present is to destroy and recreate the device.

If you want to try to debug further, here are a couple of suggestions for trying to figure out which API call is generating the error:

  • Because the list of possible return values is not complete, you can try to find which call is failing by surrounding each API call like this:

    TRACE ( "Calling DrawPrimitive" );
d3ddev->DrawPrim(...);
TRACE ( "done\n" );

    The output debug stream should then show the call that is causing the problem.

  • Additionally, for debugging purposes, try calling IDirect3DDevice9::ValidateDevice immediately before each IDirect3DDevice9::DrawPrimitive to see if there is an additional problem with the device driver (unsupported operation, unusable combination of texture formats, etc).

    Note IDirect3DDevice9::ValidateDevice should be used carefully and sparingly because of the amount of validation work the driver needs to perform to return an answer.


Multihead
Microsoft DirectX 9.0 SDK Update (October 2004)

Multihead

Multihead cards are those that have a common frame buffer and accelerator, independent digital-to-analog converters (DACs), and monitor outputs. Such devices can offer much more usable multiple monitor support than a similar number of heterogeneous display adapters.

Multihead cards are exposed in the application programming interface (API) as a single API-level device that can drive several full-screen swap chains. Consequently, all resources are shared with all the heads, and each head has exactly the same capabilities. Each head can be set to independent display modes and can be refreshed (with IDirect3DSwapChain9::Present) at different times. Use IDirect3DDevice9::Present for simultaneous presents.

Each swap chain for a multihead device must be full screen. When a device has entered multihead mode, it must remain full screen. The transition back to windowed mode requires the destruction of the device (except for the normal ALT+TAB-to-minimize operation).

The old method of dividing video memory between the heads and treating each head as a fully independent accelerator will still be a common usage scenario. This proposal does not replace that mechanism unless the application has been specifically coded to function in the Microsoft DirectX 9.0 multihead mode.

Drivers are given adequate knowledge to switch between the two modes of operation.

One head will be called the "master" head, and all other heads on the same card be called "subordinate" heads. If more than one multihead adapter is present in a system, the master and its subordinates from one multihead adapter are called a "group." Groups are denoted by the adapter ordinal of their master head.

The D3DCAPS9 structure has been updated to expose the following new hardware caps.

UINT NumberOfAdaptersInGroup;
UINT MasterAdapterOrdinal;
UINT AdapterOrdinalInGroup;
  • NumberOfAdaptersInGroup is 1 for conventional adapters, and greater than 1 for the master adapter of a multihead card. The value will be 0 for a subordinate adapter of a multihead card. Each card can have at most one master, but might have many subordinates.
  • MasterAdapterOrdinal indicates which device is the master for this subordinate.
  • AdapterOrdinalInGroup indicates the order in which heads are referenced by the API. The master adapter always has AdapterOrdinalInGroup 0. These values do not correspond to the adapter ordinals passed to the IDirect3D9 methods, but apply only to heads within a group.

This definition allows multihead cards to continue to present multiple adapters as if they were independent cards, just as they did in DirectX 8.x.

To create a multihead device, specify the behavior flag DAC in IDirect3D9::CreateDevice. The presentation parameters (an array of D3DPRESENT_PARAMETERS) should contain NumberOfAdaptersInGroup elements. The runtime will assign each element to each head in AdapterOrdinalInGroup numerical order. When DAC is set, each presentation parameter must have:

  • The Windowed member of D3DPRESENT_PARAMETERS set to FALSE (in other words, be full screen).
  • The same value for the EnableAutoDepthStencil member of D3DPRESENT_PARAMETERS.

In addition, if EnableAutoDepthStencil is TRUE, then each of the following fields must have the same value for each D3DPRESENT_PARAMETERS:

  • AutoDepthStencilFormat
  • BackBufferWidth
  • BackBufferHeight
  • BackBufferFormat

If DAC is set, additional calls to IDirect3DDevice9::CreateAdditionalSwapChain are illegal.

If the device was created with the DAC, IDirect3DDevice9::Reset will expect an array of D3DPRESENT_PARAMETERS.

Each D3DPRESENT_PARAMETERS structure passed to IDirect3DDevice9::Reset must be full screen. To switch back to windowed mode, the application must destroy the device and re-create a non-multihead device in windowed mode.

Here is a basic usage scenario:

1. Create multihead device
2. For each swap chain of device:
   3. Call GetBackBuffer for the i-th swapchain
   4. Call SetRenderTarget
   5. Call DrawPrimitive
   6. Optionally call swapchain::Present (or wait until
      all swap chains are drawn and present outside of loop)
7. End the for loop
8. Optionally present all swap chains with device::Present

For more information, see IDirect3D9::CreateDevice and IDirect3DDevice9::GetNumberOfSwapChains.


Multithreading Issues
Microsoft DirectX 9.0 SDK Update (October 2004)

Multithreading Issues

Full-screen Microsoft Direct3D applications provide a window handle to the Direct3D run time. The window is hooked by the run time. This means that all messages passed to the application's window message procedure have first been examined by the Direct3D run time's own message-handling procedure.

Display mode changes are affected by support routines built into the underlying operating system. When mode changes occur, the system broadcasts several messages to all applications. In Direct3D applications, the messages are received on the window procedure thread, which is not necessarily the same thread that called IDirect3DDevice9::Reset or IDirect3D9::CreateDevice (or the final IUnknown::Release of IDirect3DDevice9, which can cause a display mode change). The Direct3D run time maintains several critical sections internally. Because at least one of these critical sections is held across the mode switch caused by IDirect3DDevice9::Reset or IDirect3D9::CreateDevice, these critical sections are still held when the application receives the mode-change related window messages.

This design has some implications for multithreaded applications. In particular, an application must be sure to strongly segregate its window message handling threads from its Direct3D threads. An application that causes a mode change on one thread but makes Direct3D calls on a different thread in its window procedure is in danger of deadlock.

For these reasons, Direct3D is designed so that the methods IDirect3DDevice9::Reset, IDirect3D9::CreateDevice, IDirect3DDevice9::TestCooperativeLevel, or the final Release of IDirect3DDevice9 can only be called from the same thread that handles window messages.


Performance Optimizations
Microsoft DirectX 9.0 SDK Update (October 2004)

Performance Optimizations

Every developer who creates real-time applications that use 3-D graphics is concerned about performance optimization. This section provides guidelines for getting the best performance from your code.

  • General Performance Tips
  • Databases and Culling
  • Batching Primitives
  • Lighting Tips
  • Texture Size
  • Matrix Transforms
  • Using Dynamic Textures
  • Using Dynamic Vertex and Index Buffers
  • Using Meshes
  • Z-Buffer Performance

General Performance Tips

Follow these general guidelines to increase the performance of your application.

  • Clear only when you must.
  • Minimize state changes and group the remaining state changes.
  • Use smaller textures, if you can do so.
  • Draw objects in your scene from front to back.
  • Use triangle strips instead of lists and fans. For optimal vertex cache performance, arrange strips to reuse triangle vertices sooner, rather than later.
  • Gracefully degrade special effects that require a disproportionate share of system resources.
  • Constantly test your application's performance.
  • Minimize vertex buffer switches.
  • Use static vertex buffers where possible.
  • Use one large static vertex buffer per flexible vertex format (FVF) for static objects, rather than one per object.
  • If your application needs random access into the vertex buffer in accelerated graphics port (AGP) memory, choose a vertex format size that is a multiple of 32 bytes. Otherwise, select the smallest appropriate format.
  • Draw using indexed primitives. This can allow for more efficient vertex caching within hardware.
  • If the depth buffer format contains a stencil channel, always clear the depth and stencil channels at the same time.
  • Combine the shader instruction and the data output where possible. For example:
    // Rather than doing a multiply and add, and then output the data with
//   two instructions:
mad r2, r1, v0, c0
mov oD0, r2

// Combine both in a single instruction, because this eliminates an
//   additional register copy.
mad oD0, r1, v0, c0

Databases and Culling

Building a reliable database of the objects in your world is key to excellent performance in Microsoft Direct3D. It is more important than improvements to rasterization or hardware.

You should maintain the lowest polygon count you can possibly manage. Design for a low polygon count by building low-polygon models from the start. Add polygons if you can do so without sacrificing performance later in the development process. Remember, the fastest polygons are the ones you don't draw.

Batching Primitives

To get the best rendering performance during execution, try to work with primitives in batches and keep the number of render-state changes as low as possible. For example, if you have an object with two textures, group the triangles that use the first texture and follow them with the necessary render state to change the texture. Then group all the triangles that use the second texture. The simplest hardware support for Direct3D is called with batches of render states and batches of primitives through the hardware abstraction layer (HAL). The more effectively the instructions are batched, the fewer HAL calls are performed during execution.

Lighting Tips

Because lights add a per-vertex cost to each rendered frame, you can improve performance significantly by being careful about how you use them in your application. Most of the following tips derive from the maxim, "the fastest code is code that is never called."

  • Use as few light sources as possible. To increase the overall lighting level, for example, use the ambient light instead of adding a new light source.
  • Directional lights are more efficient than point lights or spotlights. For directional lights, the direction to the light is fixed and doesn't need to be calculated on a per-vertex basis.
  • Spotlights can be more efficient than point lights, because the area outside the cone of light is calculated quickly. Whether spotlights are more efficient or not depends on how much of your scene is lit by the spotlight.
  • Use the range parameter to limit your lights to only the parts of the scene you need to illuminate. All the light types exit fairly early when they are out of range.
  • Specular highlights almost double the cost of a light. Use them only when you must. Set the D3DRS_SPECULARENABLE render state to 0, the default value, whenever possible. When defining materials, you must set the specular power value to zero to turn off specular highlights for that material; just setting the specular color to 0,0,0 is not enough.

Texture Size

Texture-mapping performance is heavily dependent on the speed of memory. There are a number of ways to maximize the cache performance of your application's textures.

  • Keep the textures small. The smaller the textures are, the better chance they have of being maintained in the main CPU's secondary cache.
  • Do not change the textures on a per-primitive basis. Try to keep polygons grouped in order of the textures they use.
  • Use square textures whenever possible. Textures whose dimensions are 256x256 are the fastest. If your application uses four 128x128 textures, for example, try to ensure that they use the same palette and place them all into one 256x256 texture. This technique also reduces the amount of texture swapping. Of course, you should not use 256x256 textures unless your application requires that much texturing because, as mentioned, textures should be kept as small as possible.

Matrix Transforms

Direct3D uses the world and view matrices that you set to configure several internal data structures. Each time you set a new world or view matrix, the system recalculates the associated internal structures. Setting these matrices frequently—for example, thousands of times per frame—is computationally time-consuming. You can minimize the number of required calculations by concatenating your world and view matrices into a world-view matrix that you set as the world matrix, and then setting the view matrix to the identity. Keep cached copies of individual world and view matrices so that you can modify, concatenate, and reset the world matrix as needed. For clarity in this documentation, Direct3D samples rarely employ this optimization.

Using Dynamic Textures

To find out if the driver supports dynamic textures, check the D3DCAPS2_DYNAMICTEXTURES flag of the D3DCAPS9 structure.

Keep the following things in mind when working with dynamic textures.

  • They cannot be managed. For example, their pool cannot be D3DPOOL_MANAGED.
  • Dynamic textures can be locked, even if they are created in D3DPOOL_DEFAULT.
  • D3DLOCK_DISCARD is a valid lock flag for dynamic textures.

It is a good idea to create only one dynamic texture per format and possibly per size. Dynamic mipmaps, cubes, and volumes are not recommended because of the additional overhead in locking every level. For mipmaps, D3DLOCK_DISCARD is allowed only on the top level. All levels are discarded by locking just the top level. This behavior is the same for volumes and cubes. For cubes, the top level and face 0 are locked.

The following pseudocode shows an example of using a dynamic texture.

DrawProceduralTexture(pTex)
{
    // pTex should not be very small because overhead of
    //   calling driver every D3DLOCK_DISCARD will not
    //   justify the performance gain. Experimentation is encouraged.
    pTex->Lock(D3DLOCK_DISCARD);
    <Overwrite *entire* texture>
    pTex->Unlock();
    pDev->SetTexture();
    pDev->DrawPrimitive();
}

Using Dynamic Vertex and Index Buffers

Locking a static vertex buffer while the graphics processor is using the buffer can have a significant performance penalty. The lock call must wait until the graphics processor is finished reading vertex or index data from the buffer before it can return to the calling application, a significant delay. Locking and then rendering from a static buffer several times per frame also prevents the graphics processor from buffering rendering commands, since it must finish commands before returning the lock pointer. Without buffered commands, the graphics processor remains idle until after the application is finished filling the vertex buffer or index buffer and issues a rendering command.

Ideally the vertex or index data would never change, however this is not always possible. There are many situations where the application needs to change vertex or index data every frame, perhaps even multiple times per frame. For these situations, the vertex or index buffer should be created with D3DUSAGE_DYNAMIC. This usage flag causes Direct3D to optimize for frequent lock operations. D3DUSAGE_DYNAMIC is only useful when the buffer is locked frequently; data that remains constant should be placed in a static vertex or index buffer.

To receive a performance improvement when using dynamic vertex buffers, the application must call IDirect3DVertexBuffer9::Lock or IDirect3DIndexBuffer9::Lock with the appropriate flags. D3DLOCK_DISCARD indicates that the application does not need to keep the old vertex or index data in the buffer. If the graphics processor is still using the buffer when lock is called with D3DLOCK_DISCARD, a pointer to a new region of memory is returned instead of the old buffer data. This allows the graphics processor to continue using the old data while the application places data in the new buffer. No additional memory management is required in the application; the old buffer is reused or destroyed automatically when the graphics processor is finished with it. Note that locking a buffer with D3DLOCK_DISCARD always discards the entire buffer, specifying a nonzero offset or limited size field does not preserve information in unlocked areas of the buffer.

There are cases where the amount of data the application needs to store per lock is small, such as adding four vertices to render a sprite. D3DLOCK_NOOVERWRITE indicates that the application will not overwrite data already in use in the dynamic buffer. The lock call will return a pointer to the old data, allowing the application to add new data in unused regions of the vertex or index buffer. The application should not modify vertices or indices used in a draw operation as they might still be in use by the graphics processor. The application should then use D3DLOCK_DISCARD after the dynamic buffer is full to receive a new region of memory, discarding the old vertex or index data after the graphics processor is finished.

The asynchronous query mechanism is useful to determine if vertices are still in use by the graphics processor. Issue a query of type D3DQUERYTYPE_EVENT after the last DrawPrimitive call that uses the vertices. The vertices are no longer in use when IDirect3DQuery9::GetData returns S_OK. Locking a buffer with D3DLOCK_DISCARD or no flags will always guarantee the vertices are synchronized properly with the graphics processor, however using lock without flags will incur the performance penalty described earlier. Other application programming interface (API) calls such as IDirect3DDevice9::BeginScene, IDirect3DDevice9::EndScene, and IDirect3DDevice9::Present do not guarantee the graphics processor is finished using vertices.

Below are ways to use dynamic buffers and the proper lock flags.

    // USAGE STYLE 1
    // Discard the entire vertex buffer and refill with thousands of vertices.
    // Might contain multiple objects and/or require multiple DrawPrimitive
    //   calls separated by state changes, etc.

    // Determine the size of data to be moved into the vertex buffer.
    UINT nSizeOfData = nNumberOfVertices * m_nVertexStride;

    // Discard and refill the used portion of the vertex buffer.
    CONST DWORD dwLockFlags = D3DLOCK_DISCARD;

    // Lock the vertex buffer.
    BYTE* pBytes;
    if( FAILED( m_pVertexBuffer->Lock( 0, 0, &pBytes, dwLockFlags ) ) )
        return false;

    // Copy the vertices into the vertex buffer.
    memcpy( pBytes, pVertices, nSizeOfData );
    m_pVertexBuffer->Unlock();

    // Render the primitives.
    m_pDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, nNumberOfVertices/3)

    // USAGE STYLE 2
    // Reusing one vertex buffer for multiple objects

    // Determine the size of data to be moved into the vertex buffer.
    UINT nSizeOfData = nNumberOfVertices * m_nVertexStride;

    // No overwrite will be used if the vertices can fit into
    //   the space remaining in the vertex buffer.
    DWORD dwLockFlags = D3DLOCK_NOOVERWRITE;

    // Check to see if the entire vertex buffer has been used up yet.
    if( m_nNextVertexData > m_nSizeOfVB - nSizeOfData )
    {
        // No space remains. Start over from the beginning
        //   of the vertex buffer.
        dwLockFlags = D3DLOCK_DISCARD;
        m_nNextVertexData = 0;
    }

    // Lock the vertex buffer.
    BYTE* pBytes;
    if( FAILED( m_pVertexBuffer->Lock( (UINT)m_nNextVertexData, nSizeOfData,
               &pBytes, dwLockFlags ) ) )
        return false;

    // Copy the vertices into the vertex buffer.
    memcpy( pBytes, pVertices, nSizeOfData );
    m_pVertexBuffer->Unlock();

    // Render the primitives.
    m_pDevice->DrawPrimitive( D3DPT_TRIANGLELIST,
               m_nNextVertexData/m_nVertexStride, nNumberOfVertices/3)

    // Advance to the next position in the vertex buffer.
    m_nNextVertexData += nSizeOfData;

Using Meshes

You can optimize meshes by using Direct3D indexed triangles instead of indexed triangle strips. The hardware will discover that 95 percent of successive triangles actually form strips and adjust accordingly. Many drivers do this for older hardware also.

D3DX mesh objects can have each triangle, or face, tagged with a DWORD, called the attribute of that face. The semantics of the DWORD are user-defined. They are used by D3DX to classify the mesh into subsets. The application sets per-face attributes using the ID3DXMesh::LockAttributeBuffer call. The ID3DXMesh::Optimize method has an option to group the mesh vertices and faces on attributes using the D3DXMESHOPT_ATTRSORT option. When this is done, the mesh object calculates an attribute table that can be obtained by the application by calling ID3DXBaseMesh::GetAttributeTable. This call returns 0 if the mesh is not sorted by attributes. There is no way for an application to set an attribute table because it is generated by the ID3DXMesh::Optimize method. The attribute sort is data sensitive, so if the application knows that a mesh is attribute sorted, it still needs to call ID3DXMesh::Optimize to generate the attribute table.

The following topics describe the different attributes of a mesh.

Attribute ID

An attribute identifier (ID) is a value that associates a group of faces with an attribute group. This ID describes which subset of faces ID3DXBaseMesh::DrawSubset should draw. Attribute IDs are specified for the faces in the attribute buffer. The actual values of the attribute IDs can be anything that fits in 32 bits, but it is common to use 0 to n where n is the number of attributes.

Attribute Buffer

The attribute buffer is an array of DWORDs (one per face) that specifies which attribute group each face belongs in. This buffer is initialized to zero on creation of a mesh, but is either filled by the load routines or must be filled by the user if more than one attribute with ID 0 is desired. This buffer contains the information that is used to sort the mesh based on attributes in ID3DXMesh::Optimize. If no attribute table is present, ID3DXBaseMesh::DrawSubset scans this buffer to select the faces of the given attribute to draw.

Attribute Table

The attribute table is a structure owned and maintained by the mesh. The only way for one to be generated is by calling ID3DXMesh::Optimize with attribute sorting or stronger optimization enabled. The attribute table is used to quickly initiate a single draw primitive call to ID3DXBaseMesh::DrawSubset. The only other use is that progressing meshes also maintain this structure, so it is possible to see what faces and vertices are active at the current level of detail.

Z-Buffer Performance

Applications can increase performance when using z-buffering and texturing by ensuring that scenes are rendered from front to back. Textured z-buffered primitives are pretested against the z-buffer on a scan line basis. If a scan line is hidden by a previously rendered polygon, the system rejects it quickly and efficiently. Z-buffering can improve performance, but the technique is most useful when a scene draws the same pixels more than once. This is difficult to calculate exactly, but you can often make a close approximation. If the same pixels are drawn less than twice, you can achieve the best performance by turning z-buffering off and rendering the scene from back to front.


Presenting Multiple Views in Windowed Mode
Microsoft DirectX 9.0 SDK Update (October 2004)

Presenting Multiple Views in Windowed Mode

In addition to the swap chain that is owned and manipulated through the IDirect3DDevice9 interface, an application can create additional swap chains in order to present multiple views from the same device. The application typically creates one swap chain per view by using the IDirect3DDevice9::CreateAdditionalSwapChain method, and associates each swap chain with a particular window. The application renders images into the back buffers of each swap chain, and then presents them individually.

Only one swap chain at a time can be full-screen on each adapter.


Troubleshooting
Microsoft DirectX 9.0 SDK Update (October 2004)

Troubleshooting

This topic lists common categories of problems that you might encounter when writing Microsoft Direct3D applications, and how to prevent them.

Device Creation

If your application fails during device creation, check for the following common errors.

  • Make sure you check the device capabilities, particularly the render depths.
  • Examine the error code. D3DERR_OUTOFVIDEOMEMORY is always possible.
  • Use the debug Microsoft DirectX dynamic-link libraries (DLLs) and review output messages under the debugger.

Using Lit Vertices

Applications that use lit vertices should disable the Direct3D lighting engine by setting the D3DRS_LIGHTING render state to FALSE. By default, when lighting is enabled, the system sets the color for any vertex that doesn't contain a normal vector to 0 (black), even if the input vertex contained a nonzero color value. Because lit-vertices don't, by their nature, contain a vertex normal, any color information passed to Direct3D is lost during rendering if the lighting engine is enabled.

Obviously, vertex color is important to any application that performs its own lighting. To prevent the system from imposing the default values, make sure you set D3DRS_LIGHTING to FALSE.

If your application runs but nothing is visible, check for the following common errors.

  • Ensure that your triangles are not degenerate.
  • Ensure that your triangles are not being culled.
  • Make sure that your transformations are internally consistent.
  • Check the viewport settings to be sure they allow your triangles to be seen.

Debugging

Debugging a Direct3D application can be challenging. Try the following techniques, in addition to checking all the return values—a particularly important piece of advice in Direct3D programming, which is dependent on very different hardware implementations.

  • Switch to debug DLLs.
  • Force a software-only device, turning off hardware acceleration even when it is available.
  • Force surfaces into system memory.
  • Create an option to run in a window, so that you can use an integrated debugger.

The second and third options in this list can help you avoid the Win16 lock which can otherwise cause your debugger to hang.

Also, try adding the following entries to Win.ini.

[Direct3D]
debug=3
[DirectDraw]
debug=3

Borland Floating-Point Initialization

Compilers from Borland report floating-point exceptions in a manner that is incompatible with Direct3D. To solve this problem, include a _matherr exception handler like the following:

// Borland floating point initialization
#include <math.h>
#include <float.h>

void initfp(void)
{
    // Disable floating point exceptions
    _control87(MCW_EM,MCW_EM);
}

int _matherr(struct _exception  *e)
{
    e;               // Dummy reference to catch the warning
    return 1;        // Error has been handled
}

Parameter Validation

For performance reasons, the debug version of the Direct3D Immediate Mode run time performs more parameter validation than the retail version, which sometimes performs no validation at all. This enables applications to perform robust debugging with the slower debug run-time component before using the faster retail version for performance tuning and final release.

Although several Direct3D Immediate Mode methods impose limits on the values that they can accept, these limits are often only checked and enforced by the debug version of the Direct3D Immediate Mode run time. Applications must conform to these limits, or unpredictable and undesirable results can occur when running on the retail version of Direct3D. For example, the IDirect3DDevice9::DrawPrimitive method accepts a parameter (PrimitiveCount) that indicates the number of primitives that the method will render. The method can only accept values between 0 and D3DMAXNUMPRIMITIVES. In the debug version of Direct3D, if you pass more than D3DMAXNUMPRIMITIVES primitives, the method fails gracefully, printing an error message to the error log, and returning an error value to your application. Conversely, if your application makes the same error when it is running with the retail version of the run time, behavior is undefined. For performance reasons, the method does not validate the parameters, resulting in unpredictable and completely situational behavior when they are not valid. In some cases the call might work, and in other cases it might cause a memory fault in Direct3D. If an invalid call consistently works with a particular hardware configuration and DirectX version, there is no guarantee that it will continue to function on other hardware or with later releases of DirectX.

If your application encounters unexplained failures when running with the retail Direct3D run-time file, test against the debug version and look closely for cases where your application passes invalid parameters. Use the DirectX control panel applet, switch to the debug runtime if necessary, and check the "Break on D3DError" option. This option will force the runtime to use the Windows DebugBreak method in order to force the application to stop when an application bug is detected.


Working with Device Windows
Microsoft DirectX 9.0 SDK Update (October 2004)

Working with Device Windows

This section lists an issue that you might encounter when working with device windows in Microsoft Direct3D applications.

  • Direct3D only hooks up the focus windows instead of the device window with the Direct3D message processing function, and only processes the focus window messages. So, the focus window should be the parent of any device window.


Working with Earlier Drivers
Microsoft DirectX 9.0 SDK Update (October 2004)

Working with Earlier Drivers

This section lists issues that can be encountered when working with Microsoft DirectX 9.0 on drivers written for versions of DirectX earlier than DirectX 9.0.

  • When working with a TnLHAL device, the fog intensity is computed but the absolute value operation is not applied to this value. Rather, the value is left negative if that is what is computed. The best way to avoid this situation is to set up transforms appropriately. A less-preferred method is to make the fog-start and fog-end values negative to match.

To check for a DirectX 9.0 driver, look for a nonzero value for D3DDEVCAPS2_STREAMOFFSET in the DevCaps2 member of D3DCAPS9.


Working with Multiple Monitor Systems
Microsoft DirectX 9.0 SDK Update (October 2004)

Working with Multiple Monitor Systems

The concept of exclusive full-screen mode is retained in Microsoft DirectX 9.0, but it is kept entirely implicit in the IDirect3D9::CreateDevice and IDirect3DDevice9::Reset method calls. Whenever a device is successfully reset or created in full-screen operation, the Microsoft Direct3D object that created the device is marked as owning all adapters on that system. This state is known as exclusive mode, and at this point the Direct3D object owns exclusive mode. Exclusive mode means that devices created by any other Direct3D9 object can neither assume full-screen operation nor allocate video memory. In addition, when a Direct3D9 object assumes exclusive mode, all devices other than the device that went full-screen are placed into the lost state. For information about how to handle lost devices, see Lost Devices.

Along with exclusive mode, the Direct3D9 object is informed of the focus window to be used by the device. Exclusive mode is released when the last full-screen device owned by that Direct3D9 object is either reset to windowed mode or destroyed.

Devices can be divided into two categories when a Direct3D9 object owns exclusive mode. The first category of devices are those that were created by the same Direct3D9 object that created the device that is already full-screen, have the same focus window as the device that is already full-screen, and represent a different adapter from any full-screen device. Devices in this category have no restrictions concerning their ability to be reset or created and are not placed into the lost state. Devices in this category can even be placed into full-screen mode.

Devices not in this category, which would be those created by a different Direct3D9 object, or with a different focus window, or for some adapter with a device already full-screen cannot be reset and remain in the lost state until exclusive mode is lost.

The practical implication is that a multiple monitor application can place several devices in full-screen mode, but only if all these devices are for different adapters, were created by the same Direct3D9 object, and all share the same focus window.

Note When you create a new device using the same IDirect3D9 object and focus window, your original device will lose its surfaces. You will need to call IDirect3DDevice9::Reset on the first device in order for your application to use it. For example, to create two devices, do the following:

  1. Create Device 1.
  2. Create Device 2.
  3. Reset Device 1.


Working with Mouse Cursors
Microsoft DirectX 9.0 SDK Update (October 2004)

Working with Mouse Cursors

The mouse cursor methods enable the application to specify a color cursor by providing a surface that contains an image. The system will ensure that this cursor will be updated at half the display rate or more if the application's frame rate is slow. However, the cursor will never be updated more frequently than the display refresh rate.

The mouse cursor position is tied to the system cursor, appropriately scaled for the current display mode spatial resolution, but it can be moved explicitly by the application. This is analogous to the behavior of the Microsoft Win32 application programming interface (API)–supported system mouse cursor. For more information about how to use a mouse cursor in your Microsoft Direct3D application, see the following reference topics.

  • IDirect3DDevice9::ShowCursor
  • IDirect3DDevice9::SetCursorPosition
  • IDirect3DDevice9::SetCursorProperties

Direct3D ensures that the mouse is supported either by hardware implementations or by the Direct3D run time that performs hardware-accelerated blitting operations when calling IDirect3DDevice9::Present.


Tools
Microsoft DirectX 9.0 SDK Update (October 2004)

Tools

This section contains tools to help you develop Microsoft DirectX graphics applications efficiently. The tools are listed in the order you are likely to need them:

  • PIX
  • DirectX Extensions for Visual Studio .NET
  • Enabling Direct3D Debug Information
  • HLSL Command-Line Compiler
  • Vertex Shader Command-Line Assembler
  • Pixel Shader Command-Line Assembler
  • Mesh Viewer
  • Texture Viewer
  • Texture File Converter
  • Photoshop Texture Converter
  • Effect File Exporter (Maya Preview Pipeline)
  • X File Exporter for Discreet's 3ds max
  • DXTex
  • texconv
  • D3DSpy

Related Topics

  • DirectX Tools


PIX
Microsoft DirectX 9.0 SDK Update (October 2004)

PIX

PIX is a tool for analyzing applications that use Microsoft Direct3D. It has a wide variety of uses, both for programmers and for quality assurance engineers, depending on how it is configured. PIX can be used to perform tasks such as:

  • Gathering and analyzing statistics to help understand why some frames render more slowly than others.
  • Gathering and analyzing statistics to identify inefficient usage of application programming interfaces (APIs) and system resources.
  • Monitoring daily builds of an application for unexpected changes in performance or appearance.
  • Grabbing and comparing screenshots of the application running in different circumstances, such as a hardware abstraction layer (HAL) device vs. a reference device (see Device Types).
  • Capturing and replaying a full Direct3D call sequence to use for further analysis or for bug reporting.

There are four main steps to using PIX:

  1. Preparing an Experiment File - Specify what application to analyze and what data to gather.
  2. Modifying the Target Program (Optional) - Modify the application to interoperate with PIX (optional).
  3. Running the Experiment - Gather the PIX data and save it to run files and image files.
  4. Analyzing PIX Data - View run files and image files generated by PIX.

Terminology Used
Item | Description
Target Program | The user-specified application that is being profiled. This information is entered by the user in the experiment before data collection starts.
Experiment File | The experiment file that contains all of the user-specified settings for collecting profiler data. Open the experiment file in PIX to set up the experiment to run. Specify per-frame data gathering options in the experiment by selecting one or more counters to collect data. (see PIX Counters)
Run File | The output file that contains all of the profile data. Open this file from PIX to see all the data that was collected.

Preparing an Experiment File

A PIX "experiment" specifies what application to analyze, and what data to gather while analyzing it. This information can be saved to a PIX Experiment file (.PIXExp) for reuse in multiple analysis sessions. For several simple data-gathering scenarios, it is possible to use the Basic View of experiments to generate the experiment file without needing to understand the structure of PIX experiments. The Advanced View of experiments lets you control analysis behavior in greater detail. The experiment consists of two main areas, each on its own tab within Experiment Advanced View: Triggers/Actions and Target Program.

PIX Advanced View, showing Triggers and Actions

Triggers and Actions

PIX experiments specify triggers, such as a time, frame number, or event, that cause actions to be executed. Actions are behaviors that PIX can take such as gathering data or changing state. Each trigger can have multiple actions attached to it. A typical experiment will have several triggers, each of which has some actions attached to it. The triggers and actions are represented as a tree in the PIX experiment user interface.

Trigger | Description
Program Start | Execute the attached actions when the target program starts.
Frame | Execute the attached actions on the specified frame.
Time | Execute the attached actions at the specified time.
User Marker | Execute the attached actions when the target program calls D3DPERF_SetMarker with the specified marker name.
Begin User Event | Execute the attached actions when the target program calls D3DPERF_BeginEvent with the specified event name.
End User Event | Execute the attached actions when the target program calls D3DPERF_EndEvent to end the event with the specified name.

Each trigger can specify one or more of the following actions:

Action | Description
Create Run File | Open a new PIX run file.
Grab Screenshot | Copy the contents of the frame buffer and save it to an image file.
Modify Direct3D Device | At the next CreateDevice call, force the device to switch from hardware acceleration to the REF device. This trigger is often used when performing two screen captures to compare performance between the correct (but slow) rendering of a reference device and the fast rendering of a hardware accelerated device.
Modify Draw Calls | Enable or disable draw calls.
Set Per-Frame Counters | Identify one or more counters. Each counter gathers some information per frame.
Set Call Capture | Capture all the calls executed. This call stream is in the order in which the API commands are executed. Use this stream to identify all the API calls between frames, time markers, or user markers, for instance.
Terminate Program | End the target application. In the data-gathering mode, this terminates the collection of data and closes the PIXRun file that has been collecting per-frame counter data (see Analyzing PIX Data). In the data-analysis mode, this action terminates the PIX window.

Target Program Settings

PIX experiments also specify information about what application to launch in order to start the analysis session. In the Experiment Advanced View, click the Target Program tab to specify the path, startup folder, and command-line arguments to be used when launching the application. In some situations the application launched may be a helper program that ends up launching the application that you want to analyze. In this situation, you can set a number in Skip processes before gathering to instruct PIX which application to analyze.

Modifying the Target Program (Optional)

PIX can analyze applications without the need to modify them at all. However, more powerful analysis is possible when the target program makes certain Direct3D calls to communicate with PIX. It is also possible to modify an application so that PIX cannot analyze it.

Use the following API calls to instrument (or modify) an application for PIX analysis:

Function | Description
D3DPERF_SetMarker | Specifies a user marker that PIX can use to trigger actions.
D3DPERF_BeginEvent or D3DPERF_EndEvent | Specifies a user event that PIX can use to trigger actions. PIX also uses events to add structure to logged calls.
D3DPERF_SetOptions | Controls how PIX behaves. Currently the only defined behavior is that calling D3DPERF_SetOptions(1) tells PIX to not analyze the application.

Running the Experiment

A PIX experiment can be started using the user interface, or from the command line. From the user interface, click the Start Experiment button or choose Start Experiment from the File menu with an experiment file open.

From the command line, you can issue a command like this, assuming that PIXWin.exe is in the path:

start /wait PIXWin.exe file.PIXExp -start

Command-line operation may be more convenient when setting up an automated batch action such as overnight testing.

Analyzing PIX Data

During an experiment, PIX generates one of three types of data:

  • Screenshots are stored as standard image files.
  • Frame statistics and call logs are stored in .PIXRun files that can be analyzed by PIX.
  • Full call captures are also stored as .PIXRun files, but they cannot be directly analyzed. Instead, they are used in subsequent PIX experiments to gather more information without the need for the original application, or they can be used as a reproducible case for bug reports.

PIX generates a .PIXRun run file that contains per-frame counter data, depending on what you selected in the experiment. When the experiment is finished collecting data (stopping according to values you set in the experiment), the run file can be opened and displayed by PIX.

The run file data can be viewed in three separate ways:

  • TimeLine View
  • Events View
  • Summary View

TimeLine View

The timeline window contains two displays: the top half displays CPU and graphics processing unit (GPU) load, and the bottom half displays graphs for the values of up to four counters. In the top half, each CPU frame is shown as a gray rectangle, and each GPU frame is shown as a green rectangle. Slow frames show mostly the interior color of the rectangles, while fast frames (which are very narrow) are entirely black because each rectangle has a black outline. The magnifying glass buttons at the bottom of the timeline view can be used to zoom in on the timeline.

Display of counters in PIX TimeLine View

You can use a mouse to select the frame arrow and drag it to any frame. The lower half of this window graphically displays up to four counters using four thin, colored lines.

PIX Timeline View showing CPU and GPU processing loads

Use the drop-down list boxes to specify which counter you want to display. In this example, the black line displays the number of frames displayed per second, and the red line displays the duration of each frame.

Events View

The events window contains a list of all your specified events for which data will be collected. Each event displays some generic attributes like start time, duration, and frame number, as well as the specific attributes that you specify to collect. Click on an event, such as a particular frame, to get the timeline to display information about that event during that frame.

Summary View

The summary window contains a record of what was profiled, and where it is. A user specifies the application to profile, saves settings in the experiment file, and views results in the run file.

Related Topics

  • PIX Tutorials


PIX Counters
Microsoft DirectX 9.0 SDK Update (October 2004)

PIX Counters

PIX contains a number of counters for collecting and displaying information about each rendered frame. The counters are configured in an experiment. There are three types of counters:

  1. Microsoft Direct3D counters, which report information specifically about Direct3D.
  2. Performance counters, which report system performance information.
  3. Plugin counters, which can be implemented by third parties to provide custom information.

PIX Direct3D Counters

These counters keep track of Direct3D application programming interface (API) calls. There are several types of counters:

Types | Description
General Counters | Calculate general Direct3D performance metrics.
Primitive Counters | Count the number of draw calls.
Resource Counters | Keep track of memory allocation and object creation.
State Change Counters | Count the number of state changes.
Shader Constant Counters | Count the number of shader constants.

General Counters

These counters calculate metrics for the entire application such as:

  • Frames per second. This is an instantaneous frames-per-second, it is not averaged over multiple frames. Due to internal buffering of Direct3D commands (see Accurately Profiling Direct3D API Calls), this data may appear to be more sporadic than the actual timing of the frame updates as seen by the user onscreen.
  • Number of calls per frame. This is a count of all Direct3D calls made within each frame. D3DX calls are not included in this counter.

Primitive Counters

These counters monitor drawing activity by watching each type of draw call. There are separate counters for each of the four types of drawing methods:

  • IDirect3DDevice9::DrawPrimitive
  • IDirect3DDevice9::DrawIndexedPrimitive
  • IDirect3DDevice9::DrawPrimitiveUP
  • IDirect3DDevice9::DrawIndexedPrimitiveUP
For each type of drawing method, you can track:

  • The number of times each draw is called.
  • The time spent processing each draw call.

Alternately, you can use the Draw* counter to gather information about all draw calls.

Resource Counters

These counters measure the memory activity related to resources. Things like memory allocations for creating resources or objects. You can measure individual types of resources such as vertex buffers, index buffers, or textures. For each resource, memory resources may exist in many different types of memory pools. For each pool type (default pool, managed pool, system pool, scratch pool), you can use any of the following counters:

  • Total bytes allocated as of this frame.
  • New bytes allocated this frame.
  • Total objects allocated as of this frame.
  • New objects allocated this frame.
  • Number of locks in this frame.
  • Number of unlocks in this frame.

Alternately, you can use the All Resources counter to gather information about all resource calls. And you can use the All pools counter to gather information about calls to all the memory pools.

State Change Counters

These counters keep track of the number of state changes. Each of the state changes is tracked as the number of times each of these methods is called:

  • The number of IDirect3DDevice9::SetRenderStates per frame.
  • The number of IDirect3DDevice9::SetTextureStageStates per frame.
  • The number of miscellaneous fixed-function state sets per frame.
  • The number of IDirect3DDevice9::SetRenderTargets per frame.
  • The number of IDirect3DDevice9::SetVertexShaders per frame.
  • The number of IDirect3DDevice9::SetPixelShaders per frame.
  • The number of IDirect3DDevice9::SetTextures per frame.

Shader Constant Counters

These counters keep track of the number of shader constants that are set by tracking:

  • The number of IDirect3DDevice9::SetVertexShaderConstantB, IDirect3DDevice9::SetVertexShaderConstantF, and IDirect3DDevice9::SetVertexShaderConstantI calls per frame.
  • The number of IDirect3DDevice9::SetPixelShaderConstantB, IDirect3DDevice9::SetPixelShaderConstantF, and IDirect3DDevice9::SetPixelShaderConstantI calls per frame.

Performance Data Counters

Performance counters track overall performance of the application.

Common in-process counters measure in-process metrics such as:

  • Percent Processor Time
  • Virtual Bytes Allocated
  • Thread Count
  • Handle Count
  • I/O Read Bytes per second
  • I/O Write Bytes per second

On the other hand, there are also system-wide counters for measuring metrics across processes such as:

  • Percent Processor Time
  • Page Faults per second
  • Available Bytes
  • Total Threads
  • Percent Disk Time

In addition there are many other performance counters available. Run PIX and look under All Performance Counters to see a full listing.

User Plug-in Counters

PIX also supports user plug-ins. This allows you to create your own plug-ins, in a separate dynamic-link library (DLL), and then access them from PIX. See the sample program PIXPluginSample for more information about writing a plugin counter.

Countersets

Countersets provide a convenient way to group together a list of counters for easy access. To create a counterset, add the counters you want to an experiment, then click Save As Counterset. After naming the counterset, the counterset will appear under My Countersets in the counter chooser. You can add all counters in a counterset to an experiment by selecting it and clicking Add. You can rename or delete a counterset by right-clicking its name. You can also remove counters from a counterset by right-clicking them.


DirectX Extensions for Visual Studio .NET
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectX Extensions for Visual Studio .NET

Microsoft Visual Studio .NET supports debugging assembly-level and high-level language vertex and pixel shaders. Many of the debugger features are listed below. To prepare your machine for shader debugging, see Getting Started Debugging Shaders. If you already have the right tools installed, you can also try the Goal 5: Shader Debugging Tutorial.

The debugger works with the debug version of the runtime, as well as with certain device types. Any vertex or pixel shader can be debugged when using a reference device. Vertex shaders can be debugged, providing they are running on a hardware abstraction layer (HAL) device created for software vertex processing. No debugging support is provided for hardware vertex processing or "pure" HAL devices. For more information about device types, see D3DDEVTYPE.

  • Building with Debug Information
  • Starting the Debugger
  • Breakpoints
  • Viewing Device State
  • Debugging C++ Code and Direct3D Code Simultaneously
  • Related Topics

Building with Debug Information

To do source-level debugging of a shader, the shader must be built with debug information and it must have an on-disk source file associated with it. You can create such a shader in the following two ways.

  • Compile the shader at build time using Vsa.exe (the vertex shader assembler), Psa.exe (the pixel shader assembler), or Fxc.exe (the high-level language compiler), and specify the /Zi command-line flag.
  • Compile the shader at run time using D3DXAssembleShaderFromFile or D3DXCompileShaderFromFile and specify the D3DXSHADER_DEBUG flag. For more information about the compiler flags, see D3DXSHADER Compile Options.

For debugging purposes, disable optimizations by supplying the /Od command line flag or the D3DXSHADER_SKIPOPTIMIZATION flag.

If you choose to compile a shader from memory using methods like D3DXAssembleShader or D3DXCompileShader or D3DXCreateEffect, add the #line directive to your shader code to get the debugger to work properly. Here's an example:

#line 2 "currentfile.fx"

It is not necessary to build an application with Visual Studio .NET in order to use the shader debugger. Build your application with any compiler, and then use Visual Studio .NET to debug it by starting your application and using the "Attach To Process" dialog box (which is explained in the next section).

Starting the Debugger

To debug an application, the application must be using the debug version of the Microsoft Direct3D runtime and must have shader debugging enabled. You can configure these options through the Direct3D tab in the Microsoft DirectX control panel applet. The DirectX debug service must also be running on the target computer. This service is installed automatically when you install the DirectX extensions for Visual Studio .NET.

  • When using a HAL device, only vertex shaders created for software vertex processing can be debugged. Pixel shaders cannot be debugged at all. No debugging whatsoever is supported for "pure" HAL devices.
  • When using a reference device, any vertex or pixel shader may be debugged. Debugging of "pure" reference devices works the same as it does for "non-pure" reference devices.

There are two techniques for starting the debugger. Both techniques will work on a C++ application; however, a managed code application can only be debugged using the second technique.

Technique 1: Click Debug, Direct3D, Start With Direct3D Debugging (CTRL+ALT+F5) to start the debugger.

Technique 2: You can "attach" to an already running Direct3D process. The easiest way to do this from Visual Studio .NET is as follows:

  1. On the Debug menu, start your application with the Start Without Debugging command.
  2. On the Debug menu, click Processes to open the Processes window.
  3. Select your application from the process list and click the Attach button.

  4. In the Attach to Process dialog box, select Native to debug your C++ code, and select Direct3D to debug your Direct3D code. You can debug both C++ and Direct3D code simultaneously (see Debugging C++ Code and Direct3D Code Simultaneously near the bottom of this topic).

    Visual Studio .NET also supports remote debugging of Direct3D applications. To attach to a Direct3D process on a remote computer, in the Processes dialog box, enter the name of the remote computer in the Name box and then attach to the process the same as for a local process.

Breakpoints

To set a breakpoint in a vertex or pixel shader source file, the shader must have debug information present (see Building with Debug Information). The module window (click on Debug, then Windows and finally Modules) can be used to view all shaders that are currently loaded. When debugging native code, right-click the window and choose Show Modules for All Programs to view the shaders that are loaded.

Line Breakpoints

You can set a breakpoint at a particular line in a shader the same way you would set a breakpoint in C++ source code, that is:

  1. Open the source file in the Visual Studio .NET text editor; move the cursor to the line on which to set the breakpoint; and choose the Toggle Breakpoint command (F9 by default).
  2. Right-click the line in the source code where you want to set the breakpoint and then choose Insert Breakpoint from the shortcut menu.
  3. Select the New Breakpoint command (CTRL+B by default). Using the File tab in the New Breakpoint dialog box, enter the file name and, optionally, the line number of the breakpoint.

Left clicking the margin next to a line in the source code toggles a breakpoint.

Function Breakpoints

Using the Function tab in the Breakpoint Properties dialog box, type the case-sensitive name of the shader function as the name, and set the language to Direct3D Shader. The function name is the name of the shader function stored in the debug information, or the name of the file containing the shader. The module window (open it by clicking on Windows and then select the Windows... menu item) lists all currently loaded shaders and their names. IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene breakpoints work as before.

Conditional Breakpoints

Any of the following types of breakpoints can have a condition, as long as the breakpoint is set to occur when the condition is true (as opposed to when the condition changes):

  • Function
  • File/Line
  • Address

The expression must evaluate to a single-element Boolean result.

Pixel Area Breakpoints

A pixel area breakpoint triggers at the first instruction of any pixel shader that is about to modify a pixel within a given rectangle. Set a pixel area breakpoint by going to the Data tab in the Breakpoint dialog and:

  • Select Direct3D Shader as the language.
  • Enter a breakpoint in the Variable text box in one of these formats:
    • (x,y) : Break when the pixel at (x, y) is being computed.
    • (left,top)-(right,bottom) : Break when any of the pixels in a rectangle is being computed. Standard RECT World Wide Web link semantics apply: left and top edges are in the rectangle; right and bottom edges are not.

Alternatively, a pixel area breakpoint can also be created by dragging out a rectangle with the mouse on a render target tool window.

Assembly Code (Address) Breakpoints

Setting a breakpoint on a specific instruction of a shader does not require debug information. You can set an address breakpoint in the following ways.

  • Move the cursor in the Disassembly window to the line containing the instruction on which you want to set the breakpoint, and choose the Toggle Breakpoint command (F9 by default).
  • Right-click the line in the Disassembly window containing the instruction on which to set the breakpoint and choose Insert Breakpoint from the shortcut menu.
  • Select the New Breakpoint command (CTRL+B by default), select the Address tab, select Direct3D Shader from the Language combo box, and enter the address of the instruction that needs the breakpoint.

    The format of an address is xxx:yyy where:

    • xxx is the shader module number
    • yyy is the instruction address

    To find the values for xxx:yyy, open the Disassembly window, find the instruction on which you want to set a breakpoint, and copy the module number:address number from the previous line. The xxx number starts with a "v" for Vertex Shader or "p" for Pixel Shader. Here's an example of the number: P00000009:00000780 (which could be entered as P9:780). This would set a breakpoint in a pixel shader, that is in module 9, at address 780.

BeginScene or EndScene Breakpoints

To set a breakpoint when the application you are debugging reaches IDirect3DDevice9::BeginScene or IDirect3DDevice9::EndScene, select the New Breakpoint command (CTRL+B by default), select the Function tab, select Direct3D Shader from the Language combo box, and type either BeginScene or EndScene as the name of the function.

Stepping

You can step through shader code using the Debug menu's Step Over command (F10 by default). Stepping in Direct3D code will cause the application you are debugging to stop at the next vertex or pixel shader instruction it runs.

Expression Evaluation

When the application you are debugging is stopped in a vertex or pixel shader, or at a BeginScene or EndScene breakpoint, you can use the Watch window to inspect the state of the application you are debugging. You can also quickly view the contents of a register by briefly resting the mouse pointer on the register in the Disassembly window or in your shader source code.

The expression syntax supports register names, swizzles, and the following operators, which all operate per component.

+ - * / == != < <= > >= [] ! || &&

In addition, the following two intrinsic functions are supported.

  • any( e ) - Returns TRUE if any of the Boolean elements of e are true.
  • all( e ) - Returns TRUE if all of the Boolean elements of e are true.

All types must match exactly. Floating-point literals must have a decimal point; otherwise, they are treated as integers.

Examples

This expression returns TRUE if all of the first three components of r0 are less than the corresponding components of c4.

all( r0.xyz < c4.xyz )

Constant registers are indexed by one plus the x-component of a0.

c[a0.x+1]

Viewing Register Contents

To view the contents of a register in the watch window, use the following expression syntax:

registerName[.swizzle][,format][,w]

Where:

  • registerName is the name of the register to inspect (for example, r0, oPos, t7).
  • swizzle is the optional swizzle specifier, the same as used on a source register in the shader assembly language (for example, v0.xxyy, r2.rgb).
  • format is the optional floating-point format specifier, the same as for C++ debugging. Valid format specifiers are:
    • e - Exponential notation (for example, 1.23e+1)
    • f - Standard notation (for example, 12.3)
    • g - Either 'e' or 'f', whichever is more compact
  • w is an optional specifier that says to divide the first three components by the fourth component before displaying.

Viewing Device State

To view the current values of render states and texture stage states on the device, enter $DeviceState in the Watch window.

Viewing the Current Pixel Position

The coordinates of the pixel currently being rendered by a pixel shader are contained in register vPos (see Position Register). Enter vPos in the watch window to see its value.

Viewing Surface Contents

Viewing the render target - To view the contents of the current render-target surface, open the Render Target window by selecting the Debug menu's Direct3D, Render Target menu options. This window will be updated with the current contents of the render target whenever the application you are debugging enters "break" mode.

Viewing textures - To view the contents of the texture currently selected into a texture stage, open a Texture window by selecting the appropriate texture stage from the Debug menu's Direct3D, Textures menu. The texture windows will be updated with the current contents of the corresponding texture stage whenever the application you are debugging enters "break" mode.

If the contents of a surface (either the render target or a texture) are not available, the surface's window will show the text as "Unavailable." Possible reasons for a surface being unavailable include:

  • The surface is not lockable. The surface must be created to allow it to be locked for read-only access. To create a lockable back buffer, specify the D3DPRESENTFLAG_LOCKABLE_BACKBUFFER flag in D3DPRESENT_PARAMETERS when calling IDirect3D9::CreateDevice.
  • The surface is a volume texture. The texture windows do not support the display of volume textures in this release.
  • The surface is in an unsupported pixel format. The debugger currently supports the display of most standard RGB and RGBA pixel formats, as well as the DXTn compressed texture formats.
  • The application you are debugging is running on a remote computer. In this release, the surface views are not supported when debugging remotely.

Debugging C++ Code and Direct3D Code Simultaneously

The Visual Studio .NET debugger supports debugging of multiple program types at the same time. Typical C++ debugging uses the "Native" program type. Direct3D debugging uses the "Direct3D" program type. When the application you are debugging stops in C++ code, the current program will be set to Native, and the call stack, watch window, and other debug windows will reflect the state of the Native program. Similarly, when the application you are debugging stops in shader code, the current program will be set to Direct3D, and the debug windows will reflect the state of the Direct3D program. To switch between program types, use the Program combo box on the Debug Location toolbar. Note that when the application you are debugging is stopped in Native code, most of the state of the Direct3D program will be unavailable. The reverse is not true, however. If you stop at a breakpoint in a shader, for example, you can switch to the Native program and see the C++ call stack that caused your shader to be invoked.

For more information about debugging multiple program types simultaneously, see Debugging Multiple Programs World Wide Web link.

Debugging without Debug Information

If possible, build your shaders with debug information enabled (see Building with Debug Information). In cases where building with debug information is not feasible, such as for shaders that are built up "on the fly," debugging is possible but is much more difficult. Because source code is not available, source code breakpoints won't work. One approach to debugging without debug information is to set a BeginScene breakpoint, and when that breakpoint is reached, step into the shader code of the first shader run by pressing F10. When you're stepping through disassembly code, you can set breakpoints in the Disassembly window. You can also use the Modules window to view the names of all shaders currently loaded and selectively set breakpoints on them as needed.

Related Topics

  • Effect Command Line Compile


Enabling Direct3D Debug Information
Microsoft DirectX 9.0 SDK Update (October 2004)

Enabling Direct3D Debug Information

Are you trying to find out more information about Microsoft Direct3D objects during debug? For instance, here's what you typically see when you look at a Direct3D interface in the watch window:

You can enable the core debug objects so that a mirrored object which contains all of the properties of the object can be viewed in the watch window. Simply include the following #define in your code before the D3d9.h file:

#define D3D_DEBUG_INFO

To enable debug information, the #define must get built before the D3d9.h file. If you are running a software development kit (SDK) sample, you can see this in Dxstdafx.h (which affects all the C++ samples). You must also be running the debug Direct3D runtime (which can be enabled from the Control Panel if necessary).

Here's an example using the BasicHLSL Sample.

  1. Add the #define to the Dxstdafx.h file before line 37.
  2. Build a debug project.
  3. Set a breakpoint at line 307 in BasicHLSL.cpp
  4. Run the debugger.

Here is an example of the kind of detailed information you can get about a Direct3D texture object from the watch window:

Note

The object property names are visible and the values are correct only when the debug runtime is enabled. When running against the retail runtime, the values are invalid.

Use the Call Stack for Extended Debug

With Direct3D debug enabled, you can also look at a call stack each time an object is created. This will make your application very slow, but can be used to check for resource leaks. To write out the call stack, set the following registry key to 1:

\\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Direct3D\\
D3D9Debugging\\EnableCreationStack

Building your application with debug enabled will give you access to this additional variable:

  LPCWSTR CreationCallStack;

This variable will store the call stack each time that an object is created. This will make your application very slow, but can be used to debug resource leaks.


HLSL Command-Line Compiler
Microsoft DirectX 9.0 SDK Update (October 2004)

HLSL Command-Line Compiler

High-level shader language (HLSL) shaders can be compiled from the command line using the following executable:

(SDK root)\Utilities\fxc.exe

Syntax

The usage is:

fxc options filename

Where:

  • options can be the following compiler switch options:

    Switch Option | Description
    /D id= text | Define a macro
    /E name | Identify the entry point
    /Fc file | Generate assembly code listing file
    /Fh file | Generate header containing object code
    /Fo file | Generate object file
    /Fx file | Generate assembly code and hex listing file
    /Gpp | Force partial precision
    /nologo | Suppress copyright message
    /Od | Disable optimizations
    /T profile Identify the target profile, which is one of the following:
    • Vertex shader profiles are contained in D3DXGetVertexShaderProfile
    • Pixel shader profiles are contained in D3DXGetPixelShaderProfile
    • Procedural texture profile tx_1_0
    /Vd | Disable validation
    /Zi | Enable debugging information
    /Zpc | Pack matrices in column-major order
    /Zpr | Pack matrices in row-major order
  • filename is the name of the effect file to be compiled.

Remarks

Using the HLSLwithoutEffects Sample, here's an example of compiling the HLSL shader in the file HLSLwithoutEffects.vsh for a vs_2_0 target profile:

// For a release build
fxc /T vs_2_0 /Fo HLSLwithoutEffects.fxo HLSLwithoutEffects.vsh

// For a debug build
fxc /Od /Zi /T vs_2_0 /Fo HLSLwithoutEffects.fxo HLSLwithoutEffects.vsh

The debug options include additional options to disable compiler optimizations and enable debug information like line numbers, symbols, and so on. The binary representation of the shader is written to a file called HLSLwithoutEffects.fxo which is an arbitrary abbreviation for the fxc output file.

The command line compiler can also be used to compile a shader within an effect. This can be seen in the CompiledEffect Sample.


Vertex Shader Command-Line Assembler
Microsoft DirectX 9.0 SDK Update (October 2004)

Vertex Shader Command-Line Assembler

Vertex shaders can be assembled into binary code using psa.exe in Program Files/Microsoft DirectX 9.0 SDK/Utilities/. The usage is:

Syntax

vsa <Switch Options> <Filename>

Switch Options

The assembler switch options are:

Switch Option | Description
/Vd | Disable validation.
/Zi | Enable debugging information.
/Fo <file> | Output object file.
/Fc <file> | Output assembly code listing file.
/Fx <file> | Output assembly code and hex listing file.
/Fh <file> | Output header containing object code.
/Vn <name> | Use <name> as a variable name in the header file.
/Cc | Enable color coded assembly listings.
/D<id>=<text> | Define a macro.
/nologo | Suppress copyright message.

Filename

file is the filename of the effect to be assembled.

Related Topics

  • Pixel Shader Command-Line Assembler


Pixel Shader Command-Line Assembler
Microsoft DirectX 9.0 SDK Update (October 2004)

Pixel Shader Command-Line Assembler

Pixel shaders can be assembled into binary code using psa.exe in Program Files/Microsoft DirectX 9.0 SDK/Utilities/. The usage is:

Syntax

psa <Switch Options> <Filename>

Switch Options

The assembler switch options are:

Switch Option | Description
/Vd | Disable validation.
/Zi | Enable debugging information.
/Fo <file> | Output object file.
/Fc <file> | Output assembly code listing file.
/Fx <file> | Output assembly code and hex listing file.
/Fh <file> | Output header containing object code.
/Vn <name> | Use <name> as a variable name in the header file.
/Cc | Enable color coded assembly listings.
/D<id>=<text> | Define a macro.
/nologo | Suppress copyright message.

Filename

file is the filename of the effect to be assembled.

Related Topics

  • Vertex Shader Command-Line Assembler


Mesh Viewer
Microsoft DirectX 9.0 SDK Update (October 2004)

Mesh Viewer

The Mesh Viewer tool enables you to easily modify meshes.

Menu Descriptions

Mesh Viewer includes the menu item listed here.

File

  • Open mesh file. Opens a dialog to select a file in the .x or .m file format to be loaded and viewed.
  • Open pMesh file. Opens a dialog to select a file in the progressive mesh format to be loaded and viewed.
  • Create shape. Opens a sub-dialog to create some basic shapes that are defined programmatically (text, polygon, box, cylinder, torus, teapot, sphere, cone).
  • Save mesh as. Opens a dialog to save the selected mesh to a file. The file can be written as a text or binary file.
  • Close selected. Closes and deletes the currently selected mesh.
  • Close non-selected. Closes and deletes the meshes that are not currently selected.

View

  • Wireframe. View all content in wireframe mode.
  • Edges. View all content in solid-shaded mode with the edges drawn in black.
  • Creases. Highlight the creases on the visible meshes. A crease is an edge with a vertex that has a different piece of data on it for multiple faces that refer to it, that is, a different normal for the vertex per face.
  • Strips. Show the strips that are generated by this mesh in blue. The blue line goes from the center of each triangle to the next triangle in the triangle strip.
  • Adjacency. Show the adjacency of the polygons in a mesh by drawing a line from the center of a polygon to the center of the adjacent polygon.
  • Bounding box. Draw the bounding boxes for the visible meshes.
  • Normals. Draw the normals of the vertices on the visible meshes in yellow.
  • Texture coords. Show the texture coordinates for the viewed geometry as rays projecting from the vertices. Because a vertex in Microsoft Direct3D can have up to eight texture coordinates, users must specify which sets they would like to view. This viewing mode is especially useful when the texture coordinates are filled with tangents for use in pixel shaders for example.
  • Textures. Display the textures on the visible geometry.
  • Lighting. Show the geometry in the scene with lighting calculations still on.
  • Culling. Perform back face culling on the visible geometry when disabled polygons facing away from the camera are not drawn.
  • Hierarchy. Display the frame hierarchy of the meshes that are currently loaded. This is displayed in a separate floating window. To make the window disappear, on the View menu, clear the Hierarchy command.
  • Play animation. Play the current animation for the currently loaded geometry if one exists.
  • Pause animation. Stop the animation at the current frame when playing.
  • Normal speed. Interpret the time value in the animation from a .x file as 4800 units per second. Otherwise, the interpreted value is 30 units per second.

MeshOps

  • Optimize. Optimizes the currently selected mesh with the selected optimization method. See the D3DX reference pages to see the differences in methods.
  • Weld vertices. Removes duplicate vertices and makes polygons that use these vertices use the nondeleted vertex.
  • Split mesh. Splits the selected mesh into multiple meshes that are less than specified size in vertices and faces.
  • Collapse meshes. Collapses the currently selected meshes into a single mesh.
  • Reset matrices. Resets the matrices for the frames that are loaded to their initial position.
  • Mesh properties. Shows the selected mesh's flexible vertex format (FVF) render states and whether it is a 32-bit mesh.
  • Skinning method. Allows the user to select the skinning method while animating a skinned mesh. The choices are nonindexed, indexed, and software skinning.
  • Face selection. Enters a mode for the user to select an individual face on the current mesh.
  • Vertex selection. Enters a mode for the user to select an individual vertex on the current mesh.

PMeshes

  • Convert selected to PM. Convert the selected mesh to a progressive mesh. The conversion uses the error parameters that are entered in a dialog box. For more information about these parameters refer to the D3DX documentation of progressive meshes.
  • Snapshot to mesh. Convert the current progressive mesh object to a static mesh object using the current settings of the progressive mesh.
  • Set number of faces. Set the current number of faces in the progressive mesh to a specific number.
  • Set number of vertices. Set the current number of vertices in the progressive mesh to a specific number.
  • Trim. Set the minimum and maximum number of faces for a progressive mesh. When the user has set the trim values to the desired minimum and maximum, the progressive mesh can be trimmed to the selected values, thereby reducing the dynamic range of the progressive mesh.

N-Patches

  • N-patch selected. Draw the current object as an N-patch object. The scroll bar in this mode selects the amount of N-patch iterations for the current object.
  • Snapshot to mesh. Convert the selected object to a static mesh based on the current N-patch settings to create a high-resolution static mesh.

Icons and Usage

Icons

  • Selection modes. The first three icons are easy ways for the user to select the selection mode. They are Mesh Selection Mode (Arrow), Face Selection Mode (yellow outlined triangle), and Vertex Selection Mode (Red point highlighted triangle). These are the same modes that are available from the menus in MeshOps.
  • Display modes. The next icons are easy ways to select the most common display modes for geometry. They are Shaded mode (nonoutlined tri-color cube), Wire frame mode (wire frame cube), and Edge mode (outlined tri-color cube). These are the same modes that are available from the menus in View.
  • Topology display modes. The next icons display specific topological information about the geometry displayed. They are adjacency (A), Strips (S), Creases (C), and Normals (N). These are the same modes that are available from the menus in View.
  • Info. The next icon is the button that will display information about the currently selected element.
  • Animation controls. The last two icons are animation controls for playing and pausing the animation for the currently visible mesh.

Status Bar

The status bar in MView displays the current status of the visible geometry. The order from left to right of the displayed information is currently selected element (face or vertex only), Mesh mode (polygonor pMesh), display frames per second, display triangles per second, number of displayed triangles, and number of displayed vertices.

Scroll Bar

The scroll bar will appear in two of the three mesh modes, pMesh and N-patch mode. In pMesh mode, the scroll bar indicates the range of displayed triangles for the progressive mesh. You can slide the scroll bar up or down to change the number of triangles displayed. In N-patch mode, the scroll bar indicates how many N-patch levels are being used. As the scroll bar is moved up or down, the number of N-patch interactions performed are adjusted accordingly.

More Information

For more information about any of the functions used by MView, refer to D3DX Reference.


Texture Viewer
Microsoft DirectX 9.0 SDK Update (October 2004)

Texture Viewer

The texture viewer displays thumbnail images in the Microsoft Windows file preview system. The following are the file formats that can be displayed:
  • .bmp
  • .dds
  • .dib
  • .hdr
  • .jpg
  • .pfm
  • .png
  • .ppm
  • .tga
For more information on these texture file formats, see D3DXIMAGE_FILEFORMAT.

For a cube texture, the forward cube face will be displayed on the screen. For a volume texture, the first plane will be displayed. These display properties cannot be configured by the user.

Requirements

Minimum Operating System | Windows 2000. The viewer will not work on Windows Millennium Edition (Windows Me).
Required Applications | Microsoft DirectX 9.0 SDK Update (Summer 2003) or later

Installation

The texture viewer is automatically installed when you install the DirectX 9.0 software development kit (SDK).

Note Installation will not override any existing Windows shell viewer settings for any texture file formats.

User's Guide

From a folder view of your texture files, use the Windows View menu to view thumbnail images with texture file information. Use one of the following procedures.

Thumbnail View

In the View menu, select Thumbnails. Thumbnails of all supported file formats (see list above) will be displayed. If more than one mip level is available in a file's mipmap, only the top mip level will be displayed.

Texture view using the Explorer menu

Details View

If necessary, first switch out of Windows classic folder view; see the note below. Select the file you want to view, and then in the View menu, select Details. A rendering of the image will be displayed in the Details pane of the Explorer bar.

Texture view using Details panel of the Explorer bar

Note The Details view functionality will not work if you are using the Windows classic folder view. To change your folder settings, use the following procedure.
  1. Open any folder.
  2. In the folder's Tools menu, select Folder Options...
  3. In the General tab, select the radio button labeled Show common tasks in folders.
  4. Click Apply and then OK.
To go back to the Windows classic folder view, use this same procedure, but instead select the radio button labeled Use Windows classic folders.

Folder options dialog box


Texture File Converter
Microsoft DirectX 9.0 SDK Update (October 2004)

Texture File Converter

The texture file converter saves one or more texture files to a new file format. The following are the available input and output formats:
  • .bmp
  • .dds
  • .dib
  • .hdr
  • .jpg
  • .pfm
  • .png
  • .tga
For more information on these texture file formats, see D3DXIMAGE_FILEFORMAT.

Requirements

Minimum Operating System | Microsoft Windows 2000
Required Applications | Microsoft DirectX 9.0 SDK Update (Summer 2003) or later

Installation

The texture file converter is automatically installed when you install the DirectX 9.0 software development kit (SDK).

User's Guide

The texture file converter is activated when you right-click one or more files or a folder, and then select Convert to file format... from the context menu.

The following conversion dialog box will appear with options for output size, formats, filtering, and file location.

Texture conversion dialog box

If Image Options is set to Default, the original image size and/or mip levels will be retained. The Depth setting applies only to volume textures. Choices are available among the following options and filters.

Options and Filters | Description
Miplevels | Level of mipmap sampling. For more information, see Texture Filtering with Mipmaps.
Pixel Format | Available unsigned, signed, and mixed formats described in D3DFORMAT.
Image Filter | D3DX_FILTER_NONE, _POINT, _LINEAR, and _TRIANGLE texture channel flags described in D3DX_FILTER.
Mirror | D3DX_FILTER_MIRROR_U, _V, and _W texture channel flags described in D3DX_FILTER.
sRGB | In setting indicates the input data is in sRGB (gamma 2.2) color space. Out setting indicates the output data is to be in sRGB (gamma 2.2) color space.
Mip Filter | D3DX_FILTER_BOX, _POINT, and _TRIANGLE texture channel flags described in D3DX_FILTER.
Dither | Ordered (standard 4x4) or Error Propagation (statistically based) dither algorithms can be applied to the output from the Image Filter and Mip Filter. Alternately, no dithering can be applied.

Note The Miplevels and Mip Filter choices are disabled unless .dds output format and Enable extended .DDS file options are both selected.

Behavior of the converter varies according to whether a single file, multiple files, or a folder have been selected, as described below.

Converting a Single File

Follow these steps to convert a single texture file.

  1. Right-click a texture file to convert, then select Convert to file format... from the context menu. The conversion dialog box shown above will appear.
  2. Insert a path, file name, and extension for the converted file. Alternately, click the ... browse button, which will open a Save As dialog box to select the converted file's name, format, and destination folder.

Converting Multiple Files

Follow these steps to convert multiple texture files.

  1. Select multiple texture files, right-click, and select Convert to file format... from the context menu. A bulk file dialog box appears.
  2. In the bulk file dialog box, select whether to specify the output format for each file individually, or to convert all files to the same output format.
  3. If you chose to specify the output format for each file individually, the conversion dialog box shown above appears in turn for each file. Then for each file, specify the output size, format, and filtering to apply. However, if you chose to convert all files to the same output format, a Bulk texture file conversion dialog box, similar to the conversion dialog box shown above, appears. Specify the output size, format, and filtering to apply to all the files you have selected.
  4. Select the output format for the files.
  5. Insert a path to a destination folder in which to store the converted files, or click the ... browse button to select a destination folder.

Converting Files in a Folder

Follow these steps to convert several texture files in a folder.

  1. Right-click a folder containing texture files (or several files and a folder), then select Convert to file format... from the context menu. A Bulk texture file conversion dialog box, similar to the conversion dialog box shown above, appears.
  2. Specify the output size, format, and filtering that will apply to all the files within the folder, along with any other files you have selected.
  3. Insert a path to a destination folder in which to store the converted files, or click the ... browse button to select a destination folder.
  4. If the destination folder is the same as or within the source folder, a message box will inform you that the files will not be converted. However, any other selected source files not in this destination folder will be converted. The converter also provides options for the case where more than one file of the same name will be created; for example, when two files to be converted have the same name but different extensions.


Photoshop Texture Converter
Microsoft DirectX 9.0 SDK Update (October 2004)

Photoshop Texture Converter

The Photoshop texture file converter is a file format plug-in to Adobe Photoshop World Wide Web link to open or save texture files. The plug-in will also work with Jasc PaintShop Pro World Wide Web link. The following are the available input and output formats:
  • .bmp
  • .dds
  • .dib
  • .hdr
  • .jpg
  • .pfm
  • .png
  • .tga
See D3DXIMAGE_FILEFORMAT for more information on these texture file formats.

Requirements

Minimum Operating System Microsoft Windows 2000
Required Applications
  • Adobe Photoshop World Wide Web link version 7.0, 8.0, or CS; or Jasc PaintShop Pro World Wide Web link version 8.0
  • Microsoft DirectX 9.0 SDK Update (Summer 2004) or later

Installation

The texture converter plug-in is automatically installed when you install the DirectX 9.0 software development kit (SDK). The installer checks for valid versions of Photoshop or PaintShop Pro and copies the D3DXTextureFormat.8bi file to the application plug-in folder.

User's Guide

The texture plug-in allows you to open or save files in Photoshop in any of the nine texture file formats listed above. Similar procedures can be used in PaintShop Pro.

Opening a Texture File

Follow these steps to open a texture file.

  1. In the Photoshop File menu, select Open... or Open As....
  2. In the Files of type list at the bottom of the dialog box, select the following format:

    D3DXTextureFormat(*.BMP;*.DDS;*.DIB;*.HDR;*.JPG;*.PFM;*.PNG;*.PPM;*.TGA)

  3. Select the file you want to open, and either double-click the file icon or click the Open button. The texture file is now available to edit in Photoshop.

If more than one mip level is available in the mipmap, the following dialog box will appear.

Mip level dialog box

The Open entire file option is the default selection. If this option is selected, all mip levels are joined together in a single Photoshop 2-D image display.

Display of all mip levels

You can then edit any or all of the mip levels in Photoshop. Alternately, you can select Open a particular mip level if you want to edit only one mip level in Photoshop, for example the 128x32 pixel level shown here.

Display of the 128x32 pixel mip level

If the file to be opened is a cube or volume texture, a similar dialog box will appear that lets you select a view of all cube faces or volume slices simultaneously, or one at a time. Mip levels of a cube or volume texture are not available for display with this plug-in.

Note It is not recommended that you open a texture file by right-clicking it and selecting Open With and then Adobe Photoshop.
Warning When you use the plug-in with PaintShop Pro to open a texture file that contains an alpha channel, PaintShop Pro will multiply each of the RGB channels by the alpha channel and then will discard the alpha channel. If the input texture has an XRGB surface format (D3DFMT_X8R8G8B8, D3DFMT_X1R5G5B5, D3DFMT_X4R4G4B4, or D3DFMT_X8B8G8R8), this behavior results in an empty texture being saved.

Saving a Simple Texture File

Complete the following steps to save a texture file to any supported format except .dds.

  1. In the Photoshop File menu, select Save As....
  2. In the Files of type list at the bottom of the dialog box, select the following format:

    D3DXTextureFormat(*.BMP;*.DDS;*.DIB;*.HDR;*.JPG;*.PFM;*.PNG;*.PPM;*.TGA)

  3. Select the directory location where you want to save the file.
  4. Type in the name of the file to save, along with the three-letter file extension (any supported format listed above except .dds). You may overwrite your original file.
  5. Click the Save button.
  6. The following dialog box will appear.

    Simple texture file save dialog box

    Select the pixel format from the list of available formats at the bottom of the dialog box. No other save options will be available in this dialog.

  7. Click OK to save the file.

Saving a DDS File

Follow these steps to save a texture file to .dds format.

  1. In the Photoshop File menu, select Save As....
  2. In the Files of type list at the bottom of the dialog box, select the following format:

    D3DXTextureFormat(*.BMP;*.DDS;*.DIB;*.HDR;*.JPG;*.PFM;*.PNG;*.PPM;*.TGA)

  3. Select the directory location where you want to save the file.
  4. Type in the name of the file to save, along with the .dds file extension.
  5. Click the Save button. The following dialog box will appear.

    DDS texture file save dialog box

  6. Make selections for the type of texture to save.
    • If you select the Cube map or Volume texture, then you can also click the checkbox to duplicate the image on all cube faces or volume slices.
    • If you select a Volume texture, then in the Depth box type in the number of volume slices you want the volume texture to contain.
    • If you select Cube map but your texture file format is not square, a warning message will appear noting that the image will be cropped to be a square format.
  7. From the list of available mip levels, select the number of mip levels you want the new texture file to contain.
  8. From the list of available formats, select the pixel format in which to save the file.
  9. Click OK to save the file.

Note To avoid generating invalid results, the plug-in does not allow saving a full volume as a cube, or a full cube as a volume.

Resizing and Saving a Texture File

If you change the image size of an individual mip level in Photoshop and then try to save the file using Save from the Photoshop File menu, an error message will appear and the file will not be saved. You should instead try one of the following procedures:

  • Open the file with the Open a particular mip level option and then change the image size in Photoshop. Use Save As... from the Photoshop File menu, and the new saved file will be properly resized.
  • Open the file with the Open entire file option and then change the image size in Photoshop. If you use Save As... to save to the original file type, all mip levels will be resized proportionally in your new saved file.
  • Open the file with the Open entire file option and then change the image size in Photoshop. If you use Save As... to save to a different file type, in your new saved file the entire image displayed in Photoshop will become the new top-level texture, front cube face, or top volume slice.


Effect File Exporter (Maya Preview Pipeline)
Microsoft DirectX 9.0 SDK Update (October 2004)

Effect File Exporter (Maya Preview Pipeline)

Requirements

Minimum Operating System Microsoft Windows 2000
Required Applications
  • Alias' Maya World Wide Web link, versions 5.0 or 6.0
  • Microsoft DirectX 9.0 SDK Update (October 2004)

Installation

Complete the following steps to build the Maya preview pipeline on your computer.

  1. Close existing Maya application processes and then install the DirectX 9.0 SDK Update (October 2004).
  2. Launch Maya.
  3. From the Maya Window menu, select Settings/Preferences, then select Plugin Manager...
  4. In the selection list below the list of standard Maya paths, locate D3DMayaExportX.mll and check the boxes next to loaded and auto load.
  5. Click Close. You should now see a DirectX menu, indicating that the plug-in was successfully installed.

User's Guide

The preview pipeline defines a new material type that encapsulates a D3DX effect (.fx) file. This "DirectX Shader" material can be applied to objects in Maya. Shaders render within the preview pipeline viewer window using the associated effect. To apply an effect to an object, follow the steps below.

Create a DirectX Shader Material

First create a DirectX shader "material" in Maya with the following procedure.

  1. Launch Maya, and open or import your scene from Maya's File menu.
  2. In the Maya Window menu, select Rendering Editors, then Hypershade...
  3. In the Hypershade window that appears, verify that Create Materials is selected within the creation dropdown pane.
  4. In the Surface dropdown list, click DirectX Shader, which will create an empty material object. At this point, no effect file is associated yet with the material.

Adjust Effect Parameters

Adjust parameters in the effect to be applied to your object, then use the following procedure to preview the appearance of your object with the updated effect parameters.

  1. Open the Maya Attribute Editor. To do this, right-click on the DirectX Shader material in the lower Work Area pane, select Attribute Editor, and then minimize the Hypershade window. Alternately, minimize the Hypershade window and select Attribute Editor from Maya's Window menu.
  2. From within the Maya Attribute Editor, select the tab for the new material (the default name is "DirectXShader1"). Click the Select and Customize FX-File button.
  3. In the FX Editor window that appears, click the Open button.
  4. Browse to and select an annotated effect (.fx) file you will apply to your object. When you have selected an effect file, the effect will automatically be applied to the object in the Direct3D Preview Pipeline window.
  5. Double-click on the User Interface button to expand or collapse a drop-down list of available effect parameters that you can change. (Parameters in the Non-Interface list cannot be changed.)

    Effect editor window

  6. Click any parameter in the User Interface list that you want to change. For each parameter, you can click on the up and down arrows to change its state, or type in a new value.
  7. Click the Click to Choose button to apply the new parameter state to your object. When you click this button, the rendered view of the object in the Direct3D Preview Pipeline window will be updated with the new effect parameter state.
  8. Click the Done button at the bottom of the FX Editor window when you are done editing effect parameters.

Apply the Effect

Apply your final effect to your object with the following procedure.

  1. Return to the Hypershade window. If necessary, move this window so that your object in the main Maya view pane is also visible.
  2. Click the Work Area tab in the lower portion of the window and locate the effect material that you have been modifying.
  3. Hover the cursor over this effect material, then click the middle mouse button (or the mouse scroll wheel) and drag the mouse until the cursor is over your object in the main Maya view pane.
  4. Release the middle mouse button. The edited effect will be applied to your object. (Alternately, you can select your object in Maya and then, in the Hypershade window, select the desired effect material to apply, right-click, and select Assign Material to Selection.)
  5. To adjust the view of your object, you can select an option from Viewers... in the Maya DirectX menu. The camera for the viewer window is automatically tied to Maya's perspective view.
  6. Save your object with the newly-applied effect by using Save or Export in the Maya File menu.
Note The exporter does not currently support skinning, non-uniform rational b-splines (NURBS), subdivided surfaces, or graphics cards that do not run vertex or pixel shaders.


X File Exporter for Discreet's 3ds max
Microsoft DirectX 9.0 SDK Update (October 2004)

X File Exporter for Discreet's 3ds max

Files with the .x file name extension are used by Microsoft DirectX to store meshes, textures, animations, and other user-definable objects with a template hierarchy for data storage. DirectX has .x-file interfaces that provide a simple and safe way to import data into DirectX applications. These interfaces identify structures with unique identifiers (IDs), validate data layout, and provide data referencing and other intrinsic features.

Included with the DirectX software development kit (SDK) is source code to build a .x-file exporter plug-in for Discreet's 3ds max World Wide Web link (3D Studio MAX) application, versions 4.0 through 5.1. Some application providers include .x-file exporters that work with the application, such as Avid Technology's SOFTIMAGE|XSI World Wide Web link.

The 3ds max exporter plug-in makes use of the .x-file interfaces and functions developed to load ID3DXMesh, ID3DXPatchMesh, ID3DXSkinInfo, D3DXFRAME, ID3DXAnimationController, and other related interfaces and structures with minimal effort.

Once you have installed the DirectX SDK and Extras downloads (separate packages at Microsoft DirectX Downloads World Wide Web link), you can find the exporter plug-in files at the following location:

(SDK root)\Extras\Direct3D\Plug-Ins

Note The .x files generated by the exporter plug-in store all mesh data in a left-handed (LH) coordinate system, to match the left-handed coordinate system used by DirectX, even though 3ds max uses a right-handed coordinate system. For more information, see 3-D Coordinate Systems.

Requirements

Minimum Operating System Microsoft Windows 98
Required Applications
  • Discreet's 3ds max (3D Studio MAX), versions 4.0 through 5.1
  • Discreet's character studio World Wide Web link SDK
  • Microsoft Visual Studio 6.0
  • DirectX 9.0 SDK Update (Summer 2003) or later
Important The exporter may not build with Visual Studio .NET/Microsoft Visual C++ .NET.

Installation

Complete the following steps to build the exporter plug-in on your computer.

  1. Before proceeding, close existing 3ds max application processes.
  2. Install Discreet's character studio SDK.
  3. Open Visual Studio 6.0, and load the following file:

    (SDK root)\Extras\Direct3D\Plug-Ins\3DSMax versions 4 and 5\xskinexp.dsp

  4. Allow Visual Studio to create a project workspace (stored as a .dsw file).
  5. From the Visual Studio Project menu, select Settings.
  6. In the Project Settings window, click the C++ tab.
  7. In the Category drop box, select Preprocessor.
  8. In the Additional include directories box, insert the following path:

    (3ds max root)\maxsdk\include\

  9. Also add the path to the character studio SDK include directory if different than the (3ds max root)\maxsdk\include\ directory. This could be one of the following:

    (3ds max root)\cstudio\include\

    (3ds max root)\cstudio\

  10. Click the Link tab.
  11. In the Category drop box, select Input.
  12. In the Additional library path box, insert the following path:

    (3ds max root)\maxsdk\lib\

  13. Also add the path to the character studio SDK lib directory if different than the (3ds max root)\maxsdk\lib directory. This could be one of the following:

    (3ds max root)\cstudio\lib\

    (3ds max root)\cstudio\

  14. Save these settings.
  15. Compile and build the exporter from the Build menu in Visual Studio.
  16. Copy the resulting file:

    xskinexp.dle

    to the following directory:

    (3ds max root)\plugins\

You can confirm that the exporter plug-in is loaded into 3ds max as follows. From the 3ds max Customize menu, select Plug-in Manager..., and you should see a green "loaded" dot next to the Xskinexp.dle exporter, along with its location at (3ds max root)\plugins\.

User's Guide

Generate your scene in 3ds max. When the scene is ready to export, use the following procedure.

  1. From the File menu, select Export.
  2. In the Save As Type box, locate and select X-File (*.X).
  3. Choose or name a file, including the .x file extension, and click the Save button. The following dialog box appears:

    Dialog box for 3ds max scene statistics and file options

  4. Unless you want to select other options, click the Go! button.

    The following table lists the export options and their descriptions.

    Export Options | Description
    Text | Default export option.
    Binary or Binary Compressed | Content is not affected.
    Export Patch Data | Existing high-order surfaces will be exported as patches instead of polygonal meshes.
    Include Animation Data | Animation will occur at the selected sample rate in frames per second.
    Looping Animation Data | The D3DX animation controller (ID3DXAnimationController) will replay (loop) the animation.

For a skinned mesh scene, bone limitations are also provided in the dialog box. The exporter plug-in does not support bones that are not attached to a parent 3-D object; bones must be attached with the "node" button in 3ds max.

Note Microsoft Direct3D interfaces require object names in a C-style naming convention, where each name must start with a letter from 'a' to 'z,' or an underscore (_). The 3ds max exporter will correct your names to this convention.

Related Topics

  • Effect File Exporter (Maya Preview Pipeline)


DXTex
Microsoft DirectX 9.0 SDK Update (October 2004)

DXTex

Description

The Microsoft DirectX Texture (DXTex) tool enables DirectX software development kit (SDK) users to create texture maps that use the DXTn compression formats. Creating a DXTn-compressed texture is not difficult. However, Microsoft Direct3D can do the conversion for you when using the IDirect3DTexture9 interface. Advanced developers will probably want to write their own tools that meet their specific needs, but the DXTex tool provides useful basic functionality.

Functionality

  • Opens .bmp and Microsoft DirectDraw surface (DDS) files. For more information, see DDS File Format in this topic.
  • Opens .bmp files as alpha channel, either explicitly or implicitly, using a filename_a.bmp naming convention.
  • Saves textures in DDS format.
  • Supports conversion to all five DXTn compression formats.
  • Supports generation of mipmaps, using a box filter.
  • Supports visualization of alpha channel as a grayscale image or through a user-selectable background color.
  • Supports easy visual comparison of image quality between formats.

Note that DXTex does not currently support textures with surface formats that do not contain at least an R, G, and B texture (such as D3DFMT_G16R16 and D3DFMT_A8), although D3DX can load and save such textures in DDS format.

Path

Source: | (SDK root)\Samples\C++\Direct3D\DXTex
Executable: | (SDK root)\Samples\C++\Direct3D\Bin

User Interface

DXTex uses a fairly traditional user interface (UI) in that each texture map is a document, and several documents can be open at one time. However, each document can hold the texture in either one or two formats simultaneously while the document is open in DXTex. For example, you can import a .bmp file, which automatically creates a 32-bit ARGB texture. You can then choose to convert the texture to DXT1 format. The document now has the image open in both formats, and you can switch between the formats by clicking the window. You can also switch by clicking Original View or New View on the View menu. This makes it easy for you to observe any artifacts introduced by image compression, and to try different compression formats without progressive degradation of the image. For example, if this technique is not used and you convert an image from ARGB to DXT1, all but one bit of alpha is lost.

If you then decide to convert to DXT2, there are still only two alpha levels. Using the DXTex system, the second conversion is done from the original ARGB format, and the DXT2 image will contain all 16 levels of alpha supported by DXT2. When the image is saved, the original format is discarded and only the new format is stored.

Keep in mind the following when using the DXTex interface.

  • If no format conversion has been requested since the document was opened, the one format is the original format - that is, the format in which the image will be written when the document is saved.
  • If format conversion has been requested since the document was opened, the converted format is the new format - that is, the format in which the image will be written when the document is saved.
  • If a second format conversion is requested, the new format from the first conversion is replaced with the second format. The original format will be unchanged.
  • Generating mipmaps applies to both formats simultaneously.
  • If the original format has multiple mipmaps and conversion to a new format is requested, the new format will automatically have multiple mipmaps as well.

Performance

DXTex uses the Direct3D Reference Rasterizer to draw the textures, regardless of what 3-D hardware is available. So with larger textures (greater than 256-by-256 pixels), the application may be somewhat slow, depending on your CPU speed.

DDS File Format

See DDS File Reference for more detailed information about the DDS file format.

Mipmaps

Mipmapping is a technique that improves image quality and reduces texture memory bandwidth by providing prefiltered versions of the texture image at multiple resolutions.

To generate mipmaps in DXTex, the width and height of the source image must both be powers of two. To do this, go to the Format menu and click Generate Mip Maps. Filtering is done through a simple box filter. That is, the four nearest pixels are averaged to produce each destination pixel.

Alpha

Many texture formats include an alpha channel, which provides opacity information at each pixel. DXTex fully supports alpha in textures. When you import a .bmp file, if there is a file of the same size with a name that ends in "_a" - for example, Sample.bmp and Sample_a.bmp - the second file is loaded as an alpha channel. The blue channel of the second .bmp is stored in the alpha channel. When a document is open, you can explicitly load a .bmp file as the alpha channel by clicking Open As Alpha Channel on the File menu.

To view the alpha channel directly, without the RGB channels, on the View menu, click Alpha Channel Only. The alpha channel appears as a grayscale image. If no alpha channel has been loaded, every pixel has a full alpha channel and the image appears solid white when viewing "Alpha Channel Only." To turn off alpha channel viewing, click the Alpha Channel Only command a second time.

In the usual view, the effect of the alpha channel is visible because the window has a solid background color that shows through the texture where the alpha channel is less than 100 percent. You can change this background color by clicking Change Background Color on the View menu. This choice does not affect the texture itself or the data that is written when the file is saved.

The DXT2 and DXT4 formats use premultiplied alpha. This means that the red, green, and blue values stored in the surface are already multiplied by the corresponding alpha value. Direct3D cannot copy from a surface that contains premultiplied alpha to one that contains non-premultiplied alpha, so some DXTex operations (Open as Alpha Channel, conversion to DXT3, and conversion to DXT5) are not possible on DXT2 and DXT4 formats. Supporting textures using these formats is difficult on Direct3D devices that do not support DXTn textures. This is because Direct3D cannot copy them to a traditional ARGB surface either, unless that ARGB surface uses premultiplied alpha as well, which is rare. For this reason, you might find it easier to use DXT3 rather than DXT2, and DXT5 rather than DXT4 when possible.

Command-Line Options

You can use command-line options to pass input files, an output file name, and processing options to DXTex. If an output file name is specified, the application exits automatically after writing the output file, and no user interface is presented.

dxtex [infilename] [-a alphaname] [-m] [DXT1|DXT2|DXT3|DXT4|DXT5] [outfilename]

infilename:               Name of the file to load.  This can be a
                            .bmp or .dds file.

-a alphaname:             The next parameter is the name of a .bmp
                            file to load as the alpha channel. If no
                            alpha filename is specified, DXTex still
                            looks for a file named Infilename_a.bmp. If
                            it exists, use that file as the alpha
                            channel.

-m:                       Mipmaps are generated.

DXT1|DXT2|DXT3|DXT4|DXT5: Compression format. If no format is
                            specified, the image will be in ARGB-8888.

outfilename:              Name of the destination file. If this
                            option is not specified, the user interface
                            shows the current file and all requested
                            operations.  If an outfilename is specified,
                            the application exits after saving the
                            processed file without presenting a user
                            interface.


texconv
Microsoft DirectX 9.0 SDK Update (October 2004)

texconv

Textures can be converted between formats using the texconv.exe from the command line.

Path

Executable: (SDK root)\Utilities\Texconv.exe

Syntax

The command-line usage is:

texconv <Switch Options> <Filename>

Switch Options

The assembler switch options are:

Character | Description
-w | Width
-h | Height
-d | Depth
-m | Miplevels
-f | Format. Use any of the formats in D3DFORMAT without the D3DFMT_ prefix (except: D3DFMT_MULTI2_ARGB8).
-if | Image filter. Use one of: NONE, POINT, LINEAR, TRIANGLE, BOX, NONE_DITHER, POINT_DITHER, LINEAR_DITHER, TRIANGLE_DITHER, BOX_DITHER
-mf | Mip filter
-c | Colorkey
-srgb | sRGB {input, output}
-px | Name prefix
-sx | Name suffix
-o | Output directory
-ft | File type. Use one of: bmp, dds, jpg, hdr, pfm, png
/nologo | Suppress copyright message.


D3DSpy
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DSpy

D3DSpy is a utility that monitors function calls to the Microsoft Direct3D application programming interface (API), and shows a representation of Direct3D's internal state. This is valuable when writing a Direct3D program, or when trying to understand why a program is behaving as it is. D3DSpy can also be used to improve the performance of a Direct3D program by identifying redundant or inefficient use of the Direct3D API.

D3DSpy can monitor a program running on the same computer as the D3DSpy user interface or on a different computer, communicating by way of Microsoft DirectPlay. D3DSpy works by providing a proxy dynamic-link library (DLL), which the application connects to and treats like the real D3d9.dll. It intercepts all the Direct3D calls and gathers various information before making the real Direct3D call.

Elements of D3DSpy

The elements of D3DSpy are defined as follows:

  • D3DSpy Remote Helper (D3dspy.exe). When running D3DSpy across the network, D3DSpy can optionally be run on the target computer in the role of a remote helper program. This enables the user to send requests from the main D3DSpy user interface to the remote helper to launch the target program on the remote computer.
  • Target Program. This is the program that you want to monitor with D3DSpy. The program must use Direct3D version 9.0.
  • Proxy DLL (D3dspy9.dll). This is a DLL that the target program connects to as though it were the real D3d9.dll. The proxy DLL gathers call information and communicates with the main D3DSpy user interface.
  • D3DSpy User Interface (D3dspy.exe). This program provides the user interface that lets the user monitor the state of Direct3D, step through calls to Direct3D, and set breakpoints. It also acts as the network host when running D3DSpy across the network.

The communication between the elements is shown here.

Running D3DSpy on a Direct3D Program

To start using D3DSpy, choose Start, All Programs, Microsoft DirectX 9.0 SDK, DirectX Utilities, D3DSpy. You will see the Startup box:

The first option, local mode, runs both the target program and the D3DSpy user interface on the same computer.

The second and third options, remote mode, runs the D3DSpy the target program and the user interface on different computers. Remote mode supports monitoring of Direct3D programs running full-screen.

In the Startup box, choose the mode you want.

  • To run in local mode, click the first option (radio button).
  • To run in remote mode:
    • Click the second option to run the target program on the remote computer.

      - or -

    • Click the third option to run the D3DSpy user interface on the remote computer.

Press Continue. If you are running in remote mode, the D3DSpy Remote Helper will display the Looking For Host dialog box.

Looking For Host dialog box

To show the Start Target Program dialog box, click Connect.

Start Target dialog box

In the Start Target Program dialog box, enter the target name or, in the Path to target executable box, enter the path, either by typing it or by clicking Browse and selecting it. In addition, you can enter the initial working directory for the target program, or any command-line arguments that you want to pass to the target program.

When the target program starts, it must connect to the D3DSpy proxy DLL rather than to the real D3d9.dll. The easiest way to do this is to have D3DSpy copy the proxy DLL to the same directory as the target program. To do this:

  1. Click the Copy DLL from option button, and enter the path to the proxy DLL by typing it in or by clicking Browse and selecting it. Note that the proxy DLL is stored in the software development kit (SDK) as D3dspy9.dll but is renamed to D3d9.dll while it is copied.
  2. Select the Delete copied DLL after target program exits check box. You will generally want to to do this because, if the proxy DLL is not deleted, the next time you run the target program it will connect to the proxy DLL and attempt to use D3DSpy, which might not be what you want.
  3. Press OK. The DLL will be copied and the target program and launched automatically. Alternatively, you can start the target program manually (perhaps under a debugger or development environment). If you start the target program manually, however, you are responsible for having the proxy DLL copied and named properly.

When the target program starts, it should connect to the proxy DLL, which will then connect to the main D3DSpy user interface (and the helper program, if it is present). At this point, the main D3DSpy dialog box will appear:

Main User Interface

The main dialog box has tabs allowing navigation between several pages, each of which shows a different function of D3DSpy or a different section of the current state of Direct3D as the program runs.

Interacting with D3DSpy from a program

D3DSpy works on any program that uses Direct3D version 9.0, without special modification. However, you can add D3DSpy-specific code to your program to achieve several useful results, as follows:

To find out if D3DSpy is currently running on a program, add the following code to the program.

    typedef VOID (*D3DSPYBREAK)();
    HMODULE hModule;
    D3DSPYBREAK D3DSpyBreak;
    hModule = LoadLibrary( TEXT("d3d9.dll") );
    if( hModule != NULL )
    {
        D3DSpyBreak = (D3DSPYBREAK)GetProcAddress( hModule, "D3DSpyBreak" );
        if( D3DSpyBreak != NULL )
        {
            // D3DSpy is monitoring this program.
        }
        else
        {
            // D3DSpy is not monitoring this program.
        }
    }

To block D3DSpy from monitoring a program, add the following code to the program.

    typedef VOID (*DISABLED3DSPY)();
    HMODULE hModule;
    DISABLED3DSPY DisableD3DSpy;
    hModule = LoadLibrary( TEXT("d3d9.dll") );
    if( hModule != NULL )
    {
        DisableD3DSpy = (DISABLED3DSPY)GetProcAddress( hModule, "DisableD3DSpy" );
        if( DisableD3DSpy != NULL )
        {
            // D3DSpy is monitoring this program.
            DisableD3DSpy();
        }
        else
        {
            // D3DSpy is not monitoring this program.
        }
    }

To generate a breakpoint in D3DSpy at a certain point in your program, add the following code to the program.

    typedef VOID (*D3DSPYBREAK)();
    HMODULE hModule;
    D3DSPYBREAK D3DSpyBreak;
    hModule = LoadLibrary( TEXT("d3d9.dll") );
    if( hModule != NULL )
    {
        D3DSpyBreak = (D3DSPYBREAK)GetProcAddress( hModule, "D3DSpyBreak" );
        if( D3DSpyBreak != NULL )
        {
            // D3DSpy is monitoring this program.
            D3DSpyBreak();
        }
        else
        {
            // D3DSpy is not monitoring this program.
        }
    }


Tutorials and Samples
Microsoft DirectX 9.0 SDK Update (October 2004)

Tutorials and Samples

The software development kit (SDK) provides several sources of sample code.

  • Tutorials are built from the ground up and contain only those application programming interface (API) calls necessary to exercise Microsoft Direct3D functionality.
  • Samples demonstrate the lastest features of Microsoft DirectX 9.0 as well as functionality that is fundamental to using Direct3D. All of the samples are built on top of the sample framework.
  • The HLSL Workshop uses effects files designed in high-level shader language (HLSL). These files are ready to run in EffectEdit Sample which provides a convenient framework for learning to program HLSL shaders and effects.


Tutorials
Microsoft DirectX 9.0 SDK Update (October 2004)

Tutorials

There are two sets of tutorials in the software development kit (SDK). The first set of tutorials demonstrates basic Microsoft Direct3D functionality. The second set of tutorials makes it easy to learn how to generate high-level shader language (HLSL) shaders.

  • Direct3D Tutorials
  • HLSL Workshop
  • PIX Tutorials


Direct3D Tutorials
Microsoft DirectX 9.0 SDK Update (October 2004)

Direct3D Tutorials

The introductory tutorials in this section show how to use Microsoft Direct3D and D3DX in a C/C++ application. The tasks are divided into required steps. The following tutorials are provided:

Tutorials

  • Tutorial 1: Creating a Device
  • Tutorial 2: Rendering Vertices
  • Tutorial 3: Using Matrices
  • Tutorial 4: Creating and Using Lights
  • Tutorial 5: Using Texture Maps
  • Tutorial 6: Using Meshes

The sample code in these tutorials is from source projects whose location is provided in each tutorial. The sample files in these tutorials are written in C++. If you are using a C compiler, you must make the appropriate changes to the files for them to successfully compile. At the very least, you need to add the vtable and this pointers to the interface methods.

Some comments in the included sample code might differ from the source files in the Microsoft Platform Software Development Kit (SDK). Changes are made for brevity only and are limited to comments to avoid changing the behavior of the sample code.


Tutorial 1: Creating a Device
Microsoft DirectX 9.0 SDK Update (October 2004)

Tutorial 1: Creating a Device

To use Microsoft Direct3D, you first create an application window, then you create and initialize Direct3D objects. You use the Component Object Model (COM) interfaces that these objects implement to manipulate them and to create other objects required to render a scene. The CreateDevice sample project on which this tutorial is based illustrates these tasks by creating a Direct3D device and rendering a blue screen.

This tutorial uses the following steps to initialize Direct3D, render a scene, and eventually shut down.

Steps

  • Step 1: Creating a Window
  • Step 2: Initializing Direct3D
  • Step 3: Handling System Messages
  • Step 4: Rendering and Displaying a Scene
  • Step 5: Shutting Down

Note The path of the CreateDevice sample project is:

(SDK root)\Samples\C++\Direct3D\Tutorials\Tut01_CreateDevice


Step 1: Creating a Window
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 1: Creating a Window

The first thing any Microsoft Windows application must do when it is run is to create an application window to display to the user. To do this, the CreateDevice sample project begins execution at its WinMain function. The following sample code performs window initialization.
INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR, INT )
{
    // Register the window class.
    WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L,
                      GetModuleHandle(NULL), NULL, NULL, NULL, NULL,
                      "Direct3D Tutorial", NULL };

    RegisterClassEx( &wc );

    // Create the application's window.
    HWND hWnd = CreateWindow( "Direct3D Tutorial", "Direct3D Tutorial 01: CreateDevice",
                              WS_OVERLAPPEDWINDOW, 100, 100, 300, 300,
                              GetDesktopWindow(), NULL, wc.hInstance, NULL );

The preceding code sample is standard Windows programming. The sample starts by defining and registering a window class called "Direct3D Tutorial." After the class is registered, the sample code creates a basic top-level window that uses the registered class, with a client area of 300 pixels wide by 300 pixels tall. This window has no menu or child windows. The sample uses the WS_OVERLAPPEDWINDOW window style to create a window that includes Minimize, Maximize, and Close buttons common to windowed applications. (If the sample were to run in full-screen mode, the preferred window style is WS_EX_TOPMOST, which specifies that the created window should be placed above all non-topmost windows and should stay above them, even when the window is deactivated.) When the window is created, the code sample calls standard Microsoft Win32 functions to display and update the window.

With the application window ready, you can begin setting up the essential Microsoft Direct3D objects, as described in Step 2: Initializing Direct3D.


Step 2: Initializing Direct3D
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 2: Initializing Direct3D

The CreateDevice sample project performs Microsoft Direct3D initialization in the InitD3D application-defined function called from WinMain after the window is created. After you create an application window, you are ready to initialize the Direct3D object that you will use to render the scene. This process includes creating the object, setting the presentation parameters, and finally creating the Direct3D device.

After creating a Direct3D object, use the IDirect3D9::CreateDevice method to create a device, and to enumerate devices, types, modes, and so on.

if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
    return E_FAIL;

The only parameter passed to Direct3DCreate9 should always be D3D_SDK_VERSION. This informs Direct3D that the correct header files are being used. This value is incremented whenever a header or other change would require applications to be rebuilt. If the version does not match, Direct3DCreate9 will fail.

By filling in the fields of D3DPRESENT_PARAMETERS you can specify how you want your 3-D application to behave. The CreateDevice sample project sets Windowed to TRUE, SwapEffect to D3DSWAPEFFECT_DISCARD, and BackBufferFormat to D3DFMT_UNKNOWN.

D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory( &d3dpp, sizeof(d3dpp) );
d3dpp.Windowed = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;

The final step is to use the IDirect3D9::CreateDevice method to create the Direct3D device, as illustrated in the following code example.

if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                                  D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                  &d3dpp, &g_pd3dDevice ) ) )

The preceding code sample creates the device with the default adapter by using the D3DADAPTER_DEFAULT flag. In most cases, the system will have only a single adapter, unless it has multiple graphics hardware cards installed. Indicate that you prefer a hardware device over a software device by specifying D3DDEVTYPE_HAL for the DeviceType parameter. This code sample uses D3DCREATE_SOFTWARE_VERTEXPROCESSING to tell the system to use software vertex processing. Note that if you tell the system to use hardware vertex processing by specifying D3DCREATE_HARDWARE_VERTEXPROCESSING, you will see a significant performance gain on video cards that support hardware vertex processing.

Now that the Direct3D object has been initialized, the next step is to ensure that you have a mechanism to process system messages, as described in Step 3: Handling System Messages.


Step 3: Handling System Messages
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 3: Handling System Messages

After you have created the application window and initialized Microsoft Direct3D, you are ready to render the scene. In most cases, Microsoft Windows applications monitor system messages in their message loop, and they render frames whenever no messages are in the queue. However, the CreateDevice sample project waits until a WM_PAINT message is in the queue, telling the application that it needs to redraw all or part of its window.

// The message loop.
MSG msg;
while( GetMessage( &msg, NULL, 0, 0 ) )
{
    TranslateMessage( &msg );
    DispatchMessage( &msg );
}

Each time the loop runs, DispatchMessage calls MsgProc, which handles messages in the queue. When WM_PAINT is queued, the application calls Render, the application-defined function that will redraw the window. Then the Microsoft Win32 function ValidateRect is called to validate the entire client area.

The sample code for the message-handling function is shown below.

LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
    switch( msg )
    {
        case WM_DESTROY:
            PostQuitMessage( 0 );
            return 0;

        case WM_PAINT:
            Render();
            ValidateRect( hWnd, NULL );
            return 0;
    }

    return DefWindowProc( hWnd, msg, wParam, lParam );
}

Now that the application handles system messages, the next step is to render the display, as described in Step 4: Rendering and Displaying a Scene.


Step 4: Rendering and Displaying a Scene
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 4: Rendering and Displaying a Scene

To render and display the scene, the sample code in this step clears the back buffer to a blue color, transfers the contents of the back buffer to the front buffer, and presents the front buffer to the screen.

To clear a scene, call the IDirect3DDevice9::Clear method.

// Clear the back buffer to a blue color
g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,255), 1.0f, 0 );

The first two parameters accepted by IDirect3DDevice9::Clear inform Microsoft Direct3D of the size and address of the array of rectangles to be cleared. The array of rectangles describes the areas on the render-target surface to be cleared.

In most cases, you use a single rectangle that covers the entire rendering target. You do this by setting the first parameter to zero and the second parameter to NULL. The third parameter determines the method's behavior. You can specify a flag to clear a render-target surface, an associated depth buffer, the stencil buffer, or any combination of the three. This tutorial does not use a depth buffer, so D3DCLEAR_TARGET is the only flag used. The last three parameters are set to reflect clearing values for the render target, depth buffer, and stencil buffer. The CreateDevice sample project sets the clear color for the render-target surface to blue (D3DCOLOR_XRGB(0,0,255)). The final two parameters are ignored by the IDirect3DDevice9::Clear method because the corresponding flags are not present.

After clearing the viewport, the CreateDevice sample project informs Direct3D that rendering will begin, then signals that rendering is complete, as shown in the following code fragment:

// Begin the scene
g_pd3dDevice->BeginScene();

// Rendering of scene objects happens here

// End the scene
g_pd3dDevice->EndScene();

The IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene methods signal to the system when rendering is beginning or is complete. You can call rendering methods only between calls to these methods. Even if rendering methods fail, you should call EndScene before calling BeginScene again.

After rendering the scene, you display it by using the IDirect3DDevice9::Present method.

g_pd3dDevice->Present( NULL, NULL, NULL, NULL );

The first two parameters are a source rectangle and destination rectangle. The sample code in this step presents the entire back buffer to the front buffer by setting these two parameters to NULL. The third parameter sets the destination window for this presentation. Because this parameter is set to NULL, the hWndDeviceWindow member of D3DPRESENT_PARAMETERS is used. The fourth parameter is the DirtyRegion parameter and in most cases should be set to NULL.

The final step for this tutorial is shutting down the application, as described in Step 5: Shutting Down.


Step 5: Shutting Down
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 5: Shutting Down

At some point during execution, your application must shut down. Shutting down a Microsoft DirectX application not only means that you destroy the application window, but you also deallocate any DirectX objects your application uses, and you invalidate the pointers to them. The CreateDevice sample project calls Cleanup, an application-defined function to handle this when it receives a WM_DESTROY message.

VOID Cleanup()
{
    if( g_pd3dDevice != NULL)
        g_pd3dDevice->Release();
    if( g_pD3D != NULL)
        g_pD3D->Release();
}

The preceding function deallocates the DirectX objects it uses by calling the IUnknown::Release methods for each object. Because this tutorial follows COM rules, the reference count for most objects should become zero and should be automatically removed from memory.

In addition to shutdown, there are times during normal execution—such as when the user changes the desktop resolution or color depth—when you might need to destroy and re-create the Microsoft Microsoft Direct3D objects in use. Therefore it is a good idea to keep your application's cleanup code in one place, which can be called when the need arises.

This tutorial has shown you how to create a device. Tutorial 2: Rendering Vertices shows you how to use vertices to draw geometric shapes.


Tutorial 2: Rendering Vertices
Microsoft DirectX 9.0 SDK Update (October 2004)

Tutorial 2: Rendering Vertices

Applications written in Microsoft Direct3D use vertices to draw geometric shapes. Each three-dimensional (3-D) scene includes one or more of these geometric shapes. The Vertices sample project creates the simplest shape, a triangle, and renders it to the display.

This tutorial shows how to use vertices to create a triangle with the following steps:

Steps

  • Step 1: Defining a Custom Vertex Type
  • Step 2: Setting Up the Vertex Buffer
  • Step 3: Rendering the Display

Note The path of the Vertices sample project is:

(SDK root)\Samples\C++\Direct3D\Tutorials\Tut02_Vertices

The sample code in the Vertices project is nearly identical to the sample code in the CreateDevice project. The Rendering Vertices tutorial focuses only on the code unique to vertices and does not cover initializing Direct3D, handling Microsoft Windows messages, rendering, or shutting down. For information about these tasks, see Tutorial 1: Creating a Device.


Step 1: Defining a Custom Vertex Type
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 1: Defining a Custom Vertex Type

The Vertices sample project renders a 2-D triangle by using three vertices. This introduces the concept of the vertex buffer, which is a Microsoft Direct3D object that is used to store and render vertices. Vertices can be defined in many ways by specifying a custom vertex structure and corresponding custom flexible vertex format (FVF). The format of the vertices in the Vertices sample project is shown in the following code fragment:

struct CUSTOMVERTEX
{
    FLOAT x, y, z, rhw; // The transformed position for the vertex.
    DWORD color;        // The vertex color.
};

The structure above specifies the format of the custom vertex type. The next step is to define the FVF that describes the contents of the vertices in the vertex buffer. The following code fragment defines an FVF that corresponds with the custom vertex type created above.

#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZRHW|D3DFVF_DIFFUSE)

D3DFVF describes what type of custom vertex is being used. The sample code above uses the D3DFVF_XYZRHW and D3DFVF_DIFFUSE flags, which tell the vertex buffer that the custom vertex type has a transformed point followed by a color component.

Now that the custom vector format and FVF are specified, the next step is to fill the vertex buffer with vertices, as described in Step 2: Setting Up the Vertex Buffer.

Note The vertices in the Vertices sample project are transformed. In other words, they are already in 2-D window coordinates. This means that the point (0,0) is at the top left corner and the positive x-axis is right and the positive y-axis is down. These vertices are also lit, meaning that they are not using Direct3D lighting but are supplying their own color.


Step 2: Setting Up the Vertex Buffer
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 2: Setting Up the Vertex Buffer

Now that the custom vertex format is defined, it is time to initialize the vertices. The Vertices sample project does this by calling the application-defined function InitVB after creating the required Microsoft Direct3D objects. The following code fragment initializes the values for three custom vertices.

CUSTOMVERTEX vertices[] =
{
    { 150.0f,  50.0f, 0.5f, 1.0f, 0xffff0000, }, // x, y, z, rhw, color
    { 250.0f, 250.0f, 0.5f, 1.0f, 0xff00ff00, },
    {  50.0f, 250.0f, 0.5f, 1.0f, 0xff00ffff, },
};

The preceding code fragment fills three vertices with the points of a triangle and specifies which color each vertex will emit. The first point is at (150, 50) and emits the color red (0xffff0000). The second point is at (250, 250) and emits the color green (0xff00ff00). The third point is at (50, 250) and emits the color blue-green (0xff00ffff). Each of these points has a depth value of 0.5 and an RHW of 1.0.

The next step is to call IDirect3DDevice9::CreateVertexBuffer to create a vertex buffer as shown in the following code fragment.

if( FAILED( g_pd3dDevice->CreateVertexBuffer( 3*sizeof(CUSTOMVERTEX),
         0 /*Usage*/, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL ) ) )
    return E_FAIL;

The first two parameters of IDirect3DDevice9::CreateVertexBuffer tell Direct3D the desired size and usage for the new vertex buffer. The next two parameters specify the vector format and memory location for the new buffer. The vector format here is D3DFVF_CUSTOMVERTEX, which is the flexible vertex format (FVF) that the sample code specified earlier. The D3DPOOL_DEFAULT flag tells Direct3D to create the vertex buffer in the memory allocation that is most appropriate for this buffer. The final parameter is the address of the vertex buffer to create.

After creating a vertex buffer, it is filled with data from the custom vertices as shown in the following code fragment.

VOID* pVertices;
if( FAILED( g_pVB->Lock( 0, sizeof(vertices), (void**)&pVertices, 0 ) ) )
    return E_FAIL;

memcpy( pVertices, vertices, sizeof(vertices) );

g_pVB->Unlock();

The vertex buffer is first locked by calling IDirect3DVertexBuffer9::Lock. The first parameter is the offset into the vertex data to lock, in bytes. The second parameter is the size of the vertex data to lock, in bytes. The third parameter is the address of a BYTE pointer, filled with a pointer to vertex data. The fourth parameter tells the vertex buffer how to lock the data.

The vertices are then copied into the vertex buffer using memcpy. After the vertices are in the vertex buffer, a call is made to IDirect3DVertexBuffer9::Unlock to unlock the vertex buffer. This mechanism of locking and unlocking is required because the vertex buffer may be in device memory.

Now that the vertex buffer is filled with the vertices, it is time to render the display, as described in Step 3: Rendering the Display.


Step 3: Rendering the Display
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 3: Rendering the Display

Now that the vertex buffer is filled with vertices, it is time to render the display. Rendering the display starts by clearing the back buffer to a blue color and then calling BeginScene.

g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,255), 1.0f, 0L );
g_pd3dDevice->BeginScene();

Rendering vertex data from a vertex buffer requires a few steps. First, you need to set the stream source; in this case, use stream 0. The source of the stream is specified by calling IDirect3DDevice9::SetStreamSource.

g_pd3dDevice->SetStreamSource( 0, g_pVB, 0, sizeof(CUSTOMVERTEX) );

The first parameter is the stream number and the second parameter is a pointer to the vertex buffer. The third parameter is the offset from the beginning of the stream to the beginning of the vertex data, which is 0 in this example. The last parameter is the number of bytes of each element in the vertex declaration.

The next step is to call IDirect3DDevice9::SetFVF to identify the fixed function vertex shader. Full, custom vertex shaders are an advanced topic, but in this case the vertex shader is only the flexible vertex format (FVF) code. The following code fragment sets the FVF code.

g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );

The only parameter for SetFVF is the fixed vertex function code to define the vertex data layout.

The next step is to use IDirect3DDevice9::DrawPrimitive to render the vertices in the vertex buffer as shown in the following code fragment.

g_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, 1 );

The first parameter accepted by DrawPrimitive is a flag that tells Microsoft Direct3D what type of primitives to draw. This sample uses the flag D3DPT_TRIANGLELIST to specify a list of triangles. The second parameter is the index of the first vertex to load. The third parameter tells the number of primitives to draw. Because this sample draws only one triangle, this value is set to 1.

For more information about different kinds of primitives, see 3-D Primitives.

The last steps are to end the scene and then present the back buffer to the front buffer. This is shown in the following code fragment.

g_pd3dDevice->EndScene();
g_pd3dDevice->Present( NULL, NULL, NULL, NULL );

After the back buffer is presented to the front buffer, the client window shows a triangle with three different colored points.

This tutorial has shown you how to use vertices to render geometric shapes. Tutorial 3: Using Matrices introduces the concept of matrices and how to use them.


Tutorial 3: Using Matrices
Microsoft DirectX 9.0 SDK Update (October 2004)

Tutorial 3: Using Matrices

This tutorial introduces the concept of matrices and shows how to use them. The Vertices sample project rendered 2-D vertices to draw a triangle. However, in this tutorial you will be working with transformations of vertices in 3-D. Matrices are also used to set up cameras and viewports.

Before the Matrices sample project renders geometry, it calls the SetupMatrices application-defined function to create and set the matrix transformations that are used to render the 3-D triangle. Typically, three types of transformation are set for a 3-D scene. Steps for creating each one of these typical transformations are listed below.

Steps

  • Step 1: Defining the World Transformation Matrix
  • Step 2: Defining the View Transformation Matrix
  • Step 3: Defining the Projection Transformation Matrix

Note The path of the Matrices sample project is:

(SDK root)\Samples\C++\Direct3D\Tutorials\Tut03_Matrices

The order in which these transformation matrices are created does not affect the layout of the objects in a scene. However, Microsoft Direct3D applies the matrices to the scene in the following order:

  1. World
  2. View
  3. Projection

The sample code in the Matrices project is nearly identical to the sample code in the Vertices project. The Using Matrices tutorial focuses only on the code unique to matrices and does not cover initializing Direct3D, handling Microsoft Windows messages, rendering, or shutting down. For information about these tasks, see Tutorial 1: Creating a Device.

This tutorial uses custom vertices and a vertex buffer to display geometry. For more information about selecting a custom vertex type and implementing a vertex buffer, see Tutorial 2: Rendering Vertices.


Step 1: Defining the World Transformation Matrix
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 1: Defining the World Transformation Matrix

The world transformation matrix defines how to translate, scale, and rotate the geometry in the 3-D model space.

The following code fragment rotates the triangle on the y-axis and then sets the current world transformation for the Microsoft Direct3D device.

D3DXMATRIX matWorld;
D3DXMatrixRotationY( &matWorld, timeGetTime()/150.0f );
g_pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );

The first step is to rotate the triangle around the y-axis by calling the D3DXMatrixRotationY method. The first parameter is a pointer to a D3DXMATRIX structure that is the result of the operation. The second parameter is the angle of rotation in radians.

The next step is to call IDirect3DDevice9::SetTransform to set the world transformation for the Direct3D device. The first parameter accepted by IDirect3DDevice9::SetTransform tells Direct3D which transformation to set. This sample uses the D3DTS_WORLD macro to specify that the world transformation should be set. The second parameter is a pointer to a matrix that is set as the current transformation.

For more information about world transformations, see World Transform.

After defining the world transformation for the scene, you can prepare the view transformation matrix. Again, note that the order in which transformations are defined is not critical. However, Direct3D applies the matrices to the scene in the following order:

  1. World
  2. View
  3. Projection

Defining the view transformation matrix is described in Step 2: Defining the View Transformation Matrix.


Step 2: Defining the View Transformation Matrix
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 2: Defining the View Transformation Matrix

The view transformation matrix defines the position and rotation of the view. The view matrix is the camera for the scene.

The following code fragment creates the view transformation matrix and then sets the current view transformation for the Microsoft Direct3D device.

D3DXVECTOR3 vEyePt   ( 0.0f, 3.0f,-5.0f );
D3DXVECTOR3 vLookatPt( 0.0f, 0.0f, 0.0f );
D3DXVECTOR3 vUpVec   ( 0.0f, 1.0f, 0.0f );
D3DXMATRIXA16 matView;
D3DXMatrixLookAtLH( &matView, &vEyePt, &vLookatPt, &vUpVec );
g_pd3dDevice->SetTransform( D3DTS_VIEW, &matView );

The first step is to define the view matrix by calling D3DXMatrixLookAtLH. The first parameter is a pointer to a D3DXMATRIX structure that is the result of the operation. The second, third, and fourth parameters define the eye point, look-at point, and "up" direction, respectively. Here the eye is set back along the z-axis by five units and up three units, the look-at point is set at the origin, and "up" is defined as the y-direction.

The next step is to call IDirect3DDevice9::SetTransform to set the view transformation for the Direct3D device. The first parameter accepted by IDirect3DDevice9::SetTransform tells Direct3D which transformation to set. This sample uses the D3DTS_VIEW flag to specify that the view transformation should be set. The second parameter is a pointer to a matrix that is set as the current transformation.

For more information about view transformations, see View Transform.

After defining the world transformation for the scene, you can prepare the projection transformation matrix. Again, note that the order in which transformations are defined is not critical. However, Direct3D applies the matrices to the scene in the following order:

  1. World
  2. View
  3. Projection

Defining the projection transformation matrix is described in Step 3: Defining the Projection Transformation Matrix.


Step 3: Defining the Projection Transformation Matrix
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 3: Defining the Projection Transformation Matrix

The projection transformation matrix defines how geometry is transformed from 3-D view space to 2-D viewport space.

The following code fragment creates the projection transformation matrix and then sets the current projection transformation for the Microsoft Direct3D device.

D3DXMATRIX matProj;
D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI/4, 1.0f, 1.0f, 100.0f );
g_pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj );

The first step is to call D3DXMatrixPerspectiveFovLH to set up the projection matrix. The first parameter is a pointer to a D3DXMATRIX structure that is the result of the operation. The second parameter defines the field of view, which tells how objects in the distance get smaller. A typical field of view is 1/4 pi, which is what the sample uses. The third parameter defines the aspect ratio. The sample uses the typical aspect ratio of 1. The fourth and fifth parameters define the near and far clipping plane. This determines the distance at which geometry should no longer be rendered. The Matrices sample project has its near clipping plane set at 1 and its far clipping plane set at 100.

The next step is to call IDirect3DDevice9::SetTransform to apply the transformation to the Direct3D device. The first parameter accepted by IDirect3DDevice9::SetTransform tells Direct3D which transformation to set. This sample uses the D3DTS_PROJECTION flag to specify that the projection transformation should be set. The second parameter is a pointer to a matrix that is set as the current transformation.

For more information about projection transformations, see the projection transform.

This tutorial has shown you how to use matrices. Tutorial 4: Creating and Using Lights shows how to add lights to your scene for more realism.


Tutorial 4: Creating and Using Lights
Microsoft DirectX 9.0 SDK Update (October 2004)

Tutorial 4: Creating and Using Lights

Microsoft Direct3D lights add more realism to 3-D objects. When used, each geometric object in the scene will be lit based on the location and type of lights that are used. The sample code in this tutorial introduces the topics of lights and materials.

This tutorial has the following steps to create a material and a light.

Steps

  • Step 1: Initializing Scene Geometry
  • Step 2: Setting Up Material and Light

Note The path of the Lights sample project is:

(SDK root)\Samples\C++\Direct3D\Tutorials\Tut04_Lights

The sample code in the Lights project is nearly identical to the sample code in the Matrices project. The Creating and Using Lights tutorial focuses only on the code unique to creating and using lights and does not cover setting up Direct3D, handling Microsoft Windows messages, rendering, or shutting down. For information about these tasks, see Tutorial 1: Creating a Device.

This tutorial uses custom vertices and a vertex buffer to display geometry. For more information about selecting a custom vertex type and implementing a vertex buffer, see Tutorial 2: Rendering Vertices.

This tutorial makes use of matrices to transform geometry. For more information about matrices and transformations, see Tutorial 3: Using Matrices.


Step 1: Initializing Scene Geometry
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 1: Initializing Scene Geometry

One of the requirements of using lights is that each surface has a normal. To do this, the Lights sample project uses a different custom vertex type. The new custom vertex format has a 3-D position and a surface normal. The surface normal is used internally by Microsoft Direct3D for lighting calculations.

struct CUSTOMVERTEX
{
    D3DXVECTOR3 position; // The 3-D position for the vertex.
    D3DXVECTOR3 normal;   // The surface normal for the vertex.
};
// Custom flexible vertex format (FVF).
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_NORMAL)

Now that the correct vector format is defined, the Lights sample project calls InitGeometry, an application-defined function that creates a cylinder. The first step is to create a vertex buffer that stores the points of the cylinder as shown in the following sample code.

// Create the vertex buffer.
if( FAILED( g_pd3dDevice->CreateVertexBuffer( 50*2*sizeof(CUSTOMVERTEX),
                                           0 /*Usage*/, D3DFVF_CUSTOMVERTEX,
                                           D3DPOOL_DEFAULT, &g_pVB, NULL ) ) )
    return E_FAIL;

The next step is to fill the vertex buffer with the points of the cylinder. Note that in the following sample code, each point is defined by a position and a normal.

CUSTOMVERTEX* pVertices;
if( FAILED( g_pVB->Lock( 0, 0, (void**)&pVertices, 0 ) ) ) return E_FAIL;

for( DWORD i=0; i<50; i++ )
{
    FLOAT theta = (2*D3DX_PI*i)/(50-1);
    pVertices[2*i+0].position = D3DXVECTOR3( sinf(theta),-1.0f, cosf(theta) );
    pVertices[2*i+0].normal   = D3DXVECTOR3( sinf(theta), 0.0f, cosf(theta) );
    pVertices[2*i+1].position = D3DXVECTOR3( sinf(theta), 1.0f, cosf(theta) );
    pVertices[2*i+1].normal   = D3DXVECTOR3( sinf(theta), 0.0f, cosf(theta) );
}

After the preceding sample code fills the vertex buffer with the vertices for a cylinder, the vertex buffer is ready for rendering. But first, the material and light for this scene must be set up before rendering the cylinder. This is described in Step 2: Setting Up Material and Light.


Step 2: Setting Up Material and Light
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 2: Setting Up Material and Light

To use lighting in Microsoft Direct3D, you must create one or more lights. To determine which color a geometric object reflects, a material is created that is used to render geometric objects. Before rendering the scene, the Lights sample project calls SetupLights, an application-defined function that sets up one material and one directional light.

  • Creating a Material
  • Creating a Light

Creating a Material

A material defines the color that is reflected off the surface of a geometric object when a light hits it. The following code fragment uses the D3DMATERIAL9 structure to create a material that is yellow.

D3DMATERIAL9 mtrl;
ZeroMemory( &mtrl, sizeof(mtrl) );
mtrl.Diffuse.r = mtrl.Ambient.r = 1.0f;
mtrl.Diffuse.g = mtrl.Ambient.g = 1.0f;
mtrl.Diffuse.b = mtrl.Ambient.b = 0.0f;
mtrl.Diffuse.a = mtrl.Ambient.a = 1.0f;
g_pd3dDevice->SetMaterial( &mtrl );

The diffuse color and ambient color for the material are set to yellow. The call to the IDirect3DDevice9::SetMaterial method applies the material to the Direct3D device used to render the scene. The only parameter that IDirect3DDevice9::SetMaterial accepts is the address of the material to set. After this call is made, every primitive will be rendered with this material until another call is made to IDirect3DDevice9::SetMaterial that specifies a different material.

Now that material has been applied to the scene, the next step is to create a light.

Creating a Light

There are three types of lights available in Direct3D:

  • point lights
  • directional lights
  • spotlights
The sample code creates a directional light, which is a light that goes in one direction. The code also oscillates the direction of the light.

The following code fragment uses the D3DLIGHT9 structure to create a directional light.

D3DXVECTOR3 vecDir;
D3DLIGHT9 light;
ZeroMemory( &light, sizeof(light) );
light.Type = D3DLIGHT_DIRECTIONAL;

The following code fragment sets the diffuse color for this light to white.

light.Diffuse.r = 1.0f;
light.Diffuse.g = 1.0f;
light.Diffuse.b = 1.0f;

The following code fragment rotates the direction of the light around in a circle.

vecDir = D3DXVECTOR3(cosf(timeGetTime()/360.0f),
                     0.0f,
                     sinf(timeGetTime()/360.0f) );
D3DXVec3Normalize( (D3DXVECTOR3*)&light.Direction, &vecDir );

The call to D3DXVec3Normalize normalizes the direction vector used to determine the direction of the light.

A range can be specified to tell Direct3D how far the light will have an effect. This member does not affect directional lights. The following code fragment assigns a range of 1000 units to this light.

light.Range = 1000.0f;

The following code fragment assigns the light to the Direct3D device by calling IDirect3DDevice9::SetLight.

g_pd3dDevice->SetLight( 0, &light );

The first parameter that IDirect3DDevice9::SetLight accepts is the index that this light will be assigned to. Note that if a light already exists at that location, it will be overwritten by the new light. The second parameter is a pointer to the light structure that defines the light. The Lights sample project places this light at index 0.

The following code fragment enables the light by calling IDirect3DDevice9::LightEnable.

g_pd3dDevice->LightEnable( 0, TRUE);

The first parameter that IDirect3DDevice9::LightEnable accepts is the index of the light to enable. The second parameter is a Boolean value that tells whether to turn the light on (TRUE) or off (FALSE). In the sample code above, the light at index 0 is turned on.

The following code fragment tells Direct3D to render lights by calling IDirect3DDevice9::SetRenderState.

g_pd3dDevice->SetRenderState( D3DRS_LIGHTING, TRUE );

The first two parameters that IDirect3DDevice9::SetRenderState accepts is which device state variable to modify and what value to set it to. This code sample sets the D3DRS_LIGHTING device variable to TRUE, which has the effect of enabling the rendering of lights.

The final step in this code sample is to turn on ambient lighting by again calling IDirect3DDevice9::SetRenderState.

g_pd3dDevice->SetRenderState( D3DRS_AMBIENT, 0x00202020 );

The preceding code fragment sets the D3DRS_AMBIENT device variable to a light gray color (0x00202020). Ambient lighting will light up all objects by the given color.

For more information about lighting and materials, see Lights and Materials.

This tutorial has shown you how to use lights and materials. Tutorial 5: Using Texture Maps shows you how to add texture to surfaces.


Tutorial 5: Using Texture Maps
Microsoft DirectX 9.0 SDK Update (October 2004)

Tutorial 5: Using Texture Maps

While lights and materials add a great deal of realism to a scene, nothing adds more realism than adding textures to surfaces. Textures can be thought of as wallpaper that is shrink-wrapped onto a surface. You could place a wood texture on a cube to make the cube look like it is actually made of wood. The Texture sample project adds a banana peel texture to the cylinder created in Tutorial 4: Creating and Using Lights. This tutorial covers how to load textures, set up vertices, and display objects with texture.

This tutorial implements textures using the following steps:

Steps

  • Step 1: Defining a Custom Vertex Format
  • Step 2: Initializing Screen Geometry
  • Step 3: Rendering the Scene

Note The path of the Texture sample project is:

(SDK root)\Samples\C++\Direct3D\Tutorials\Tut05_Textures

The sample code in the Texture project is nearly identical to the sample code in the Lights project, except that the Texture sample project does not create a material or a light. The Using Texture Maps tutorial focuses only on the code unique to textures and does not cover initializing Microsoft Direct3D, handling Microsoft Windows messages, rendering, or shutting down. For information about these tasks, see Tutorial 1: Creating a Device.

This tutorial uses custom vertices and a vertex buffer to display geometry. For more information about selecting a custom vertex type and implementing a vertex buffer, see Tutorial 2: Rendering Vertices.

This tutorial makes use of matrices to transform geometry. For more information about matrices and transformations, see Tutorial 3: Using Matrices.


Step 1: Defining a Custom Vertex Format
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 1: Defining a Custom Vertex Format

Before using textures, a custom vertex format that includes texture coordinates must be used. Texture coordinates tell Microsoft Direct3D where to place a texture for each vector in a primitive. Texture coordinates range from 0.0 to 1.0, where (0.0, 0.0) represents the top-left side of the texture and (1.0, 1.0) represents the lower-right side of the texture.

The following sample code shows how the Texture sample project sets up its custom vertex format to include texture coordinates.

// A structure for our custom vertex type. Texture coordinates were added.
struct CUSTOMVERTEX
{
    D3DXVECTOR3 position; // The position
    D3DCOLOR    color;    // The color
#ifndef SHOW_HOW_TO_USE_TCI
    FLOAT       tu, tv;   // The texture coordinates
#endif
};

// Custom flexible vertex format (FVF), which describes custom vertex structure
#ifdef SHOW_HOW_TO_USE_TCI
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE)
#else
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)
#endif

For more information about texture coordinates, see Texture Coordinates.

Now that a custom vertex type has been defined, the next step is to load a texture and create a cylinder, as described in Step 2: Initializing Screen Geometry.


Step 2: Initializing Screen Geometry
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 2: Initializing Screen Geometry

Before rendering, the Texture sample project calls InitGeometry, an application-defined function that creates a texture and initializes the geometry for a cylinder.

Textures are created from file-based images. The following code fragment uses D3DXCreateTextureFromFile to create a texture from Banana.bmp that will be used to cover the surface of the cylinder.

if( FAILED( D3DXCreateTextureFromFile( g_pd3dDevice, "Banana.bmp",
                                       &g_pTexture ) ) )
    return E_FAIL;

The first parameter that D3DXCreateTextureFromFile accepts is a pointer to the Microsoft Direct3D device that will be used to render the texture. The second parameter is a pointer to an ANSI string that specifies the filename from which to create the texture. This sample specifies Banana.bmp to load the image from that file. The third parameter is the address of a pointer to a texture object.

When the banana texture is loaded and ready to use, the next step is to create the cylinder. The following code sample fills the vertex buffer with a cylinder. Note that each point has the texture coordinates (tu, tv).

for( DWORD i=0; i<50; i++ )
{
    FLOAT theta = (2*D3DX_PI*i)/(50-1);

        pVertices[2*i+0].position = D3DXVECTOR3( sinf(theta),-1.0f, cosf(theta) );
        pVertices[2*i+0].color    = 0xffffffff;
#ifndef SHOW_HOW_TO_USE_TCI
        pVertices[2*i+0].tu       = ((FLOAT)i)/(50-1);
        pVertices[2*i+0].tv       = 1.0f;
#endif

        pVertices[2*i+1].position = D3DXVECTOR3( sinf(theta), 1.0f, cosf(theta) );
        pVertices[2*i+1].color    = 0xff808080;
#ifndef SHOW_HOW_TO_USE_TCI
        pVertices[2*i+1].tu       = ((FLOAT)i)/(50-1);
        pVertices[2*i+1].tv       = 0.0f;
#endif
}

Each vertex includes position, color, and texture coordinates. The code sample above sets the texture coordinates for each point so that the texture will wrap smoothly around the cylinder.

Now that the texture is loaded and the vertex buffer is ready for rendering, it is time to render the display, as described in Step 3: Rendering the Scene.


Step 3: Rendering the Scene
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 3: Rendering the Scene

After scene geometry has been initialized, it is time to render the scene. In order to render an object with texture, the texture must be set as one of the current textures. The next step is to set the texture stage states values. Texture stage states enable you to define the behavior of how a texture or textures are to be rendered. For example, you could blend multiple textures together.

The Texture sample project starts by setting the texture to use. The following code fragment sets the texture that the Microsoft Direct3D device will use to render with IDirect3DDevice9::SetTexture.

g_pd3dDevice->SetTexture( 0, g_pTexture );

The first parameter that IDirect3DDevice9::SetTexture accepts is a stage identifier to set the texture to. A device can have up to eight set textures, so the maximum value here is 7. The Texture sample project has only one texture and places it at stage 0. The second parameter is a pointer to a texture object. The Texture sample project uses the texture object that it created in its InitGeometry application-defined function.

The following code sample sets the texture stage state values by calling the IDirect3DDevice9::SetTextureStageState method.

    // Setup texture. Using textures introduces the texture stage states, which
    //   govern how textures get blended together (in the case of multiple
    //   textures) and lighting information. In this case, you are modulating
    //   (blending) your texture with the diffuse color of the vertices.
    g_pd3dDevice->SetTexture( 0, g_pTexture );
    g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP,   D3DTOP_MODULATE );
    g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
    g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
    g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP,   D3DTOP_DISABLE );

#ifdef SHOW_HOW_TO_USE_TCI
    // Note: To use Direct3D texture coordinate generation, use the stage state
    // D3DTSS_TEXCOORDINDEX, as shown below. In this example, you are using
    // the position of the vertex in camera space to generate texture
    // coordinates. The tex coord index (TCI) parameters are passed into a
    // texture transform, which is a 4x4 matrix that transforms the x,y,z
    // TCI coordinates into tu, tv texture coordinates.

    // In this example, the texture matrix is set up to
    // transform the texture from (-1,+1) position coordinates to (0,1)
    // texture coordinate space:
    //    tu =  0.5*x + 0.5
    //    tv = -0.5*y + 0.5
    D3DXMATRIXA16 mat;
    mat._11 = 0.25f; mat._12 = 0.00f; mat._13 = 0.00f; mat._14 = 0.00f;
    mat._21 = 0.00f; mat._22 =-0.25f; mat._23 = 0.00f; mat._24 = 0.00f;
    mat._31 = 0.00f; mat._32 = 0.00f; mat._33 = 1.00f; mat._34 = 0.00f;
    mat._41 = 0.50f; mat._42 = 0.50f; mat._43 = 0.00f; mat._44 = 1.00f;

    g_pd3dDevice->SetTransform( D3DTS_TEXTURE0, &mat );
    g_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS,
                  D3DTTFF_COUNT2 );
    g_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX,
                  D3DTSS_TCI_CAMERASPACEPOSITION );
#endif

The first parameter that IDirect3DDevice9::SetTextureStageState accepts is the stage index for the state variable to be set. This code sample changes the values for the texture at stage 0, so it puts a zero here. The next parameter is the texture state to set. For a list of all valid texture states and their meaning, see D3DTEXTURESTAGESTATETYPE. The next parameter is the value to which the texture state will be set. The value that you place here is based on the texture stage state value that you are modifying.

After setting up the desired values for each texture stage state, the cylinder can be rendered and texture will be added to the surface.

Another way to use texture coordinates is to automatically generate them. This is done by using a texture coordinate index (TCI). The TCI uses a texture matrix to transform the (x,y,z) TCI coordinates into (tu, tv) texture coordinates. In the Texture sample project, the position of the vertex in camera space is used to generate texture coordinates.

The first step is to create the matrix that will be used for the transformation, as demonstrated in the following code fragment.

D3DXMATRIX mat;
mat._11 = 0.25f; mat._12 = 0.00f; mat._13 = 0.00f; mat._14 = 0.00f;
mat._21 = 0.00f; mat._22 =-0.25f; mat._23 = 0.00f; mat._24 = 0.00f;
mat._31 = 0.00f; mat._32 = 0.00f; mat._33 = 1.00f; mat._34 = 0.00f;
mat._41 = 0.50f; mat._42 = 0.50f; mat._43 = 0.00f; mat._44 = 1.00f;

After the matrix is created, it must be set by calling IDirect3DDevice9::SetTransform, as shown in the following code fragment.

g_pd3dDevice->SetTransform( D3DTS_TEXTURE0, &mat );

The D3DTS_TEXTURE0 flag tells Direct3D to apply the transformation to the texture located at texture stage 0. The next step that this sample takes is to set more texture stage state values to get the desired effect. That is done in the following code fragment.

g_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS,
                  D3DTTFF_COUNT2 );
g_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX,
                  D3DTSS_TCI_CAMERASPACEPOSITION );

The texture coordinates are set up, and now the scene is ready to be rendered. Notice that the coordinates are automatically created for the cylinder. This particular setup gives the effect of the texture being laid over the rendering screen after the geometric shapes have been rendered.

For more information about textures, see Direct3D Textures.

This tutorial has shown you how to use textures for surfaces. Tutorial 6: Using Meshes shows you how to use complex geometric shapes with meshes.


Tutorial 6: Using Meshes
Microsoft DirectX 9.0 SDK Update (October 2004)

Tutorial 6: Using Meshes

Complicated geometry is usually modeled using 3-D modeling software, after which the model is saved to a file. An example of this is the .x file format. Microsoft Direct3D uses meshes to load the objects from these files. Meshes are somewhat complicated, but D3DX contains functions that make using meshes easier. The Meshes sample project introduces the topic of meshes and shows how to load, render, and unload a mesh.

This tutorial shows how to load, render, and unload a mesh using the following steps.

Steps

  • Step 1: Loading a Mesh Object
  • Step 2: Rendering a Mesh Object
  • Step 3: Unloading a Mesh Object

The path of the Meshes sample project is: (SDK root)\Samples\C++\Direct3D\Tutorials\Tut06_Meshes

The sample code in the Meshes project is nearly identical to the sample code in the Lights project, except that the code in the Meshes project does not create a material or a light. The Using Meshes tutorial focuses only on the code unique to meshes and does not cover setting up Direct3D, handling Microsoft Windows messages, rendering, or shutting down. For information about these tasks, see Tutorial 1: Creating a Device.

This tutorial uses custom vertices and a vertex buffer to display geometry. For more information about selecting a custom vertex type and implementing a vertex buffer, see Tutorial 2: Rendering Vertices.

This tutorial makes use of matrices to transform geometry. For more information about matrices and transformations, see Tutorial 3: Using Matrices.

This tutorial uses textures to cover the surface of the mesh. For more information about loading and using textures, see Tutorial 5: Using Texture Maps.


Step 1: Loading a Mesh Object
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 1: Loading a Mesh Object

A Microsoft Direct3D application must first load a mesh before using it. The Meshes sample project loads the tiger mesh by calling InitGeometry, an application-defined function, after loading the required Direct3D objects.

A mesh needs a material buffer that will store all the materials and textures that will be used. The function starts by declaring a material buffer as shown in the following code fragment.

LPD3DXBUFFER pD3DXMtrlBuffer;

The following code fragment loads the mesh.

// Load the mesh from the specified file
if( FAILED( D3DXLoadMeshFromX( "Tiger.x", D3DXMESH_SYSTEMMEM,
            g_pd3dDevice, NULL, &pD3DXMtrlBuffer, NULL,
            &g_dwNumMaterials, &g_pMesh ) ) )
    {
    // If model is not in current folder, try parent folder
    if( FAILED( D3DXLoadMeshFromX( "..\\Tiger.x",
            D3DXMESH_SYSTEMMEM, g_pd3dDevice, NULL,
            &pD3DXMtrlBuffer, NULL, &g_dwNumMaterials,
            &g_pMesh ) ) )
        {
            MessageBox(NULL, "Could not find tiger.x",
                       "Meshes.exe", MB_OK);
            return E_FAIL;
        }
    }

The first parameter is a pointer to a string that tells the name of the Microsoft DirectX file to load. This sample loads the tiger mesh from Tiger.x.

The second parameter specifies how to create the mesh. The sample uses the D3DXMESH_SYSTEMMEM flag, which is equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM. Both of these flags put the index buffer and vertex buffer for the mesh in system memory.

The third parameter is a pointer to a device that will be used to render the mesh.

The fourth parameter is a pointer to an ID3DXBuffer object. This object will be filled with information about neighbors for each face. This information is not required for this sample, so this parameter is set to NULL.

The fifth parameter also takes a pointer to an ID3DXBuffer object. After this method is finished, this object will be filled with D3DXMATERIAL structures for the mesh.

The sixth parameter is a pointer to the number of D3DXMATERIAL structures placed into the ppMaterials array after the method returns.

The seventh parameter is the address of a pointer to a mesh object, representing the loaded mesh.

After loading the mesh object and material information, you need to extract the material properties and texture names from the material buffer.

The Meshes sample project does this by first getting the pointer to the material buffer. The following code fragment uses the ID3DXBuffer::GetBufferPointer method to get this pointer.

D3DXMATERIAL* d3dxMaterials = (D3DXMATERIAL*)pD3DXMtrlBuffer->GetBufferPointer();

The following code fragment creates new mesh and texture objects based on the total number of materials for the mesh.

g_pMeshMaterials = new D3DMATERIAL9[g_dwNumMaterials];
g_pMeshTextures  = new LPDIRECT3DTEXTURE9[g_dwNumMaterials];

For each material in the mesh the following steps occur.

The first step is to copy the material, as shown in the following code fragment.

g_pMeshMaterials[i] = d3dxMaterials[i].MatD3D;

The second step is to set the ambient color for the material, as shown in the following code fragment.

g_pMeshMaterials[i].Ambient = g_pMeshMaterials[i].Diffuse;

The final step is to create the texture for the material, as shown in the following code fragment.

// Create the texture.
if( FAILED( D3DXCreateTextureFromFile( g_pd3dDevice,
   d3dxMaterials[i].pTextureFilename, &g_pMeshTextures[i] ) ) )
    g_pMeshTextures[i] = NULL;
}

After loading each material, you are finished with the material buffer and need to release it by calling IUnknown::Release.

pD3DXMtrlBuffer->Release();

The mesh, along with the corresponding materials and textures are loaded. The mesh is ready to be rendered to the display, as described in Step 2: Rendering a Mesh Object.


Step 2: Rendering a Mesh Object
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 2: Rendering a Mesh Object

In step 1 the mesh was loaded and is now ready to be rendered. It is divided into a subset for each material that was loaded for the mesh. To render each subset, the mesh is rendered in a loop. The first step in the loop is to set the material for the subset, as shown in the following code fragment.

g_pd3dDevice->SetMaterial( &g_pMeshMaterials[i] );

The second step in the loop is to set the texture for the subset, as shown in the following code fragment.

g_pd3dDevice->SetTexture( 0, g_pMeshTextures[i] );

After setting the material and texture, the subset is drawn with the ID3DXBaseMesh::DrawSubset method, as shown in the following code fragment.

g_pMesh->DrawSubset( i );

The ID3DXBaseMesh::DrawSubset method takes a DWORD that specifies which subset of the mesh to draw. This sample uses a value that is incremented each time the loop runs.

After using a mesh, it is important to properly remove the mesh from memory, as described in Step 3: Unloading a Mesh Object.


Step 3: Unloading a Mesh Object
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 3: Unloading a Mesh Object

After any Microsoft DirectX program finishes, it needs to deallocate any DirectX objects that it used and invalidate the pointers to them. The mesh objects used in this sample also need to be deallocated. When it receives a WM_DESTROY message, the Meshes sample project calls Cleanup, an application-defined function, to handle this.

The following code fragment deletes the material list.

if(g_pMeshMaterials)
    delete[] g_pMeshMaterials;

The following code fragment deallocates each individual texture that was loaded and then deletes the texture list.

if(g_pMeshTextures)
{
    for(DWORD i = 0; i < g_dwNumMaterials; i++
    {
        if(g_pMeshTextures[i])
            g_pMeshTextures[i]->Release();
    }
delete[] g_pMeshTextures;

The following code fragment deallocates the mesh object.

Delete the mesh object
if(g_pMesh)
    g_pMesh->Release();

This tutorial has shown you how to load and render meshes. This is the last tutorial in this section.


HLSL Workshop
Microsoft DirectX 9.0 SDK Update (October 2004)

HLSL Workshop

The high-level shader language (HLSL) Workshop is a set of tutorials that make it easy to learn how to generate HLSL shaders.

HLSL Tutorials

These tutorials are .fx files designed to run in the EffectEdit Sample. The tutorials offer a step-by-step approach to learning how to use vertex, pixel, and texture shaders in HLSL to create the following functionality:

  • Goal 1: Hemispheric Lighting Tutorial
  • Goal 2: Vertex Animation Tutorial
  • Goal 3: Environment Mapping
  • Goal 4: Procedural Texture Tutorial

Launching The Shader Debugger

While running these tutorials, you may find it helpful to know how to launch the shader debugger to interactively debug your shaders. Here is one additional tutorial that will show you how to launch the debugger and start your debug session:

  • Goal 5: Shader Debugging Tutorial


Goal 1: Hemispheric Lighting Tutorial
Microsoft DirectX 9.0 SDK Update (October 2004)

Goal 1: Hemispheric Lighting Tutorial

In this lesson you'll be implementing the hemispheric lighting term of the lighting equation. Before starting on the solution, look at this page for an explanation of the theory (Hemispheric Lighting Explained) as you work through the tutorial. If you get stuck, refer to the Goal1_Solution.fx file inside the solutions directory for the suggested answer. Most of the steps can be implemented in many different ways, so don't worry if your code is different from the solution.

The hemispheric lighting goal is divided into three tasks:

  1. Use the occlusion term stored per vertex to modulate the hemisphere term.
  2. Calculate the hemisphere light value.
  3. Change the sky and ground colors.

Extra Credit: Make the skull translucent where the occlusion term is low (you'll need to set alpha blend states).

Setup

Preparation

Open Goal1.fx inside EffectEdit. If you have the software development kit (SDK) installed, the .fx file is located at:

(SDK root)\Samples\C++\Direct3D\Tutorials\HLSLWorkshop\

Description

The default render technique is Hemisphere, which uses only the hemispheric lighting term of the lighting equation. Since you'll be implementing hemispheric lighting in this lesson, this term is currently calculated using placeholder values; therefore, your render view should show a flat, dark, gray skull surface:

Task 1: Use the Occlusion Term Stored per Vertex to Modulate the Hemisphere Term

Preparation

Locate Goal 1A in the code and follow the instructions.

Description

The occlusion term is a weight that was calculated in a offline pass of the model that is the percentage of the hemisphere that is blocked by other parts of the model. In the term provided, a value of 0 means that the vertex is not occluded by any geometry (all light will be received) versus a value of 1 which means that the vertex is completely blocked from light.

Tip

Multiplying by the result of 1 - Occ will darken the hemisphere light in relation to how much this vertex is affected by a hemisphere light.

Solution

Hemi *= (1 - Occ);

After modulating by the occlusion term, the model appears shadowed in occluded areas:

Task 2: Calculate the Hemisphere Light Value

Preparation

Locate Goal 1B in the code and follow the instructions.

Description

A hemisphere light is made up of two colors, sky and ground, that are interpolated between based on the normal; that is, areas with normals pointing towards the sky are "sky"-colored, and areas pointed towards the "ground" are more "ground"-colored.

Tip

An easy way to implement a hemisphere light is to linearly interpolate between the sky color and the ground color based on the angle between the normal and sky direction. The angle can easily be calculated by doing a dot product between the normal and sky direction. This results in a -1 to 1 value that, when remapped to 0 to 1, is perfect for linearly interpolating between the two colors.

Solution

float LerpFactor = (dot(Normal, DirToSky) + 1) / 2;

After taking into account the angle between sky and ground colors, the model reflects the white sky color on areas pointed upward and the black ground color on areas pointed downward:

Task 3: Change the Sky and Ground Colors

Preparation

Locate Goal 1C in the code and follow the instructions.

Description

Experiment with a few values for sky and ground. The hemisphere light is used to simulate an environment that is dominated by one color at the north and south poles of a "sphere" surrounding the object. One hemisphere is the sky color and the other is the ground color. An example of this is blue for the sky and green for the ground. This will simulate basic radiosity of a scene for an object sitting on a green surface like grass with a blue sky overhead. Note that the default color values are stored at the top of the file.

Solution

float4 GroundColor              = { 0.1f, 0.4f, 0.0f, 1.0f };    // ground
float4 SkyColor                 = { 0.5f, 0.5f, 0.9f, 1.0f };    // sky

Notice how the new sky and ground colors affect the model:

Because the selected technique Hemisphere only uses the hemispheric term of the lighting equation, the model shading is very dark. Try scrolling through the other techniques to see how the different components of the lighting equation affect the model; notice that all the techniques which start with Hemisphere include the hemispheric lighting term you implemented. The following image, rendered using the Hemisphere technique, shows the model under complete illumination:

That completes Goal 1. Feel free to try the extra credit problem or move on to Goal 2 when ready.


Hemispheric Lighting Explained
Microsoft DirectX 9.0 SDK Update (October 2004)

Hemispheric Lighting Explained

Hemispheric lighting divides scene lighting into two spheres: an upper hemisphere and a lower hemisphere. Each vertex uses its normal to determine whether it is more visible to the upper or the lower hemisphere. Once the visibility is determined, per-vertex lighting is interpolated from the two hemisphere colors to produce more realistic object lighting. See Goal 1: Hemispheric Lighting Tutorial.

Why Use Hemispheric Lighting?

Compare the two objects below. The difference between the lighting on the two objects is that the one on the right has a hemispheric component.

In the image on the right, notice the color difference between the top and the bottom of the object. The top is brighter with a bluish tint because it is more influenced by the sky color. The bottom is darker with a greenish tint because it is more influnced by the ground color.

How Does It Work?

Here is an example of a vertex "p" that is influenced by two hemispheres. This diagram shows two hemispheres: the top one is blue, and the bottom one is green. The polygon in the center of the sphere is the one we are lighting. The angle theta is the angle between the vertex normal and the up vector (a vector pointed (0,1,0)).

Hemispheric lighting takes the sky and ground color and blends them together based on the value of theta like this:

The resulting hemisperic component can then be combined with other per-vertex components (such as ambient, diffuse, or specular components).

This example also includes an occlusion term that identifies which vertices are occluded (or blocked) from the hemispheric lighting. A value of 1 means that the vertex is completely occluded from the light; a value of 0 means the vertex is not blocked from the light. In this example, the occlusion term is a per-vertex property, and was supplied in the per-vertex model data.

An easy way to implement a hemisphere light is to interpolate between the sky color and the ground color based on the angle between the normal and sky direction. The angle can easily be calculated by doing a dot product between the normal and sky direction. This results in a -1 to 1 value that, when remapped to 0 to 1, is perfect for interpolating between the two colors.


Goal 2: Vertex Animation Tutorial
Microsoft DirectX 9.0 SDK Update (October 2004)

Goal 2: Vertex Animation Tutorial

In this lesson you'll be using a programmable vertex shader to animate the vertices of the model. Animating vertices using the fixed function pipeline would require either updating the vertex positions stored in the vertex buffer, or changing tranformation matrices for each vertex. Because smooth animation would require making these changes for every frame, both of these approaches are prohibitively slow for most applications; if, however, the animation is performed in a programmable vertex shader, the animation can be performed during the transformation process at minimal expense. As before, the given solutions are just suggested implementations, and your answers may vary.

The vertex animation goal contains a single task: Use the Time variable to modify geometry.

Extra Credit: Use sin(float3) to create a rippling skull.

Setup

Preparation

Open Goal2.fx inside EffectEdit. If you have the software development kit (SDK) installed, the .fx file is located at:

(SDK root)\Samples\C++\Direct3D\Tutorials\HLSLWorkshop\

Description

The default render technique is HemisphereDiffuseSpecular, which uses the full hemispheric lighting equation developed in the previous lesson:

Task 1: Use the Time Variable to Modify Geometry

Preparation

Locate Goal 2A in the code and follow the instructions.

Description

EffectEdit will put the current time in seconds in any float variable with the TIME semantic like the Time variable declared above. Offset is just the vertex's model space coordinate, and can be used to distinguish different vertices so that any motion generated at one vertex is not the same as all vertices (that is, it can be used to offset the sine evaluation so that each point is at a different point in the sine equation).

Tip

One good method of animating things is using sine or cosine. This can be used to generate waves or other interesting interference patterns.

A couple of high-level shader language (HLSL) features will be very useful for this task. First, most of the intrinsic functions are defined for both scalar and vector types (that is, if you pass a vector to the sine function it will return a vector containing the sine of each vector component). Second, a single component scalar type will automatically be promotion cast to multiple component types when the function returns.

Note You probably do not want to add or subtract too large a value per vertex. Multiplying the result of sine or cosine by 0.1 is a good start for the skull model.

Solution

In particular, this task doesn't have any right or wrong implementations. Here are a few values which give interesting results:

return sin(Time);
return sin(Time * Offset) * 0.1;
return sin(Time + Offset) * 0.1;
return float3( sin(Time + Offset.x), sin(3*Time + Offset.x), 0) * 0.5;

return (Normal*(sin(Time)+1))*0.5;
// For this solution, you'll need to pass "Normal" into the function

The computed value is added to the vertex's transformed position inside the vertex shader, resulting in a periodic animation:

This completes Goal 2. Feel free to try the extra credit problem or move on to Goal 3 when ready.


Goal 3: Environment Mapping
Microsoft DirectX 9.0 SDK Update (October 2004)

Goal 3: Environment Mapping

In this lesson you'll be implementing environment mapping to simulate ray-traced reflections. Before starting on the solution, look over the Environment Mapping Explained for an explanation of the theory, and refer back as needed as you work through the code. If you get stuck, refer to the Goal3_Solution.fx file inside the solutions directory for the suggested answer. Most of the steps can be implemented in many different ways, so don't worry if your code is different from the solution.

The environment mapping goal is divided into four tasks:

  1. Create a texture and a sampler for the environment map.
  2. Do a cubemap texture lookup.
  3. Calculate the reflection vector.
  4. Adjust reflectivity.

Extra Credit:

  • Add a fresnel term.
  • Change the environment map to per-pixel instead of per-vertex.

Setup

Preparation

Open Goal3.fx inside EffectEdit. If you have the software development kit (SDK) installed, the .fx file is located at:

(SDK root)\Samples\C++\Direct3D\Tutorials\HLSLWorkshop\

Description

The default render technique is HemisphereDiffuseSpecular, which uses the full hemispheric lighting equation developed in lesson 1; however, the pixel shader has been modified to use the environment map in place of the diffuse color. Since you'll be adding support for environment mapping in this lesson, the placeholder code evaluates to black, leaving only subtle white highlights from the specular contribution:

Note that the animation calculation added in the previous lesson has been commented out to make things easier.

Task 1: Create a Texture and a Sampler for the Environment Map

Preparation

Locate Goal 3A in the code and follow the instructions.

Description

Texture variables are the .fx file representation of the texture interfaces. Texture parameters also have annotations that specify what type of texture and where the texture should come from. This information is read by the application, which then creates a texture using that information and sets the interface back into the effect for use. In this case, the sample looks for type and name annotations in order to correctly load the texture.

The sampler variable is the high-level shader language (HLSL) .fx representation of how to do lookups. The texture intrinsics require a sampler, because a sample encompasses the concept of the texture and the method in which to do the lookup (that is, types of filtering, and so on). In .fx files, samplers can also have sampler_state blocks that specify the state to be loaded into the device whenever that sampler is used.

Note These blocks are ignored if D3DXCompileShader or Effect Command Line Compile is used.
Tip

Create a texture variable named EnvironmentMap. Also create two string annotations:

  1. "type" with the value "CUBE"
  2. "name" with the value "lobbycube.dds" (the environment map to use)

Create a samplerCUBE variable called Environment. Add a sampler_state block that sets the following state:

  1. Texture to (EnvironmentMap)
  2. MipFilter to LINEAR;
  3. MinFilter to LINEAR;
  4. MagFilter to LINEAR;

Solution

texture EnvironmentMap
<
    string type = "CUBE";
    string name = "lobbycube.dds";
>;

samplerCUBE EnvironmentSampler = sampler_state
{
    Texture = (EnvironmentMap);
    MipFilter = LINEAR;
    MinFilter = LINEAR;
    MagFilter = LINEAR;
};

Task 2: Do a Cubemap Texture Lookup

Preparation

Locate Goal 3B in the code and follow the instructions.

Description

The cubemap contains the view of the environment from the object's perspective along the six positive and negative axes. By sampling this texture and applying the result to the model's surface, the model will appear to reflect the environment.

Tip

Use the provided CubeTexcoord and the texCUBE intrinsic to do the texture lookup.

Solution

return texCUBE(EnvironmentSampler, CubeTexcoord);

The environment can now be seen reflected from the object:

Note that the reflection does not take the viewer's position into account (as you'll notice if you move the camera). This will be fixed in the next step.

Task 3: Calculate the Reflection Vector

Preparation

Locate Goal 3C in the code and follow the instructions.

Description

The reflection vector is used to find the ray of light leaving a particular point in the environment, bouncing off the surface of the object, and entering the camera.

Tip

A good way to start is just to return the Normal until you make sure the cube map lookup is working. Next you can use the reflect intrinsic to reflect the ViewToPos vector around the Normal vector. Both the ViewToPos and Normal vectors should be normalized before calculating reflection (which has already been done for you in the vertex shader).

Solution

return reflect(ViewToPos, Normal);

The environment mapping appears much more accurate with the correct reflection vector:

Note that the environment mapping is still not quite right—upon close inspection you will notice that the surface reflection appears slightly warped when moving the model around. This is a result of calculating the cubemap sample coordinates per-vertex and interpolating the result across the fragment. Instead, the normal and view vector could be interpolated across the fragment and used to calculate environment mapping per-pixel. For this workshop, per-vertex approximation is good enough, and per-pixel environment mapping is left to the user as an extra credit exercise. As a general rule, moving calculations from the vertex shader to the pixel shader gives greater accuracy at the expense of performance.

Task 4: Adjust Reflectivity

Preparation

Locate Goal 3D in the code and follow the instructions.

Description

Most shiny objects are not completely reflective. Some percentage of the final color is a reflection of the environment and the remaining contribution comes from the material's diffuse properties. Factor in the diffuse color to decrease reflectivity.

Tip

Linearly interpolate between the diffuse color calculated within the vertex shader (In.Diff) and the environment map color sampled from the cubemap. A good reflectivity value for this scene is 0.25

Solution

OutColor = lerp(In.Diff, Environment, 0.25);

The environment now appears as a subtle reflection on top of the diffuse color:

Now that you have everything working, you might want to uncomment the animation calculation and to see how the reflections give added visual cues to the animated deformations.

This completes Goal 3. Feel free to try the extra credit problems or move on to Goal 4 when ready.


Environment Mapping Explained
Microsoft DirectX 9.0 SDK Update (October 2004)

Environment Mapping Explained

This sample uses high-level shader language (HLSL) and effects to apply a cubic environment map using a pixel shader. A vertex shader is also used trivially to transform the vertex data to projection space. The shaders and the helper functions are written in HLSL. An effect encapsulates the sampler state, the texture state, and a technique that invokes the vertex and pixel shaders.

How an Environment Map Works

An environment map, sometimes referred to as a reflection map, is a method for applying environment reflections to a curved surface. A cubic environment map, is a texture map that contains six 2-D textures, one for each direction from a point (see Cubic Environment Mapping). By applying an environment map, an object can be made to appear like it has a highly smooth surface (such as an object made out of metal or glass). This example illustrates the difference between two objects: one object lit with normal diffuse lighting, and one that has a environment map applied.

Figure 1. Standard ambient/diffuse lighting | Figure 2. With an environment map and identical lighting

The skull in Figure 1 appears to have a flat finish; there are no reflections from the environment and no glossy or specular highlights. In contrast, Figure 2 contains an environment map that makes the skull appear to have a highly reflective, glossy surface.

How This Example Works

An environment map relies on a reflection vector to sample the texture. The reflection vector leaves the point being textured at an angle form the normal that is equivalent to the angle between the view vector to the point. This is shown below.

Generating the Reflection Vector

The reflection vector will be used as a lookup (in other words, as texture coordinates) for the texture sampling. The vertex shader calculates the reflection vector with the help of the CalcReflectionVector HLSL function as shown here.

// Generate a reflection vector to lookup in a reflection cube-map
Out.CubeTexcoord = CalcReflectionVector(EyeToVertex, Normal);

The helper function uses the reflect HLSL intrinsic function to generate a reflection vector from the view vector and the vertex normal. The last thing the helper function does is normalize the resulting vector by calling the normalize intrinsic function.

float3 CalcReflectionVector(float3 ViewToPos, float3 Normal)
{
    return normalize(reflect(ViewToPos, Normal));
}

You may want to test your normals to see that they are correct, by simply returning the normal with this function. This will produce a texture image on your object that is incorrect, but it will help verify the normal data. Once this works, add the reflect and normalize intrinsic functions to create correct environmental mapping.

Environment Map Lookup

The environment map lookup is a cubic texture sample. The texture sample requires the input texture coordinate (passed into the helper function by CubeTexcoord), and the sampler that we declared earlier. The sampling is done with the help of the HLSL intrinsic function texCUBE, which takes the 3-D coordinates, and returns a 4-D color value.

float4 CubeMapLookup(float3 CubeTexcoord)
{
    return 0.25 * texCUBE(EnvironmentSampler, CubeTexcoord);
}

Lastly, once the texture is sampled and a color is returned, this will be added to the existing pixel color in the pixel shader. The 0.25 factor is an arbitrary number chose to scale down the influence of the sampled color. This is done so that the appearance of the surface is not completely reflective.

Technique

In the render loop, an application sets the current technique ID3DXEffect::SetTechnique. This technique contians a single pass which calls a vs_2_0 vertex shader and a ps_2_0 pixel shader.

technique TEnvironmentMap
{
    pass P0
    {
        VertexShader = compile vs_2_0 VS();
        PixelShader = compile ps_2_0 PS();
    }
}

Pixel Shader

The pixel shader is also very simple, thanks to the CubeMapLookup helper function. The pixel shader is passed in the output of the vertex shader, and then returns a single color, marked by the COLOR semantic just after the functions argument list.

The first line of the pixel shader sums the diffuse and specular color to make the final color. The second line adds an additional color that is returned by the CubeMapLookup helper function; this is the cubic environment map sample that results from looking up the texture coordinates that were calculated by the vertex shader.

struct VS_OUTPUT
{
    float4 Pos  : POSITION;
    float4 Diff : COLOR0;
    float4 Spec : COLOR1;
    float3 VolTexcoord : TEXCOORD0;
    float3 CubeTexcoord : TEXCOORD1;
};

float4 PS ( VS_OUTPUT In) : COLOR
{
    float4 OutColor;

    OutColor = In.Diff + In.Spec;

    OutColor += CubeMapLookup(In.CubeTexcoord);

    return OutColor;
}


Goal 4: Procedural Texture Tutorial
Microsoft DirectX 9.0 SDK Update (October 2004)

Goal 4: Procedural Texture Tutorial

In this lesson you'll be using the high-level shader language (HLSL) to generate a volume texture procedurally. If you get stuck, refer to the Goal4_Solution.fx file inside the solutions directory for the suggested answer. Most of the steps can be implemented in many different ways, so don't worry if your code is different from the solution.

The procedural texture goal is divided into two tasks:

  1. Do a volume texture lookup.
  2. Generate a procedural texture.

Extra Credit: Use if statements to create a volume checkerboard texture.

Setup

Preparation

Open Goal4.fx inside EffectEdit. If you have the software development kit (SDK) installed, the .fx file is located at:

(SDKRoot)\Samples\C++\Direct3D\Tutorials\HLSLWorkshop\

Description

The default render technique is HemisphereDiffuseSpecular, which uses the full hemispheric lighting equation developed in Goal 1: Hemispheric Lighting Tutorial. In addition, the model shows the environment mapping developed in the previous lesson (Goal 3: Environment Mapping):

Note that the animation calculation added in lesson 2 has been commented out to make things easier.

Task 1: Do a volume texture lookup.

Preparation

Locate Goal 4A in the code and follow the instructions.

Description

Simply sample from the volume texture at the provided coordinate. Assume for now that the texture has already been procedurally generated, although this will actually be done during the next step.

Tip

Use the provided VolTexcoord and the tex3D intrinsic function to do the texture lookup. Unlike the cubemap lookup (from lesson 2), it is easier to scale down the values of the volume map in the function that generates the volume instead of doing it here, so no scale should be required.

Solution

return tex3D(VolumeTexture, VolTexcoord);

The volume texture currently contains a solid yellow color, which yields the following render output when the sampled texture color is added to the diffuse color:

Task 2: Generate a procedural texture.

Preparation

Locate Goal 4B in the code and follow the instructions.

Description

EffectEdit Sample uses the D3DXFillVolumeTextureTX function to execute this function for every texel in the volume texture. The height, width, depth, and function name are all described in the texture definition. The input is the position of the texel in the texture. In this case it is a three-dimensional coordinate that ranges from 0 to 1 on all axes (x = width, y = height, z = depth). The return value is the color stored at the texel position specified by the input position.

Tip

The noise intrinsic is a good start for a procedural texture. Even by itself it can give a nice grainy texture. One thing to remember about the noise function is that it is a good idea to scale up the access to it, because the range of noise on inputs of 0 to 1 is not as interesting as that of 0 to 500. You get a more random-looking set of values then. The noise function outputs values between 0 and 1, so you might want to scale the return value down to limit the effect.

Solution

return noise(Pos * 500) * 0.5f;

The speckles added by the procedural texture give the appearance of metal shavings within a glossy paint layer:

This completes Goal 4 of the shader workshop. The tutorials are designed to make it easy to experiment with the code. Don't be afraid to experiment with different values for noise to see if you can create other interesting procedural textures.


Goal 5: Shader Debugging Tutorial
Microsoft DirectX 9.0 SDK Update (October 2004)

Goal 5: Shader Debugging Tutorial

This tutorial will launch the debugger and show you how to debug a vertex shader.

If you are having trouble getting the debugger to work, see Getting Started Debugging Shaders to understand the tools you must have installed. Once you have completed the tutorial, many of the debugger features are listed in the DirectX Extensions for Visual Studio .NET.

The shader debugger tutorial is divided into several tasks:

  1. Task 1: Launching Visual Studio .NET.
  2. Task 2: Opening a Visual Studio .NET project.
  3. Task 3: Building a Debug Project
  4. Task 4: Starting the debugger.
  5. Task 5: Setting a breakpoint.
  6. Task 6: Viewing the disassembly code.
  7. Task 7: Setting conditional breakpoints.

Task 1: Launching Visual Studio .NET.

Launch Microsoft Visual Studio .NET (either version 2002 or 2003).

If neither of these versions is available, you need to install Visual Studio .NET. Go to Setting Up The Tools for install instructions.

Task 2: Opening a Visual Studio .NET project.

  1. From the File menu, click Open Solution.
  2. In the file open dialog box, open the file BasicHLSL which is installed by the software development kit (SDK) into the following default location:

    C:\DX90SDK\Samples\C++\Direct3D\BasicHLSL\BasicHLSL

    If you cannot find BasicHLSL you may need to install the latest version of the Microsoft DirectX SDK. For instructions, see Install DirectX 9.

Task 3: Building a Debug Project

  1. From the Build menu, click Configuration Manager to make sure Debug is selected.
  2. Remove the first comments in the following two lines:
    //#define DEBUG_VS   // Uncomment this line to debug vertex shaders
//#define DEBUG_PS   // Uncomment this line to debug pixel shaders

    The lines should now look like this:

    #define DEBUG_VS   // Uncomment this line to debug vertex shaders
#define DEBUG_PS   // Uncomment this line to debug pixel shaders

    This sets the correct shader flags so that the shaders can be debugged.

  3. From the Build menu, click Build Solution to build the debug project.

Task 4: Starting the debugger.

From the Debug menu, click Direct3D then Start With Direct3D Debugging to launch the debugger.

Visual Studio .NET window with Direct3D Debugging selected

This is also available with shortcut keys CTRL+ALT+F5.

Task 5: Setting a breakpoint.

A breakpoint can be set in the code window.

  1. From the File menu, click Open.
  2. Select the BasicHLSL.fx file.
  3. Once the file has opened, click on a line of code (line 92 in this example) where you want to break and press the F9 key.

    This is what you will see when the debugger breaks. The breakpoint is marked by the filled circle to the left of line 92.

    You can now step through one line of code at a time by hitting F10. You can check the contents of any variable or register by placing the mouse over the variable and waiting for the value to pop up.

See Viewing Register Contents or Viewing Device State for more options for viewing state.

Task 6: Viewing the disassembly code.

Disassembly code is a combination of the high-level shader language (HLSL) shader statements, and the assembly instructions generated by the HLSL compiler. From the Debug menu, click Windows then Disassembly to open the disassembly window.

With the shader paused at the breakpoint, you can hold the mouse over individual registers to see the contents, or even drag and drop a register into the watch window to look at the contents.

Task 7: Setting conditional breakpoints.

Once a breakpoint is set, you may need a mechanism for stopping at this breakpoint only if a certain condition is met; for example, after some number of vertices have been processed, or only if a certain normal vector value is seen. This is called a conditional breakpoint because the break only occurs on this condition. Here is an example of how to set one.

  1. First right click on the breakpoint and select Properties.
  2. When the Breakpoint Properties dialog box opens, click the Condition... button.

  3. In the text box on the Breakpoint Conditions dialog box, enter an expression that evaluates to a Boolean result.

The conditional expression in this example is (Output.Diffuse.a == 1), which means that the debugger will only break on line 92 when the alpha component of the diffuse color is 1. (Since we set alpha to this value, this will always cause a break.) Conditional breakpoints offer a powerful method for fine tuning breakpoints, so that you can look at a particular subset of conditions while debugging.

See DirectX Extensions for Visual Studio .NET for more options for setting breakpoints and for debugging shader and Microsoft Direct3D code simultaneously.


PIX Tutorials
Microsoft DirectX 9.0 SDK Update (October 2004)

PIX Tutorials

The following tutorials demonstrate how to use features of the PIX tool.

  • Gathering Data in the PIX Basic View
  • Comparing Image Quality with PIX


Gathering Data in the PIX Basic View
Microsoft DirectX 9.0 SDK Update (October 2004)

Gathering Data in the PIX Basic View

This tutorial demonstrates how to configure and experiment file to gather PIX data. The tutorial is divided into the following tasks:

  • Setup
  • Duration
  • Step 1: Start PIX
  • Step 2: Specify the Program Path
  • Step 3: Specify the Information You Want to Gather
  • Step 4: Gather Data

Setup

The PIX tool is located at:

(SDK root)\Utilities\PIX\PIXWin.exe

The Microsoft DirectX 9.0 software development kit (SDK) contains many sample applications that can be tested with PIX. Executable sample applications are located at:

(SDK root)\Samples\C++\Direct3D\Bin

Duration

This tutorial will typically take 10-15 minutes.

Step 1: Start PIX

Launch PIX from either the DirectX 9.0 Utilities folder at the path given above, or from the Microsoft Windows Start menu. From Start, select All Programs, then Microsoft DirectX 9.0 SDK Update, then Utilities, and then PIX for Windows.

From the PIX File menu select New Experiment, or Open to open an existing experiment file.

After you select a new experiment, a Basic View window will open in which you can specify the options PIX will use to profile an application. The Basic View is designed to make it easy for you to run PIX for the first time.

Step 2: Specify the Program Path

Enter into the program path the location of the application you want to profile. As an example, this tutorial uses the BasicHLSL Sample. The default project selected on startup is whatever the previous program path was.

Step 3: Specify the Information You Want to Gather

One of three choices for experiment settings can be made in the Basic View:

  • Compute statistics for each frame, using one or more counters, or sets of counters, to count the number of application programming interface (API) calls made when the application is running. To select this option, click the first radio button and then click the down arrow and select the counters to use to collect data.
  • Create a log of all calls to the Microsoft Direct3D and D3DX API in a given frame number. If you click on the second radio button and then enter a frame number in the text box, the log will contain all the API calls made during that frame.
  • Save to a file a replayable stream of Direct3D API calls. This stream of API calls can be used by PIX to re-run this experiment. Click the third radio button and then either click the browse button and locate a directory where you want to save the file, or type the file's directory path in the text entry box.

In the figure above, the selection has been made to log all Direct3D and D3DX calls in frame 1000.

Step 4: Gather Data

Start your PIX experiment by clicking Start Experiment in the Basic View. If logging of frame 1000 has been selected, PIX will run the application up to frame 999, log the calls made during frame 1000, save the log to a file, and end the experiment.

When you exit the application or click Terminate in the PIX (Helper DLL) window, the .PIXRun log file will automatically be displayed.


Comparing Image Quality with PIX
Microsoft DirectX 9.0 SDK Update (October 2004)

Comparing Image Quality with PIX

This tutorial demonstrates how to use the PIX tool to generate screen shots of rendered frames, and how to compare per-pixel rendering results for frames rendered on hardware abstraction layer (HAL) and reference device types (see Device Types). The tutorial is divided into the following tasks:

  • Setup
  • Duration
  • Step 1: Create an Experiment to Grab a Screen Shot
  • Step 2: Generate a Screen Shot on a HAL Device
  • Step 3: Generate a Screen Shot on a Reference Device
  • Step 4: Compare the Screen Shots

Setup

The PIX tool is located at:

(SDK root)\Utilities\PIX\PIXWin.exe

The Microsoft DirectX 9.0 software development kit (SDK) contains many sample applications that can be tested with PIX. Executable sample applications are located at:

(SDK root)\Samples\C++\Direct3D\Bin

Duration

This tutorial will typically take 10-15 minutes.

Step 1: Create an Experiment to Grab a Screen Shot

Create an experiment for taking a screen capture at frame 1000 of the ShadowVolume Sample. This will require that you modify the experiment's default trigger and default action.

Launch PIX (see Step 1: Start PIX). In the PIX File menu select New Experiment. Click More Options to go into the Advanced View. In the Trigger Type selection box, select Frame. You should see the following view:

PIX Advanced View with frame trigger selection

The Advanced View (unlike the Basic View discussed in Gathering Data in the PIX Basic View) is designed to let you enter triggers and actions directly. The following procedure will allow you to capture a screen shot capture at frame 1000:

  1. Make sure the T (for Trigger) is highlighted, and then enter "1000" in the Frame box.
  2. Click the A (for Action) so that it is highlighted.
  3. In the Action Type selection box, select Grab Screenshot.
  4. In the Path to screenshot box, either click the Browse button and locate a directory where you want to save the file, or type the file's directory path in the text entry box.

PIX Advanced View with screen shot selection

Step 2: Generate a Screen Shot on a HAL Device

Now that you have your experiment set up, click Start Experiment. The following screen shot is generated:

Screen shot of ShadowVolume sample frame 1000, on a HAL device

The only supported PIX screen capture file format is .png, but the Texture File Converter Tool may be used to convert a .png file to other common formats.

Step 3: Generate a Screen Shot on a Reference Device

Now rerun the experiment with a reference device. To do this, you will need to generate another action that switches the device to a reference device.

  1. First delete the existing trigger. Select the trigger, and, on the experiment toolbar, click the X button. Alternately, right-click the existing trigger and select Delete this Trigger.
  2. Add a new trigger action by selecting Add Trigger from the Edit menu, or click the T button on the experiment toolbar.
  3. In the Trigger Type box, select Frame. The numeral 1 should appear in the Frame box immediately below.
  4. Click the action icon titled Unspecified Action, and then in Action Type, select Modify D3D Device. In Device modification, select Force REF.
  5. From the Edit menu, select Insert Trigger, or click the T button on the experiment toolbar.
  6. In this second Trigger and Action, set up a screenshot at frame 1000 just as you did in Step 1: Create an Experiment to Grab a Screen Shot.

The experiment view should now look like this:

PIX Advanced View with triggers set at frames 1 and 1000

Once again, run the experiment by clicking Start Experiment. This will generate the following screen shot using the reference device:

Screen shot of ShadowVolume sample frame 1000, on a reference device

Step 4: Compare the Screen Shots

You can view a per-pixel comparison of the screen shots to see how they differ between HAL and reference device types. Because the differences in the images are subtle, you can use the file comparison feature of PIX.

From the File menu, select Compare Images. The following user interface is displayed:

PIX Image Compare utility

  1. Click Source 1.
  2. Click the "Open Folder" button ( Open Folder button) and browse to the first file to use in the comparison.
  3. Click Source 2 and browse to the second file to use in the comparison.
  4. Click Compare.

The resulting display shows the RGB differences between the corresponding pixels in each of the two original images:

PIX Image Compare display of HAL vs. reference screen shots at frame 1000


Samples
Microsoft DirectX 9.0 SDK Update (October 2004)

Samples

The samples in this section show how to use Microsoft Direct3D and D3DX in a C/C++ application. Once you have mastered the tutorials, you are ready to jump into the samples. Some of these samples demonstrate the latest features of Microsoft DirectX 9.0. Other samples demonstrate existing functionality that is fundamental to using Direct3D. All of the samples are built on top of the sample framework, which you can learn more about by going to The Sample Framework and Sample Framework Reference.

Note Follow the instructions for Sample Code contained in the license agreements within the following folder:

(SDK root)\Documentation\License Agreements

Samples

These samples demonstrate the newest techniques incorporated into DirectX. Although DirectX samples include Microsoft Visual C++ project workspace files, you might need to verify other settings in your development environment to ensure that the samples compile properly.

  • BasicHLSL Sample
  • Blobs Sample
  • CompiledEffect Sample
  • CustomUI Sample
  • DepthOfField Sample
  • EffectEdit Sample
  • EffectParam Sample
  • EmptyProject Sample
  • EnhancedMesh Sample
  • FragmentLinker Sample
  • HDRCubeMap Sample
  • HDRFormats Sample
  • HDRLighting Sample
  • HLSLwithoutEffects Sample
  • Instancing Sample
  • MeshFromObj Sample
  • MultiAnimation Sample
  • OptimizedMesh Sample
  • PixelMotionBlur Sample
  • PostProcess Sample
  • ProgressiveMesh Sample
  • PRTPerVertex Sample
  • ShadowMap Sample
  • ShadowVolume Sample
  • SkinnedMesh Sample
  • StateManager Sample
  • Text3D Sample


BasicHLSL Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

BasicHLSL Sample

This sample shows a simple example of the high-level shader language (HLSL) using an effect interface.

Path

Source: | (SDK root)\Samples\C++\Direct3D\BasicHLSL
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\BasicHLSL.exe

Sample Overview

This sample simply loads a mesh, creates an effect from a file, and then uses the effect to render the mesh. The effect that is used is a simple vertex shader that animates the vertices based on time.

How the Sample Works

First the sample loads the geometry with D3DXLoadMeshFromX and calls D3DXComputeNormals to create mesh normals if there aren't any. It then calls OptimizeInplace() to optimize the mesh for the vertex cache, then loads the textures using D3DXCreateTextureFromFile. Next, the sample calls D3DXCreateEffectFromFile to compile the effect text file to a ID3DXEffect* interface called m_pEffect.

Note that the D3DXCreateEffectFromFile takes flags which are needed to debug shaders with the Microsoft Visual Studio .NET shader debugger. Debugging vertex shaders requires either a reference device or software vertex processing. Debugging a pixel shader requires a reference device.

The D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flags set various source code debugging options. Setting these flags will cause slower rendering since the shaders will be unoptimized and forced into software. All that is needed to turn these flags on with the sample code is to uncomment the #define DEBUG_VS or #define DEBUG_PS line from near the top of the file. This will also force the device into software processing by adding some code to CMyD3DApplication::ConfirmDevices. See DirectX Extensions for Visual Studio .NET for more information about debugging shaders.

In CMyD3DApplication::Render, the sample sets the technique to use with a call to ID3DXEffect::SetTechnique and passes a D3DXHANDLE to the technique that was obtained upon initialization with a call to ID3DXBaseEffect::GetTechniqueByName. It is possible to pass a string name instead of a handle, but using a handle improves performance since this high frequency call does not have to spend time on a string compare.

The sample then sets variables used by the technique such as the World*View*Projection matrix and the time variable with various ID3DXEffect::Set* calls. To render, the sample calls ID3DXEffect::Begin which returns the number of passes required by the technique, then loops through each pass calling m_pEffect->Pass(iPass) and rendering the mesh with ID3DXBaseMesh::DrawSubset. When all the passes are done, it calls ID3DXEffect::End.


Blobs Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

Blobs Sample

This sample mimics a metaball effect in screen space using a pixel shader. True metaball techniques deform surfaces according to pushing or pulling modifiers, and are commonly used to model liquid effects like the merging of water droplets. Metaball effects can be computationally expensive, however, so this sample implements a 3-D metaball effect in 2-D image space with a pixel shader.

Path

Source: | (SDK root)\Samples\C++\Direct3D\Blobs
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\Blobs.exe

Sample Overview

Metaballs (also called Blinn blobs after James Blinn who formulated the technique) are included with most modeling software as an easy way to create smooth surfaces from a series of enclosed volumes (called blobs) which merge together; the apparent flow between blobs makes the technique particularly well suited for particle systems which model liquids.

The underlying technique is based on isosurfaces, which are 3-D equations that define a closed volume. For instance, x2 + y2 + z2 = 1 defines a sphere of radius 1 centered at the origin. This idea can be extended to arbitrary 3-D functions. That is, an isosurface is defined by the set of all points along a continuous function which are equal to an arbitrary constant value. Individual metaballs are often implemented as spheres defined by Gaussian distributions where the highest value exists at the sphere's center and all values above an arbitrary threshold are defined to be inside the sphere. Subtracting the threshold from the Gaussian height gives a surface height of zero at the blob edge. Since the surface is completely defined according to this threshold, the values of overlapping spheres can be added to produce a new surface. Figure 1 shows the smooth curve which results from the addition of two Gaussian curves.

Figure 1: Addition of Gaussian curves produces smooth blending

For a true metaball effect, these calculations would be made in 3-D space. Instead, this sample performs the computation in 2-D screen space, which gives a nice visual effect requiring few computations. However, one limitation you may notice is that accuracy is lost when blobs in the background merge with blobs near the camera as they align along the view vector.

How the Sample Works

The individual blobs are described according to world-space position, size, and color. Before each frame is rendered, the blob positions are animated in FrameMove and then FillBlobVB projects each blob into screen-space and fills the vertex buffer with corresponding billboard quads. The vertex format of these billboards is shown below:

struct VS_OUTPUT
{
    float4 vPosition : POSITION;    // Screen-space position of the vertex
    float2 tCurr     : TEXCOORD0;   // Texture coordinates for Gaussian sample
    float2 tBack     : TEXCOORD1;   // Texture coordinates of vertex position on render target
    float2 sInfo     : TEXCOORD2;   // Z-offset and blob size
    float3 vColor    : TEXCOORD3;   // Blob color
};

The coordinates stored in tCurr are used to sample a 2-D Gaussian texture which defines the sphere. The coordinates stored in tBack are used to sample data from previously-rendered blobs, and could also be used to blend against a background texture. These pre-transformed vertices are handed directly to the BlobBlenderPS pixel shader:

PS_OUTPUT BlobBlenderPS( VS_OUTPUT Input )
{
    PS_OUTPUT Output;
    float4 weight;

    // Get the new blob weight
    DoLerp( Input.tCurr, weight );

    // Get the old data
    float4 oldsurfdata = tex2D( SurfaceBufferSampler, Input.tBack );
    float4 oldmatdata  = tex2D( MatrixBufferSampler, Input.tBack );

    // Generate new surface data
    float4 newsurfdata = float4((Input.tCurr.x-0.5) * Input.sInfo.y,
                                (Input.tCurr.y-0.5) * Input.sInfo.y,
                                0,
                                1);
    newsurfdata *= weight.r;

    // Generate new material properties
    float4 newmatdata = float4(Input.vColor.r,
                               Input.vColor.g,
                               Input.vColor.b,
                               0);
    newmatdata *= weight.r;

    // Additive blending
    Output.vColor[0] = newsurfdata + oldsurfdata;
    Output.vColor[1] = newmatdata + oldmatdata;

    return Output;
}

The DoLerp helper function performs a bilinear filtered texture sample since bilinear filtering of floating-point textures is typically not implemented by the graphics driver. Each blob billboard is rendered to a set of temporary textures, one to store accumulated color data and one to store accumulated surface normal data:

Figure 2: Surface normal buffer Figure 3: Color buffer

The blended normal and color data are used by the BlobLightPS pixel shader for a final lighting pass which samples into an environment map based on the averaged surface normal:

float4 BlobLightPS( VS_OUTPUT Input ) : COLOR
{
    static const float aaval = THRESHOLD * 0.07f;

    float4 blobdata = tex2D( SourceBlobSampler, Input.tCurr);
    float4 color = tex2D( MatrixBufferSampler, Input.tCurr);

    color /= blobdata.w;

    float3 surfacept = float3(blobdata.x/blobdata.w,
                              blobdata.y/blobdata.w,
                              blobdata.w-THRESHOLD);
    float3 thenorm = normalize(-surfacept);
    thenorm.z = -thenorm.z;

    float4 Output;
    Output.rgb = color.rgb + texCUBE( EnvMapSampler, thenorm );
    Output.rgb *= saturate ((blobdata.a - THRESHOLD)/aaval);
    Output.a=1;

    return Output;
}

Which yields the final composite image:


CompiledEffect Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

CompiledEffect Sample

This sample shows how an ID3DXEffect object can be compiled when the project is built and loaded directly as a binary file at run time.

Path

Source: | (SDK root)\Samples\C++\Direct3D\CompiledEffect
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\CompiledEffect.exe

Overview

Large-scale projects may contain dozens or even hundreds of shader and effect files. Compiling these files at run time can cause a noticeable delay during initialization, and this delay is incurred each and every time the project is run. In spite of this, it is beneficial to compile at run time when developing or debugging effect files as this allows more debugging flexibility.

Once development and/or debugging of these shaders are completed, these files can be compiled as part of your project build process. Since these files will only need to be compiled when changes are made, no additional build time is spent on effect files which have already been debugged and compiled.

The process illustrated in this sample is identical, whether compiling a complete effect object or individual shaders. All that would change would be the shader profile passed to the compiler on the command line.

How the Sample Works

The code is virtually identical to the HLSLwithoutEffects Sample except for a couple important differences:

  • The call to D3DXCreateEffectFromFile is passed the filename of the compiled effect CompiledEffect.fxo instead of the filename of the effect source CompiledEffect.fx.
  • No debugging flags are passed to D3DXCreateEffectFromFile. Instead, flags are passed to the effect compiler to enable shader debugging. The choice of compiler flags depends on the Microsoft Visual Studio .NET build configuration chosen.

The program used to compile shaders at build time is fxc. This command-line utility ships with the software development kit (SDK), and wraps the ID3DXEffectCompiler calls (which are called to compile the shader). You could create your own shader compiler fairly easily using the ID3DXEffectCompiler, but fxc should be flexible enough for most needs. The commands used to build release and debug versions of a typical .fx file are:

Release: | fxc /Tfx_2_0 /FoMyEffect.fxo MyEffect.fx
Debug: | fxc /Od /Zi /Tfx_2_0 /FoMyEffect.fxo MyEffect.fx

Run fxc without any arguments for usage information.

For more information on fxc, see Effect Command Line Compile.

Build Environment Configuration

Here are the steps taken to configure the build environment. These steps should be performed for every effect file you want to be compiled as part of the build process:

  1. Open the CompiledEffect Sample project inside Visual Studio .NET.
  2. From within the Solution Explorer window, right click on CompiledEffect.fx and select Properties from the context menu.
  3. Select Configuration Properties->Custom Build Step to view the custom build step directives. The specific compile command issued depends on the project build configuration, as you can verify by scrolling through the Configuration combo box.


CustomUI Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

CustomUI Sample

This sample is a simple demonstration of the UI subsystem implemented by the Microsoft Direct3D sample framework. The sample framework provides code and infrastructure common to most Microsoft DirectX applications. One area of the framework is user interface support. The sample framework contains commonly used control objects, such as buttons and check boxes, that both windowed and full screen Direct3D applications can use to implement their user interfaces.

Path

Source: | (SDK root)\Samples\C++\Direct3D\CustomUI
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\CustomUI.exe

How the Sample Works

This sample demonstrates how an application that uses the Direct3D sample framework can take advantage of the framework's user interface support. The sample framework supports the following control types:

Control type | Class that implements it
Statics | CDXUTStatic
Buttons | CDXUTButton
Radio buttons | CDXUTRadioButton
Check boxes | CDXUTCheckBox
Combo boxes | CDXUTComboBox
Sliders | CDXUTSlider
Edit boxes | CDXUTEditBox
Edit boxes with IME capability | CDXUTIMEEditBox

All of the sample framework controls work similarly to Windows controls. They are implemented entirely from scratch and do not use HWND or any Windows control underneath. They are also rendered with Direct3D, and therefore can be used by both windowed and full screen Direct3D applications.

The CDXUTIMEEditBox is an edit box with IME (Input Method Editor) functionality. When entering text with CDXUTIMEEditBox, the user can switch input language to one of the East Asian languages supported (Japanese, Korean, Simplified Chinese, and Traditional Chinese). When typing, CDXUTIMEEditBox renders IME windows with Direct3D, and it also supresses the default IME windows so that they will not corrupt the application window in full screen mode.

This sample starts by defining two CDXUTDialog objects: g_HUD and g_SampleUI. A CDXUTDialog serves as a container that encapsulates one or more controls. It sits between the application and the controls, so that the application can pass messages and rendering calls to CDXUTDialog, and CDXUTDialog will ensure that all of its controls receive the messages and get rendered properly. The controls themselves are designed to be used with a CDXUTDialog, not stand-alone. Applications are not limited to one CDXUTDialog object. They can use more at once, as this sample does.

The first thing the the sample has to do to initialize the CDXUTDialog objects is set the event callback function with the SetCallback method. As the user interacts with the UI controls, the controls can notify the sample about important events, so that it can respond accordingly. At this time the sample also initializes additional fonts that it will need. This is done with the SetFont method.

The next step that the sample has to do is create the controls it needs. This is achieved by calling the CDXUTDialog's AddXXX methods, such as AddButton. In the sample, g_HUD contains 4 buttons that provide standard functionalities that Direct3D samples have: view whitepaper, toggle between full screen and windowed mode, toggle between HAL and REF, and change 3D device settings. g_SampleUI contains the rest of the controls, which are sample-specific. After a control is added, its appearance can be modified. This is demonstrated in the sample as it modifies the appearance of the static controls as well as the combo box and IME-capable edit box.

Next, in OnResetDevice, are a number of calls to the CDXUTDialog's and controls' SetSize and SetLocation methods. This is because when the user resizes the application window, some dialogs and controls need to be resized and repositioned as well. It is worth noting that the CDXUTDialog's location is relative to the application window, while a control's location is relative to the CDXUTDialog it belongs.

To render the user interface, the sample calls the OnRender method of the two CDXUTDialog objects in its OnFrameRender function. CDXUTDialog will render the controls it contains in the correct order.

The final step required to make the UI work is passing messages to the controls. This lets them receive keyboard and mouse events from the user. In MsgProc, the sample calls CDXUTDialog's MsgProc method to pass down the messages. It is very important that if CDXUTDialog's MsgProc returns true indicating that the message has been handled, the sample sets *pbNoFurtherProcessing to true and returns immediately. Failure to do so will cause a message to be processed more than once, and this can cause undesirable behavior for certain Input Method Editor (IME) messages, such as double windows.

Event Callback

Certain events happen as the user interacts with the UI controls, such as checking or unchecking a check box, selecting a new item in a combo box, selecting a new item in a radio button group, etc. The application may be interested in such events, and it can be notified with the CDXUTDialog event callback mechanism. In the sample, a callback function, OnGUIEvent, is defined and passed as the parameter to the CDXUTDialog::SetCallback method. As a result, this function will get called whenever the user performs an interesting action with a UI control. The actions that can trigger a callback are:

  • Clicking a button (CDXUTButton)
  • Selecting a new item in a combo box (CDXUTComboBox)
  • Selecting a new item in a radio button group (CDXUTRadioButton)
  • Changing the check state of a check box (CDXUTCheckBox)
  • Changing the value of a slider (CDXUTSlider)
  • Pressing Enter in an edit box (CDXUTEditBox and CDXUTIMEEditBox)
  • In the callback, the type of event, the ID of the control that fired the event, and the control object are available to the application. The sample responds to the callback by retrieving content of the firing control and displaying it on screen.


DepthOfField Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

DepthOfField Sample

This sample shows several techniques for creating a depth-of-field effect in which objects are only in focus at a given distance from the camera and out of focus at other distances. Rendering objects out of focus adds realism to the scene. The methods it shows are reasonably cheap to perform on most hardware, and the depth of field post processing can easily be combined with other post process techniques such as image-based motion blur or high dynamic range (HDR) lighting.

Path

Source: | (SDK root)\Samples\C++\Direct3D\DepthOfField
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\DepthOfField.exe

Background

In CMyD3DApplication::InitDeviceObjects it loads the geometry with D3DXLoadMeshFromX and calls D3DXComputeNormals to create mesh normals if there aren't any. It then calls ID3DXMesh::OptimizeInplace to optimize the mesh for the vertex cache. It then loads the textures using D3DXCreateTextureFromFile.

CMyD3DApplication::RestoreDeviceObjects does the following:

  • Sets up the camera class. The camera class encapsulates handling mouse and keyboard input and updating the view matrix accordingly.
  • Calls D3DXCreateTexture to create a D3DUSAGE_RENDERTARGET A8R8G8B8 texture with the same height & width as the back buffer. If that fails, it tries again but without the D3DUSAGE_RENDERTARGET flag.
  • Creates a ID3DXRenderToSurface with D3DXCreateRenderToSurface to help render to the texture on cards that don't support render targets.
  • Loads the D3DX effect file into a ID3DXEffect xxx, and caches the D3DXHANDLE to all the parameters that it will set every frame.
  • Initializes effect parameters that don't change every frame, such as the material properties and render target texture, using ID3DXBaseEffect::SetVector and ID3DXBaseEffect::SetTexture.
  • Finds the first valid technique in the effect for the current device.
  • Creates a quad of vertices to be used in the post-processing pass. The quad has 6 sets of texture coords defined. Each set of texture coordinates is slightly shifted so when they are used in post process the pixel shader effect will be a blur. Note that the entire set of texture coordinates aren't used in every technique. How this quad is used will be explained below in more detail.
  • Scales the effect's kernel TwelveKernelBase from pixel space (where 1.0 means 1 pixel) to texture coordinate space and stores the result into a separate array labeled TwelveKernel.

In CMyD3DApplication::FrameMove it simply calls FrameMove() on the camera class so it can move the view matrix according the user input over time.

CMyD3DApplication::Render essentially does 2 things:

  1. It first renders the scene into a render target while it simultaneously calculates the blur factor and stores this in the alpha channel of the render target. An alpha value of 0 means that specific pixel is not blurry while an alpha value of 1 means that specific pixel is blurry.
  2. It then uses this render target with depth information stored in the alpha channel and renders a full screen quad to execute a pixel shader for each pixel in the final surface.

In more detail, the first part of CMyD3DApplication::Render uses the technique WorldWithBlurFactor which uses the vs_1_1 vertex shader called WorldVertexShader. This vertex shader transforms vertex position into screen space, performs a simple N dot L lighting equation, copies texture coordinates, and computes the blur factor based on the depth. The blur factor is calculated with these equations:

fBlurFactor = dot(float4(vViewPosition, 1.0), vFocalPlane)*fHyperfocalDistance;
Output.Diffuse.a = fBlurFactor*fBlurFactor;

This equation calculates the distances from a point to a plane and scales the result by some factor. The hyperfocal distance is a factor that is the distance from clear to blurry. The blur factor is then squared and capped at 0.75f so that the center pixel is always weighted in the blurred image, thus reducing artifacts.

The technique WorldWithBlurFactor then uses a ps_1_1 pixel shader called WorldPixelShader which simply modulates the diffuse vertex color with the mesh's texture color. This could be done with texture blending if desired.

The second part of CMyD3DApplication::Render is where the blur actually happens. It uses one of five techniques to show off essentially 2 different pixel shader blur techniques.

The techniques UsePS20ThirteenLookups and UsePS20SevenLookups both use the ps_2_0 pixel shader called DepthOfFieldManySamples (but compile it using different parameters). The pixel shader is fairly simple: for a fixed number of samples it uses an array of values, called TwelveKernel, to offset the original UV texture coords and calls tex2D() with this new UV on a texture which is the render target created above. The kernel is defined to be two hexagons: one a single pixel out and the other two pixels out with close to "equal" spacing between the points in order to get the best blurring. For each sample it keeps a running sum of the color with this equation:

Blurred += lerp(Original.rgb, Current.rgb, saturate(Original.a*Current.a));

After all the samples have been taken, it returns this color divided by number of samples.

The other techniques UsePS20SixTexcoords, UsePS11FourTexcoordsNoRings, and UsePS11FourTexcoordsWithRings all are similar. Unlike the above, they don't use a kernel to offset the texture coordinates but instead use separate sets of texture coords that are precomputed. These texture coordinates are created in the application function called CMyD3DApplication::SetupQuad and each set is offset to create a blur when used in a very similar way as done above in DepthOfFieldManySamples. The advantage to this method is that it can be done with ps_1_1 hardware.

The difference between UsePS11FourTexcoordsNoRings, and UsePS11FourTexcoordsWithRings is that UsePS11FourTexcoordsWithRings linearly interpolates between the center pixel's RGB and the 3 jitter pixel's RGB based on the alpha value (the blur factor) of the center pixel. If one of the jitter pixels is not blurry while the center pixel is blurry, then the jitter pixel is incorrectly averaged in. However, UsePS11FourTexcoordsNoRings linearly interpolates between the center pixel's RGB and the 3 jitter pixel's RGB based on the value of center pixel's alpha multiplied by the jitter pixel alpha. Since 0 means no blur, this means that if one of the jitter pixels is not blurry while the center pixel is blurry then 0 * 1 = 0 so that the jitter pixel is not averaged in, causing a better result without artifacts.

For example, here is an original unblurred scene:

By pressing I, the sample will visually show you the blur factor of the scene. White means that pixel is not blurry (alpha=0.0f), and black means that pixel is blurry (alpha=1.0f).

Here's what the final scene looks like:


EffectEdit Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

EffectEdit Sample

The EffectEdit Sample implements a tool that allows easy experimentation with effects. Effects provide a convenient way to package multiple techniques for rendering an object, including render states, vertex shaders, pixel shaders, and multiple passes. Using the sample, you can load effect files, edit them, and see an object rendered with the effect. Changes to the effect are reflected immediately on the rendered object. To see the effect reference section, go to Effect Reference.

Path

Source: | (SDK root)\Samples\C++\Direct3D\EffectEdit
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\EffectEdit.exe

User's Guide

The user interface is a window divided into four panes. You can press CTRL+TAB to change the keyboard focus between these panes.

The Effect file source code pane shows the source code for the current effect and provides text editing capability.

The Effect compilation results pane shows the results of compiling the current effect. You can double-click on errors to jump to the offending line in the source code pane. If there are no errors, the results pane will say "Compilation successful!" and you should see the rendered object.

The Rendered scene pane shows the rendered object, using the current effect. You can drag the left mouse button to rotate the object, the right mouse button to move the object, and click the scroll wheel to zoom the object.

The Rendering options pane lets you change various aspects of how the object is rendered. The Reset Camera button moves the camera back to the default position and orientation.

Programming Notes

The sample is a Microsoft Foundation Classes (MFC) application, using the single-document model. CEffectDoc is the class representing the document, which is mainly just the text contents of the effect. CMainFrame manages the display of the four different views used on this document and the splitter windows that control the panes containing the views. CTextView is the text editor, CErrorsView is the compilation results, COptionsView is the rendering options, and CRenderView is the rendered output. Only the last class really uses Microsoft Direct3D and Direct3D code. CRenderView is derived from both CFormView and CD3DApplication, so it can use familiar methods like FrameMove, InitDeviceObjects, etc.

This sample uses the sample framework code that is shared with other samples in the Microsoft DirectX software development kit (SDK). All common headers and source code can be found at:

(SDK root)\Samples\C++\Common

The sample provides a convenient application for shader development using effects. The application supports allows you to load an effect into an interactive edit environment for developing shader code. Sample code can be cut and pasted into a text edit window, which can be compiled on the fly. The render results can be automatically updated.

The sample takes advantage of semantics and annotations to decide what to do with certain types of parameters. This default effect uses the fixed function pipeline to blend the diffuse lighting with a solid, textured object. The model is in the file Tiger.x. To adjust the view in the render window, use the mouse to move or rotate the object or to move the light direction.

The sample renders four panes (listed here in clockwise order):

  • Code pane (upper left)
  • Render pane (upper right)
  • Rendering options pane (lower right)
  • Compile results pane (lower left)

The Code Pane

The code pane displays the effect code. This includes the effect global variables, the shader functions and techniques and passes. You can use the scroll bars to navigate up and down in the code, or use the arrow keys to navigate. The nice thing about this pane is that you can enter new high-level shader language (HLSL) code here and it will be automatically recompiled and re-rendered for you. This makes it a handy test bed for code development.

The Render Pane

The render pane displays the rendered output. Like all the SDK samples, EffectEdit can display the frame rate. Use the arrow keys to rotate the object and view it from different camera angles. Click on the arrow that represents the direction of the light to move the light and watch the rendered result change.

The Rendering Options Pane

The rendering options pane gives you control over what gets rendered. The options include choosing which techniques and passes will be rendered, setting the rendering mode (wireframe, solid, or textured), and enabling or disabling automatic compiling and rendering.

The Compile Results Pane

The compile results pane displays the results of compiling whatever is in the code pane. When stepping through the debugger, any error messages are displayed in this pane. The error messages also provide the line number of the compile failures and may describe the shader validation rule that was violated. Often, the validation restrictions are displayed in this pane. If you double click on the line number of a line that fails to compile, the debugger will open to that line in the shader code.

Getting an Effect to Run in EffectEdit

The sample implements a tool that allows easy experimentation with effects. Effects provide a convenient way to package multiple techniques for rendering an object, including render states, vertex shaders, pixel shaders, and multiple passes. Using the sample, you can load effect files, edit them, and see an object rendered with the effect. Changes to the effect are reflected immediately on the rendered object.

The sample is set up to take advantage of these parameter combinations:

  • A parameter with a semantic attached to it
  • A parameter with an annotation
  • A string parameter with a particular name
  • An integer parameter with a particular name

Here are the semantics that are recognized by the sample:

If the parameter has this semantic attached to it: | EffectEdit will expect the parameter to contain:
WORLD | World matrix
VIEW | View matrix
PROJECTION | Projection matrix
WORLDVIEW | World-view matrix
VIEWPROJECTION | View-projection matrix
WORLDVIEWPROJECTION | World-view-projection matrix

The Glow.fx effect uses the WORLDVIEW semantic to identify the composite world-view matrix:

float4x3 WorldView  : WORLDVIEW;

Here are the annotations that are recognized by the sample:

If the parameter contains this annotation: | EffectEdit will use the parameter for:
NAME | A texture file to be loaded
FUNCTION | A procedural texture file to be loaded
TARGET | A procedural texture target (the default is "tx_1_0").
WIDTH | The texture width
HEIGHT | The texture height

Here are the string names that are recognized by the sample:

If the effect contains a string named: | EffectEdit will use the string as:
BIMG | A background image for the scene
XFile | The .x file containing the object

The default effect specifies the tiger.x file:

string XFile = "tiger.x";   // model

Here is an integer type that is recognized by the sample:

If the effect contains a string named: | EffectEdit will use the integer value as:
BCLR | The background color of the scene

The default effect that uses BCLR to specify the background color is:

int    BCLR  = 0xff202080;  // background

A hexadecimal color is read in ARGB order, so this represents a color with full intensity alpha, whose blue component is four times the value of the red and green components. To see the color in EffectEdit Sample, comment out the statement that defines the background image and the background will be cleared to this shade of blue.


EffectParam Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

EffectParam Sample

The EffectParam Sample demonstrates two D3DX effect system features: parameter blocks and parameter sharing (see Sharing Effect Parameters and Use Parameter Blocks to Manage Effect Parameters). Parameter blocks group multiple Setxxx application programming interface (API) calls and associate them with an effect handle. An application can then use the parameter block to make all those state changes with a single API call. Parameter sharing synchronizes parameters in multiple effects; each time an application updates a parameter in one effect, that parameter is updated in all the other shared effects.

Path

Source: | (SDK root)\Samples\C++\Direct3D\EffectParam
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\EffectParam.exe

How the Sample Works

This sample renders a scene that consists of seven mesh objects. The meshes are arranged in a circular ring. The user can rotate either the front mesh, or the ring to bring another mesh to the front. Each mesh has one or more materials, and each mesh can specify the effect file to render each material with.

A mesh is encapsulated by the CEffectMesh class, which wraps the ID3DXMesh interface. The class is mainly a helper class for setting up mesh materials. When loading a mesh, D3DX returns an array of materials used by the mesh. Each material has several attributes that define the appearance of the material, such as diffuse color, specular color, texture name, and the effect file used to render the material. D3DX does not set up materials automatically when loading meshes. It is up to the application to do so. CEffectMesh takes care of this task when an instance is created.

Each material is represented as a CMeshMaterial. This class contains three data members representing the needed data when rendering this material: the texture object, the effect object, and a handle for setting the effect's parameters.

To create a mesh, CEffectMesh::Create is called with the name of the mesh file. The sample calls D3DXLoadMeshFromX to create an ID3DXMesh interface and material information. Then, for each material, it checks for the associated effect instance. The effect instance (D3DXEFFECTINSTANCE) specifies the effect file name for rendering the material, optional effect parameters and their default values. If an effect instance exists for this material, then an ID3DXEffect interface is created from the effect file. Next, the sample creates a parameter block that contains the effect parameters. This is done by first calling ID3DXEffect::BeginParameterBlock. This call indicates to the effect object that it should record all subsequent set calls, until ID3DXEffect::EndParameterBlock is called. When ID3DXEffect::EndParameterBlock is called, the effect returns a D3DXHANDLE for the parameter block. From this point on, when the parameter block is applied (with ID3DXEffect::ApplyParameterBlock), the effect looks at the parameters inside the block, and sets the values for each of the parameters. The result is as if the application called this series of set methods. For instance, if an effect has two float4 parameters called Diffuse and Specular, a parameter block can be created to include these two parameters like this:

D3DXVECTOR4 vDiffuse;
D3DXVECTOR4 vSpecular;
D3DXHANDLE  hBlock;

// Initialize vDiffuse and vSpecular

pEffect->BeginParameterBlock();
pEffect->SetVector( "Diffuse", &vDiffuse );
pEffect->SetVector( "Specular", &vSpecular );
hBlock = pEffect->EndParameterBlock();

After this code is run, hBlock contains two parameters, Diffuse and Specular, and the recorded value of vDiffuse and vSpecular. Now, whenever the application does this:

// Apply the parameter block

pEffect->ApplyParameterBlock(hBlock);

The result is equivalent to the following, assuming vDiffuse and vSpecular still have the correct values:

pEffect->SetVector( "Diffuse", &vDiffuse );
pEffect->SetVector( "Specular", &vSpecular );

After the parameter block is created, the sample creates a new CMeshMaterial object to encapsulate the material. An effect may have more than one parameter, but CMeshMaterial only uses one D3DXHANDLE because parameter blocks allow the sample to use a single handle to represent multiple parameters.

For materials without an effect instance, a default effect is used for rendering those materials, and a parameter block is created for the standard Microsoft Direct3D material attributes; that is, ambient, diffuse, specular, emissive, and specular power.

Parameter Sharing

When loading an effect, an application can optionally supply an ID3DXEffectPool pointer. An application passes NULL for the pool to indicate that there is no parameter sharing between effects. When a valid ID3DXEffectPool is passed, parameters declared with shared usage are shared between multiple effects. When the value of the parameter changes in one effect, every effect that shares this parameter will also see the change. To the application, it is as if there is only one instance of the parameter, used by all effects. For instance, if two effects are created with the same ID3DXEffectPool, and they both have a shared parameter named WorldViewProjection, then updating WorldViewProjection on one effect changes its value as seen by the other effect.

In the EffectParam Sample, the parameters that are declared with the shared usage are the world, view, and projection matrices (or combinations of them). Because all materials of a mesh use the same transformation, it makes sense to share them among the effects so that the sample only needs to set each matrix once per mesh rendered, instead of once per material. The sample allows the user to enable or disable parameter sharing to see its impact on performance. During rendering of a mesh, the sample always sets the transformation matrices once in the default effect. When the share option is enabled, all effects of the mesh see the correct matrices and are able to transform vertices appropriately. This means that all parts of the mesh are rendered regardless of their materials (Figure 1). When the option is set to disable, the updated matrices are only seen by the default effect. All other effects never see up-to-date values in the matrices, unless they are set by other effects. Because the sample does not do this, only materials rendered by the default effect are visible (Figure 2).

Figure 1. Parameter sharing enabled. All materials are rendered correctly.

Figure 2. Parameter sharing disabled. Only materials rendered by the default effect are correctly transformed.


EmptyProject Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

EmptyProject Sample

Starting point for new Microsoft Direct3D applications.

Path

Source: | (SDK root)\Samples\C++\Direct3D\EmptyProject
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\EmptyProject.exe

Sample Overview

This sample is a bare-bones Direct3D application provided as a convenient starting point for your own project.

How the Sample Works

This sample uses the sample framework to initialize and run a basic Direct3D application.


EnhancedMesh Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

EnhancedMesh Sample

The EnhancedMesh Sample demonstrates mesh tessellation in Microsoft Direct3D. Mesh tessellation subdivides mesh triangles. This produces a mesh with finer geometry details which can produce better lighting results even with per-vertex lighting. Mesh tessellation is often used to implement a level of detail (LOD) technique where meshes closer to the viewer are rendered with more details, and meshes further away are rendered with less detail.

Path

Source: | (SDK root)\Samples\C++\Direct3D\Meshes\EnhancedMesh
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\EnhancedMesh.exe

How the Sample Works

The sample can run in one of two modes: hardware tessellation or software tessellation. The user can set the tessellation level to different values and see how the mesh changes in reaction to the level adjustment.

When running in hardware tessellation mode, the sample tessellates the mesh by calling IDirect3DDevice9::SetNPatchMode which sets the number of tessellation segments into which the device will tessellate each mesh segment. For instance, specifying 3.0 will cause each original segment in the input mesh to be tessellated into three segments. This tessellation happens in real-time, after the mesh draw calls in the render loop.

When running in software tessellation mode, the sample does not rely on the hardware to do on-the-fly tessellation. Therefore, the sample must process the mesh and obtain the desired detail level before rendering it. The code achieves this by calling D3DXTessellateNPatches which takes an input mesh and a segment count, and then outputs another mesh that represents the tessellated version of the input mesh. The sample can then render this tessellated mesh using any standard mechanism.


FragmentLinker Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

FragmentLinker Sample

This sample shows how to use the ID3DXFragmentLinker interface. Shader source code can be split into a series of shader fragments, which are compiled separately and linked together to form a complete shader. This linking stage is very efficient, making it suitable for run-time use. In this way a Microsoft Direct3D application can custom-build an appropriate shader for the current graphics card.

Path

Source: | (SDK root)\Samples\C++\Direct3D\FragmentLinker
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\FragmentLinker.exe

How the Sample Works

Large-scale Direct3D applications commonly employ a large set of redundant shaders covering every supported fallback case for a given technique (often generated by uniform parameters) from which the appropriate shader for the current graphics hardware is selected at run time. This approach can result in a large amount of compiled shaders being included with the application, only a small fraction of which are ever used on a given machine. Using shader fragments, the desired shader for the current graphics card can be built at run time.

This sample links together one of two vertex shader fragments which handle projection (vertex animated or static) and one of two vertex shader fragments which handle vertex lighting (diffuse enabled or ambient only). These fragments are compiled once during initialization and are then linked together at run time.

There are only a few steps that need to be followed when using shader fragments in your application:

  1. Create the ID3DXFragmentLinker interface using the D3DXCreateFragmentLinker function.
  2. Load and compile the shader fragments by calling D3DXGatherFragments, D3DXGatherFragmentsFromFile, or D3DXGatherFragmentsFromResource.
  3. Add the compiled fragments to the linker's internal list with a call to ID3DXFragmentLinker::AddFragments. This list defines the complete set of all fragments, from which a subset will be linked to create a shader.
  4. Retrieve handles of the fragments you want linked through calls to ID3DXFragmentLinker::GetFragmentHandleByIndex or ID3DXFragmentLinker::GetFragmentHandleByName.
  5. Link together a subset of the added fragments by passing fragment handles to the ID3DXFragmentLinker::LinkVertexShader, ID3DXFragmentLinker::LinkPixelShader, or ID3DXFragmentLinker::LinkShader method. These methods create an interface to a compiled shader which can be used for rendering.

The sample application performs the above steps upon device creation within the OnCreateDevice function:

// Create the fragment linker interface
V_RETURN( D3DXCreateFragmentLinker( pd3dDevice, 0, &g_pFragmentLinker ) );

// Compile the fragments to a buffer. The fragments must be linked together to form
// a shader before they can be used for rendering.
V_RETURN( D3DXGatherFragmentsFromFile( L"FragmentLinker.fx", NULL, NULL, g_dwShaderFlags, &g_pCompiledFragments, NULL ) );

// Build the list of compiled fragments
V_RETURN( g_pFragmentLinker->AddFragments( (DWORD*)g_pCompiledFragments->GetBufferPointer() ) );

// Store the fragment handles
CDXUTComboBox* pComboBox = NULL;
pComboBox = g_SampleUI.GetComboBox( IDC_LIGHTING );
pComboBox->RemoveAllItems();
pComboBox->AddItem( L"Ambient", (void*) g_pFragmentLinker->GetFragmentHandleByName( "AmbientFragment" ) );
pComboBox->AddItem( L"Ambient & Diffuse", (void*) g_pFragmentLinker->GetFragmentHandleByName( "AmbientDiffuseFragment" ) );

pComboBox = g_SampleUI.GetComboBox( IDC_ANIMATION );
pComboBox->RemoveAllItems();
pComboBox->AddItem( L"On", (void*) g_pFragmentLinker->GetFragmentHandleByName( "ProjectionFragment_Animated" ) );
pComboBox->AddItem( L"Off", (void*) g_pFragmentLinker->GetFragmentHandleByName( "ProjectionFragment_Static" ) );

// Link the desired fragments to create the vertex shader
V_RETURN( LinkVertexShader() );

The final linking step is performed within the LinkVertexShader helper function. In addition to being called upon device creation, this function is also called whenever the user changes a fragment combobox selection. The currently selected fragments are retrieved from the user interface controls, the shader is quickly linked, and the new shader is passed to the effect file:

HRESULT LinkVertexShader()
{
    HRESULT hr;

    const int NUM_FRAGMENTS = 2;
    D3DXHANDLE aHandles[ NUM_FRAGMENTS ] = {0};
    aHandles[ 0 ] = (D3DXHANDLE) g_SampleUI.GetComboBox( IDC_ANIMATION )->GetSelectedData();
    aHandles[ 1 ] = (D3DXHANDLE) g_SampleUI.GetComboBox( IDC_LIGHTING )->GetSelectedData();

    // Link the fragments together to form a shader
    IDirect3DVertexShader9* pVertexShader = NULL;
    V_RETURN( g_pFragmentLinker->LinkVertexShader( "vs_1_1", g_dwShaderFlags, aHandles, NUM_FRAGMENTS, &pVertexShader, NULL ) );

    // Associate this vertex shader with the effect object
    V_RETURN( g_pEffect->SetVertexShader( "MyVertexShader", pVertexShader ) );

    SAFE_RELEASE( pVertexShader );
    return S_OK;
}

Resources

The syntax for writing shader fragments is detailed in Writing Shader Fragments and in the Fragment Declaration Syntax.

More in-depth coverage of the process behind compiling and linking shader fragments is found in Building And Rendering Fragments.


HDRCubeMap Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

HDRCubeMap Sample

This sample demonstrates cubic environment-mapping with floating-point textures and high dynamic range lighting. In Microsoft DirectX 9.0, floating-point formats have become available for textures. These formats can store color values higher than 1.0, which can make lighting effects more realistic on the environment-mapped mesh when the material absorbs part of the light.

Note that not all cards support all features for the environment-mapping and high dynamic range lighting techniques.

Path

Source: | (SDK root)\Samples\C++\Direct3D\HDRCubeMap
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\HDRCubeMap.exe

Sample Overview

HDRCubeMap Sample shows off two rendering techniques: cubic environment-mapping and high dynamic range lighting. Cubic environment-mapping is a technique in which the environment surrounding a 3-D object are rendered into a cube texture map, so that the object can use the cube map to achieve complex lighting effects without memory intensive lighting calculations. High dynamic range (HDR) lighting is a technique to render highly realistic lighting effects by using floating-point textures and high-intensity lights. The floating-point texture formats are introduced in DirectX 9.0. Unlike traditional textures in integer format, floating-point textures are capable of storing a wide range of color values. Because color values in floating-point textures don't get clamped to [0, 1], much like lights in real-world, these textures can be used to achieve greater realism.

The scene that HDRCubeMap Sample renders is an environment-mapped mesh, along with several other objects making up the environment around the mesh. The mesh has a reflectivity setting adjustable from 0 to 1, where 0 means the mesh absorbs light completely, and 1 means it absorbs no light and reflects all. The lights used in the scene consist of four point lights, whose intensity is adjustable by the user.

Implementation

HDRCubeMap Sample follows the DirectX sample framework architecture. A CMyD3DApplication class, derived from CD3DApplication, does most of the work in the sample.

The scene that the sample renders consists of these objects:

  • A room mesh. This includes the walls, floor, and ceiling.
  • Four small sphere meshes representing light sources.
  • A mesh in the center of the room with the environment map applied to it.
  • Two bi-plane meshes. These orbit around the environment-mapped mesh and are reflected on the environment map. They give the visual cue that the environment map is dynamic, and changes as the surrounding environment changes.

When the sample loads, it creates two cubic textures, one in A8R8G8B8 format and the other in A16B16G16R16F format. When rendering, the sample uses one of these to construct an environment map based on the user's choice. This is done to show the visual difference between integer and floating-point textures when used with high dynamic range lighting. A stencil surface with a size equal to the size of a cube texture face is also created at this time. This stencil surface will be used as the stencil buffer when the sample renders the scene onto the cube texture. The sample also creates an effect object that contains all of the shaders and techniques needed for rendering the scene. The camera used in the sample is a CModelViewerCamera. This camera always looks at the origin, where the environment-mapped mesh is. The user can move the camera position around the mesh and rotate the mesh with mouse control. The camera object computes the view and projection matrices for rendering, as well as the world matrix for the environment-mapped mesh.

The Rendering Code

The rendering of the sample happens in three functions: RenderSceneIntoCubeMap, Render, and RenderScene, using vertex and pixel shaders.

RenderScene is the function that does the actual work of rendering the scene onto the current render target. This is called both to render the scene onto the cube texture and onto the device backbuffer. It takes three parameters: a view matrix, a projection matrix, and a flag indicating whether it should render the environment-mapped mesh. The flag is needed because the environment-mapped mesh is not drawn when constructing the environment map. The rest of the function is straight-forward. It first updates the effect object with the latest transformation matrices, as well as the light position in view space. Then, it renders every mesh object in the scene by using an appropriate technique for each one.

RenderSceneIntoCubeMap's job is rendering the entire scene (minus the environment-mapped mesh) onto the cube texture. First, it saves the current render target and stencil buffer, and sets the stencil surface for the cube texture as the device stencil buffer. Next, the function iterates through the six faces of the cube texture. For each face, it sets the appropriate face surface as the render target. Then, it computes the view matrix to use for that particular face, with the camera at the origin looking out in the direction of the cube face. It then calls RenderScene with bRenderEnvMappedMesh set to false, passing along the computed view matrix and a special projection matrix. This projection matrix has a 90 degree field of view and an aspect ratio of 1, since the render target is a square. After this process is complete for all six faces, the function restores the old render target and stencil buffer. The environment map is now fully constructed for the frame.

Render is the top level rendering function called once per frame by the sample framework. It first calls FrameMove for the camera object, so that the matrices managed by the camera can be updated. Next, it calls RenderSceneIntoCubeMap to construct the cube texture to reflect the environment for that frame. After that, it renders the scene by calling RenderScene with the view and projection matrices from the camera, and bRenderEnvMappedMesh set to true.

The Shaders

All of the rendering in this sample are done by programmable shaders, divided into three effect techniques: RenderLight, RenderHDREnvMap, and RenderScene.

The RenderLight technique is used for rendering the spheres representing the light sources. The vertex shader does a usual world-view-projection transformation, then assigns the light intensity value to the output diffuse. The pixel shader propagates the diffuse to the pipeline.

The RenderHDREnvMap technique is used for rendering the environment-mapped mesh in the scene. Besides transforming the position from object space to screen space, the vertex shader computes the eye reflection vector (the reflection of the eye-to-vertex vector) in view space. This vector is passed to the pixel shader as a cubic texture coordinate. The pixel shader samples the cube texture, applies the reflectivity to the sampled value, and returns the result to the pipeline.

The RenderScene technique is used to render everything else. Objects rendered by this technique employ per-pixel diffuse lighting. The vertex shader transforms the position from object to screen space. Then, it computes the vertex position and normal in view space and passes them to the pixel shader as texture coordinates. The pixel shader uses this information to perform per-pixel lighting. A for-loop is used to compute the amount of light received from the four light sources. The diffuse term of the pixel is computed by taking the dot product of the normal and the unit vector from the pixel to the light. The attenuation term is computed as the reciprocal of the square of the distance between the pixel and the light. These two terms are then modulated to represent the amount of light the pixel receives from one of the light sources. Once this process is done for all lights in the scene, the values are summed and modulated with the light intensity and the texel to form the output.

High Dynamic Range Realism

Prior to DirectX 9.0, only integer texture formats are supported by Microsoft Direct3D. When a texture of this type is used, if a color value is higher than 1.0, it is clamped to 1.0 before being written so that the value can fit in an 8-bit integer. This means that when the cube texture is written, its texel color values will have a maximum of 1.0. When this texture is later used for environment-mapping on a material that is not 100 percent reflective (say, only 30 percent reflective), even the brightest texels in the texture will end up showing at 0.3 on the mesh, regardless of how high the original light intensity is. Consequently, realism is compromised. This is demonstrated in the figure below.

When DirectX 9.0's new floating-point cube texture is used with lights whose intensity is higher than 1, the texture is capable of storing color values higher than 1.0, thus preserving true luminance even after the reflectivity multiplication. The figure below shows this.

Alternatives

It is possible to achieve a high level of realism in a high dynamic range lighting environment without using floating-point cube textures. An application can accomplish this by applying the material reflectivity multiplier when constructing the cubic environment map. Then, during rendering, the pixel shader will sample the cube texture and output the value straight back to the pipeline. This method works around color clamping by scaling before the clamping instead of after. The drawback of this method is that if the scene has multiple environment-mapped objects with different reflectivity, a different environment map will generally need to be rendered for each of these objects.


HDRFormats Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

HDRFormats Sample

High Dynamic range lighting effects require the ability to work with color values beyond the 0 to 255 range, usually by storing high range color data in textures. Floating point texture formats are the natural choice for HDR applications, but may not be available on all target systems. This sample shows how high dynamic range data can be encoded into integer formats for compatibility across a wide range of devices.

Path

Source: | (SDK root)\Samples\C++\Direct3D\HDRFormats
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\HDRFormats.exe

Sample Overview

High dynamic range lighting techniques add realism to your application; furthermore, these techniques are fairly straight-forward to implement, integrate well into an existing render pipeline, and require a modest amount of processing time; however, most HDR techniques rely in floating-point texture formats, which may not be available on the target system. One way to enable HDR techniques on devices without floating-point texture support is to encode high range floating-point data into an integer format, decoding on-the-fly as needed.

Be aware that integer textures are not perfect replacements for floating point textures; the disadvantages of integer encoding are a loss of precision and/or a loss a range from the floating-point source, plus a performance hit resulting from the encoding/decoding process. This encoding/decoding happens seemlessly within the pixel shaders, so it's not prohibitively expensive, but it does use some of the available shader instruction count and can cause a slight frame-rate drop. For static elements, such as a skyboxes, the encoding can be done once during initialization, saving some cycles during run-time.

Implementation

The application uses two high dynamic range techniques: tone mapping and blooming. If you're not familiar with how these techniques work or want more information about high dynamic range images in general, look at HDR Lighting programming guide first, and view the HDRLighting and HDRCubeMap samples included with the SDK.

For the techniques used in this sample, the ability to store HDR data in textures is critical. The scene must be rendered to an HDR render target, the environment map texture needs to be HDR, and the temporary textures used to measure scene luminance all need to store HDR data. A device which supports floating-point textures will offer the best performance and simplest implementation, but with a little extra work integer textures can be used to store HDR data. This sample implements two encoding schemes:

RGB16

Using a 16-bit per channel integer format, 65536 discrete values are available to store per channel data. This encoding is a simple linear distribution of those 65536 values between 0.0f and an arbitrary maximum value (100.0f for this sample). The alpha channel is unused. Here is the formula for decoding the floating-point value from an encoded RGB16 color:

decoded.rgb = encoded.rgb dot max_value

RGBE8

This encoding is more sophisticated than RGB16, and allows for a far greater range of color data by using a logarithmic distribution. Each channel stores the mantissa of the color component, and the alpha channel stores a shared exponent. The added flexibility of this encoding comes at the cost of extra computation. Here is the formula for decoding the floating-point value from an encoded RGBE8 color:

decoded.rgb = encoded.rgb * 2encoded.a

The images below show the textures used to render the scene in top-down order according to when they're used. Images with a blue border contain high dynamic range data, shown here with RGBE8 encoding.

The process of rendering the scene is nearly identical between the native floating-point texture mode and the encoded integer texture modes. Pixel shaders which read from high dynamic range textures simply require an extra decoding step when reading from encoded integer textures and require a similar encoding step when writing HDR data to integer textures. By using uniform arguments to the shader, the same shader can be compiled differently and used by every encoding scheme. For example, here's the pixel shader which lights the model:

//-----------------------------------------------------------------------------
// Name: ScenePS
// Type: Pixel Shader
// Desc: Environment mapping and simplified hemispheric lighting
//-----------------------------------------------------------------------------
float4 ScenePS( SceneVS_Output Input,
                uniform bool RGBE8,
                uniform bool RGB16 ) : COLOR
{
    // Sample the environment map
    float3 vReflect = reflect( Input.ViewVec_World, Input.Normal_World );
    float4 vEnvironment = texCUBE( CubeSampler, vReflect );

    if( RGBE8 )
        vEnvironment.rgb = DecodeRGBE8( vEnvironment );
    else if( RGB16 )
        vEnvironment.rgb = DecodeRGB16( vEnvironment );

    // Simple overhead lighting
    float3 vColor = saturate( MODEL_COLOR * Input.Normal_World.y );

    // Add in reflection
    vColor = lerp( vColor, vEnvironment.rgb, MODEL_REFLECTIVITY );

    if( RGBE8 )
        return EncodeRGBE8( vColor );
    else if( RGB16 )
        return EncodeRGB16( vColor );
    else
        return float4( vColor, 1.0f );
}


HDRLighting Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

HDRLighting Sample

This sample demonstrates some high dynamic range (HDR) lighting effects using floating-point textures. Integer texture formats have a limited range of discrete values, which results in lost color information under dynamic lighting conditions; conversely, floating-point formats can store very small or very large color values, including values beyond the displayable 0.0 to 1.0 range. This flexibility allows for dynamic lighting effects, such as blue-shifting under low lighting and blooming under intense lighting. This sample also employs a simple light adaptation model, under which the camera is momentarily overexposed or underexposed to changing light conditions.

HDR Lighting Sample screen shot

Path

Source: | (SDK root)\Samples\C++\Direct3D\HDRLighting
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\HDRLighting.exe

Why This Sample Is Interesting

Light in the real world has a very high ratio between highest and lowest luminances; this ratio is called dynamic range and is approximately 1012:1 for viewable light in everyday life, from sun to starlight; however, the human visual system is only capable of a dynamic range around 1000:1 at a particular exposure. In order to see light spread across a high dynamic range, the human visual system automatically adjusts its exposure to light, selecting a narrow range of luminances based on the intensity of incoming light. This process is not instantaneous, as you'll notice when entering a dark building on a sunny day, or vice versa. This delayed exposure adjustment is referred to as light adaptation, and can be simulated in a real-time application.

Computer displays and print media have a dynamic range around 100:1, so compromises will have to be made when trying to display a scene with a higher dynamic range; this sample borrows from a technique originally developed for use in photography called tone mapping, which describes the process of mapping an HDR image into a low dynamic range space. Tone mapping effectively produces the same effect as the automatic exposure control which happens in the human visual system.

Finally, when a bright light strikes a lens, certain aberrations naturally occur, including bloom and star effects shown in the following image. If high-intensity light values are not discarded during the render process, these effects can be produced after the scene has been rendered to add an additional level of realism to the image. Because these are post-process effects, the time required to produce them depends only on the screen resolution, regardless of scene or lighting complexity.

Scene with glare effects

Overview

This sample uses Microsoft DirectX 9.0 floating-point textures to store HDR lighting information for the scene. Integer texture formats are clamped from 0.0f to 1.0f in the pixel shader, but floating-point textures are allowed to contain any value, bound only to the constraints of available bits for mantissa and exponent.

The algorithms described in this sample are based very closely on the lighting effects implemented in the following references.

  • Kawase, Masaki. Real-Time High Dynamic Range Image-Based Lighting World Wide Web link.
  • Reinhard, Erik, Mike Stark, Peter Shirley, and Jim Ferwerda. Photographic Tone Reproduction for Digital Images World Wide Web link.

How the Sample Works

For this sample, scene objects are textured with normal integer format textures, but the sphere objects representing lights are shaded with a high range of values, effectively creating emissive lights. All objects in the scene are shaded using an illumination model that calculates ambient, diffuse, and specular lighting based on the position and intensity of the lights; because these lights be assigned high values, the resulting colors of illuminated objects can extend far beyond the 1.0f cutoff. If a floating-point texture is not used to capture these HDR values, this light data will be lost, and the scene will appear overexposed, as in the following figure.

Scene without tone mapping

If, instead, the scene is rendered onto a floating-point surface, the HDR information will be stored and the scene can then be tone mapped to an appropriate low dynamic range for display, as shown in the following figure.

Scene with tone mapping

The following figure shows the top-level flow diagram for the sample. The scene is first rendered onto a floating-point texture, which has the same dimensions as the backbuffer. Because the scene will be sampled several times to create the post-processing effects, a good first step is to scale down the scene to minimize the number of pixels the shaders must sample. This has the added benefit of making post-process effects larger when their associated textures are scaled up to full size. The scaled scene texture is processed to measure the average luminance of the scene. Using this average luminance value, it is possible to determine which pixels in the scene will be bright after the scene has been tone mapped to a low dynamic range. By excluding all color data in the scene except brightly-lit areas, a bright-pass filtered copy of the scene is created that can be used as the source of post-process lighting effects.

Flow diagram for high dynamic range sample

The scene in this sample is rendered using a pixel shader to control the ambient, diffuse, and specular contribution of each light at every pixel. Because the lights for the featured scene are very bright, most of the pixels have per-channel color components above the 0.0 to 1.0 range displayable by the graphics card. Therefore, this texture appears mostly white when viewed directly. However, the color information above 1.0 is not lost, but simply needs to be tone-mapped into the 0.0 to 1.0 range. During a final pass, the scene is tone-mapped to the desired luminance range, and the post-process image effects are blended on top of the scene to create the final image.

User's Guide

Calculating Luminance

Before your program can scale the intensity of your scene, it will need to determine how bright the scene is to begin with. The goal is to calculate a good estimate for the average scene luminance while minimizing the amount of time spent making the calculation. The calculation can be sped up by reducing the number of sampled texels, but you risk missing bright areas with a sparse test pattern. The approach used in this sample is to first scale the scene by 1/4 x 1/4, using the average of each 4 x 4 block of texels to down-sample. This scaled texture is also used to create the source textures for the lighting effects, so it is important that the scale operation is precise, to avoid flickering artifacts as the camera moves around the scene.

The process used to measure the average scene luminance and perform tone mapping is featured in the whitepaper Photographic Tone Reproduction for Digital Images World Wide Web link, from which the following luminance equation is taken.

Equation for average luminance

The average scene luminance used for later calculations is the antilogarithm of the average log values for all sampled pixels. Delta contains a small value to handle the case of pure black texels. This equation is implemented using four pixel shader passes called from the sample application's MeasureLuminance method, as follows:

  1. Sample average log() values into a 64 x 64 texture.
  2. Downscale to 16 x 16.
  3. Downscale to 4 x 4.
  4. Downscale to 1 x 1 and perform an exp() operation on the result.

By keeping the calculation result inside a 1 x 1 texture, the calculations which require the average luminance value can be done completely on the video card without requiring any accelerated graphics port (AGP) transfers.

Exposure Control

Exposure control is the process of finding an appropriate low dynamic range view of the HDR scene. In a physical lens system, the aperture is adjusted to limit the amount of light entering the system. The process used in computer graphics to emulate exposure control is commonly called tone mapping, which refers to the process of mapping an HDR image space onto a low dynamic range space suitable for video display. Unlike exposure control, all the high range data is available for use when tone mapping; so, depending on the operator used, the image may contain more detail from bright and dark areas simultaneously than would be possible using a traditional camera.

After the average scene luminance has been calculated, the HDR scene texture can be scaled according to a target average luminance, represented by alpha in the following equation:

Equation for luminance scaled to target average luminance

This equation simply produces a linear scaling of the scene luminance centered around the target average luminance for the final scene; however, the resulting values have not yet been compressed to fit within the low dynamic range of 0.0 to 1.0 viewable on the monitor. The following tone mapping operator performs the desired compression.

Equation for tone mapping operator

Light Adaptation

The human visual system does not adjust instantly for changing light conditions, and this behavior can be easily simulated by slightly extending the tone-mapping calculations. The luminance value to which the user is currently adapted is used instead of the average scene luminance within the tone-mapping equations. This adapted luminance value is stored in a 1 x 1 texture and is adjusted each frame to slowly track the measured scene luminance, as shown in the following code snippet:

float fNewAdaptation = fAdaptedLum + (fCurrentLum - fAdaptedLum) * ( 1 - pow( 0.98f, 30 * g_fElapsedTime ) );

For example, if the camera is stationary, the adapted luminance will eventually match the measured luminance, resulting in tone-mapped output identical to the output when adaptation is disabled. However, if the camera is moved to focus on an area of different lighting magnitude, the image will appear over- or underexposed while the viewer adjusts to the new lighting conditions. The adaptation model used in this sample is not intended to be a realistic model of human adaptation, which can take longer than a half hour for full dark adaptation.

Bright-Pass Filter

Tone mapping is performed in two places within the code: once in Render as part of the final shader pass to compose the glare textures onto the scene, and once as part of the bright-pass filter. The bright-pass filter uses tone mapping to first determine what areas of the final scene image will be bright, and then it excludes the remaining data. Because HDR lighting effects are relative to the current exposure, these effects can be performed on a tone-mapped image and added directly to the scene output. This procedure offers the advantage of being able to use integer textures for glare generation.

As shown in the following code snippet, the bright-pass filter first maps the scene to a desired middle gray target luminance before subtracting out the dark areas. The tone mapping operator which transforms the scene luminance to the 0.0 to 1.0 range is modified slightly from the last equation. Instead of dividing the luminance by one plus the luminance, an offset value replaces one in the equation. As this offset value increases, the relative separation between bright and dark regions of the scene also increases.

// Determine what the pixel's value will be after tone mapping occurs
vSample.rgb *= g_fMiddleGray/(fAdaptedLum + 0.001f);

// Subtract out dark pixels
vSample.rgb -= BRIGHT_PASS_THRESHOLD;

// Clamp to 0
vSample = max(vSample, 0.0f);

// Map the resulting value into the 0 to 1 range. Higher values for
// BRIGHT_PASS_OFFSET will isolate lights from illuminated scene
// objects.
vSample.rgb /= (BRIGHT_PASS_OFFSET+vSample);

Bloom Effect

Before the bloom is performed, the bright-pass filtered image is scaled and blurred down to 1/8 x 1/8 scale of the original scene texture. The bloom pass is simply a two-pass separable horizontal and vertical Gaussian blur of the scaled bright-pass filtered scene. As shown in the following figure, the texture is first blurred along the horizontal, then the horizontally-blurred texture is blurred along the vertical to complete the process. As part of the final scene pass, the bloom texture is scaled to the size of the back buffer using bilinear filtering and added directly to the output of the scene.

Star Effect

The star effect may require as many as three passes to render each of the star lines. The star patterns used in this sample require as many as eight lines, resulting in a potential cost of 24 passes to render fully. The GlareDef.h file defines characteristics for the various star types, including the number of lines, line directions, and chromatic offsets. As shown in the following figure, once all the individual directional lines have been rendered, the average texel value across the individual line textures is used to create the final composite star texture. This composite texture is scaled and added directly to the final scene image.


HLSLwithoutEffects Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

HLSLwithoutEffects Sample

HLSLwithoutEffects demonstrates using high-level shader language (HLSL) to write vertex shaders without using the D3DX effect interfaces. HLSL is a language that closely resembles C syntax and constructs. By writing shaders in HLSL instead of assembly language, developers can take advantage of not only the features and elements of the language they are already familiar with, but also the great optimization capabilities offered by the D3DX shader compiler.

Path

Source: | (SDK root)\Samples\C++\Direct3D\HLSLwithoutEffects
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\HLSLwithoutEffects.exe

How HLSLwithoutEffects Works

The scene that this sample renders consists of a square grid of triangles lying on the XZ plane. In each frame, the vertices of this grid will move up or down along the Y direction based on a function of their distance to the origin and time. The vertices are also lit using another function of the distance and time. The time is incremented for each frame. Because the Y coordinate and color of the vertices are generated in each frame, they do not need to be stored. Therefore, the vertex declaration only contains a D3DXVECTOR2 for the X and Z coordinates.

During initialization, the sample calls D3DXCompileShaderFromFile to read the shader function from a file and compile it into binary shader code. After this process, an ID3DXBuffer containing the shader code and a ID3DXConstantTable that allows the application to get and set the global variables of the shader are created. Then, the sample calls IDirect3DDevice9::CreateVertexShader with the shader code to obtain a IDirect3DDevice9 object that can be passed to the device.

In FrameMove, the sample uses the ID3DXConstantTable interface to set the shader's global variables mViewProj and fTime in order to update the view + projection transformation and time parameter for the shader. At render time, the sample calls IDirect3DDevice9::SetVertexShader to enable vertex shader rendering on the device. When IDirect3DDevice9::DrawIndexedPrimitive is called after that, the vertex shader will be invoked once for every vertex processed.

In the sample, the vertex shader is written in a text file called HLSLwithoutEffects.vsh. In this file, there are two global variables and a shader function called Ripple. Ripple takes a float2 as input (for X and Z of the vertex) and outputs two float4 representing the screen-space position and vertex color. The Y coordinate is generated using this formula:

Y = 0.1 * sin( 15 * L * sin(T) );

L is the distance between the vertex and the origin before the Y adjustment, so it has the value of sqrt(X2 + Z2), because the vertices are lying on the XZ plane. T is the fTime global variable.

The color of the vertex will be some shade of gray based on this formula:

C = 0.5 - 0.5 * cos( 15 * L * sin(T) );

C will be the value used for all red, green, blue, and alpha and will range from 0 to 1, giving the vertex a color of black to white, respectively. The result looks like ripples with width changing back and forth between narrow and wide and with proper shading based on the slope.

General controls defined in the sample:

Key | Action
W/S | Move forward/backward
Q,E,A,D | Strafe
F2 | Change device
Esc | Quit


Instancing Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

Instancing Sample

This sample demonstrates the instancing feature available with Microsoft DirectX 9.0c. A vs_3_0-capable device is required for this feature. The sample also shows alternate ways of achieving results similar to hardware instancing, but for adapters that do not support vs_3_0. The shader instancing technique shows the benefits of efficient batching of primitives.

Note On graphics hardware that does not support vs_3_0, the sample will run as a reference device.

Path

Source: | (SDK root)\Samples\C++\Direct3D\Instancing
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\Instancing.exe

How the Sample Works

The sample demonstrates four different rendering techniques to achieve the same result: to render many nearly identical boxes (objects with small numbers of polygons) in the scene. The boxes differ by their position and color.

The user can vary the number of boxes in the scene between one and 1000. Use the sample to monitor performance as the number of boxes increases. As you change the number of boxes, the vertex and index buffer resources are recreated by the sample application's OnCreateBuffers and OnDestroyBuffers methods.

Technique 1: Hardware Instancing

Hardware instancing requires a vs_3_0-capable device. The instance-specific data is stored in a second vertex buffer. The rendering is implemented in the sample application's OnRenderHWInstancing method. IDirect3DDevice9::SetStreamSourceFreq is used with D3DSTREAMSOURCE_INDEXEDDATA to specify the number of boxes and with D3DSTREAMSOURCE_INSTANCEDATA to specify the frequency of the instance data (in this case, frequency equals one).

Drawing the scene is accomplished as follows:

pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0, 4 * 6, 0, 6 * 2 );

Technique 2: Hardware Instancing with Draw Call Batching

This is the most efficient technique that does not use the hardware to perform the instancing. One call to IDirect3DDevice9::DrawIndexedPrimitive handles multiple primitives at once. The instance data is stored in a system memory array, which is then copied into the vertex shader's constants at draw time. Since vs_2_0 only guarantees 256 constants, it is not possible for the entire array of instance data to fit at once. This sample's .fx file can only batch-process 120 constants (one float4 is required for box position, and one float4 is required for box color). Rendering is performed in the sample's OnRenderShaderInstancing method.

int nRenderBoxes = min( nRemainingBoxes, g_nNumBatchInstance );
...
pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0, nRenderBoxes * 4 * 6, 0, nRenderBoxes * 6 * 2 );

This method would also work on a vs_1_1 part, although not as efficiently because vs_1_1 only guarantees 96 constants. This means that batching is nearly three times more efficient on vs_2_0 hardware than on vs_1_1 hardware, but even on vs_1_1 hardware, batching still outperforms no batching.

Technique 3: Hardware Instancing without Draw Call Batching

This technique is somewhat similar to Technique 2 without the batching (batch size = 1). It will render one box at a time, by first setting its position and color and then calling IDirect3DDevice9::DrawIndexedPrimitive. The technique is implemented in the sample's OnRenderConstantsInstancing method.

Technique 4: Hardware Instancing with Stream Instancing

As in Technique 1, this technique uses a second vertex buffer to store instance data. Instead of setting vertex shader constants to update the position and color for each box, this technique changes the offset in the instance stream buffer and draws one box at a time. The technique is implemented in the sample's OnRenderStreamInstancing method.

CPU- vs. GPU-bound

When the sample renders a large number of boxes, only Techniques 1 and 2 are graphics processing unit (GPU)-bound, while Techniques 3 and 4 waste many CPU cycles by making numerous calls per frame to IDirect3DDevice9::DrawIndexedPrimitive. To demonstrate the benefits of not being CPU-bound in a real-world application, the sample offers a Goal slider control that simulates CPU resources consumed by secondary tasks such as game logic, artificial intelligence, or physics modeling.

If the sample determines that there is time left to do so before the next frame, it consumes remaining CPU resources according to the position of the Goal slider control. The Remaining for logic statistic displays the percentage of CPU cycles that are being spent on the simulated non-rendering algorithms such as game logic or physics. The higher this percentage is, the more efficiently the CPU is being used for rendering. The Goal settings are implemented in the sample's OnTimer method.

If the scene is loaded with 1000 boxes, the efficient techniques have twice the CPU efficiency of the CPU-bound techniques. Using Techniques 3 and 4 to render many instances will often starve other tasks of available CPU resources.

The following table summarizes hardware and memory requirements for different rendering techniques:

Rendering Technique | Requires vs_3_0 Card | CPU-bound | Requires Additional Vertex Buffer | Requires Additional Shader Constant Buffer
Hardware Instancing | Yes | No | Yes | No
Shader Instancing | No | No | No | Yes
Constants Instancing | No | Yes | No | Yes
Stream Instancing | No | Yes | Yes | No

Related Topics

  • Drawing Multiple Instances of Geometry Efficiently


MeshFromObj Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

MeshFromObj Sample

This sample shows how an ID3DXMesh object can be created from mesh data stored in a Wavefront Object file ( .obj). It's convenient to use .x files when working with ID3DXMesh objects since D3DX can create and fill an ID3DXMesh object directly from a .x file. It's also easy to initialize an ID3DXMesh object with data gathered from any file format or memory resource.

Path

Source: | (SDK root)\Samples\C++\Direct3D\MeshFromObj
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\MeshFromObj.exe

Sample Overview

The ID3DXMesh interface is a handy way to manage complex meshes. It allows you to divide the mesh into subsets, usually according to separate material types. When rendering the mesh you can loop through subsets, setting the proper render state for the current material. The interface treats the complex mesh as a single object while still offering the flexibility of rendering with several different textures or shaders.

The interface implements member functions for optimizing how internal mesh data is sorted. This leads to fewer state changes during rendering and increased vertex cache performance. In addition, the related interfaces ID3DXPatchMesh, ID3DXPMesh, and ID3DXSPMesh support other specialized cases.

ID3DXMesh can encapsulate any mesh that can be rendered using indexed triangle lists, and therefore does not rely on any particular file format. The purpose of this sample is to show how an ID3DXMesh object can be created from arbitrary mesh data.

Implementation

ID3DXMesh objects contain a vertex buffer and an associated index buffer. Each ID3DXMesh object is rendered as an indexed triangle list, so a call to ID3DXMesh::DrawSubset is functionally the same as retrieving the internal vertex and index buffers and calling IDirect3DDevice9::DrawIndexedPrimitive using the D3DPT_TRIANGLELIST primitive type. To fill an ID3DXMesh object with mesh data you simply need to fill the internal vertex and index buffers. When creating a mesh directly from a .x file using D3DXLoadMeshFromX, setting the vertex format and populating the vertex and index buffers are handled automatically. If you use a different mesh file format (than .x) you will need to set up the vertex and index buffers yourself.

For this sample, the .obj format was chosen for its simplicity, but the lesson extends to any file format or memory resource layout. In fact, the most important snippet of sample code is the portion which deals with loading an ID3DXMesh object once the mesh data has already been imported:

// Create the encapsulated mesh
ID3DXMesh* pMesh = NULL;
V_RETURN( D3DXCreateMesh( m_Indices.GetSize() / 3, m_Vertices.GetSize(),
                          D3DXMESH_MANAGED | D3DXMESH_32BIT, VERTEX_DECL,
                          pd3dDevice, &pMesh ) );

// Copy the vertex data
VERTEX* pVertex;
V_RETURN( pMesh->LockVertexBuffer( 0, (void**) &pVertex ) );
memcpy( pVertex, m_Vertices.GetData(), m_Vertices.GetSize() * sizeof(VERTEX) );
pMesh->UnlockVertexBuffer();
m_Vertices.RemoveAll();

// Copy the index data
DWORD* pIndex;
V_RETURN( pMesh->LockIndexBuffer( 0, (void**) &pIndex ) );
memcpy( pIndex, m_Indices.GetData(), m_Indices.GetSize() * sizeof(DWORD) );
pMesh->UnlockIndexBuffer();
m_Indices.RemoveAll();

// Copy the attribute data
DWORD* pSubset;
V_RETURN( pMesh->LockAttributeBuffer( 0, &pSubset ) );
memcpy( pSubset, m_Attributes.GetData(), m_Attributes.GetSize() * sizeof(DWORD) );
pMesh->UnlockAttributeBuffer();
m_Attributes.RemoveAll();

The code above locks and fills the internal vertex and index buffers, much the same way these buffers would be accessed if used independently of the ID3DXMesh interface. This code also fills the optional attribute buffer. Each face in the mesh can be given an attribute, which is the number of the subset to which it belongs; during a call to ID3DXMesh::DrawSubset( DWORD AttribId ), those faces with an attribute that matches the attribute id will be rendered. If rendering the entire mesh, the application simply needs to loop through all the subsets. The attribute ids divide a mesh into groups which are rendered separately. For this sample, the mesh is divided into material groups which allows an application to render each subset with the correct material properties.

Here's the code to render a subset of the mesh, showing how the texture, illumination variables, and shaders are adjusted for the particular material prior to rendering the subset:

void RenderSubset( UINT iSubset )
{
    HRESULT hr;
    UINT iPass, cPasses;

    // Retrieve the ID3DXMesh pointer and current material from the MeshLoader helper
    ID3DXMesh* pMesh = g_MeshLoader.GetMesh();
    Material* pMaterial = g_MeshLoader.GetMaterial( iSubset );

    // Set the lighting variables and texture for the current material
    V( g_pEffect->SetValue( g_hAmbient, pMaterial->vAmbient, sizeof(D3DXVECTOR3) ) );
    V( g_pEffect->SetValue( g_hDiffuse, pMaterial->vDiffuse, sizeof(D3DXVECTOR3) ) );
    V( g_pEffect->SetValue( g_hSpecular, pMaterial->vSpecular, sizeof(D3DXVECTOR3) ) );
    V( g_pEffect->SetTexture( g_hTexture, pMaterial->pTexture ) );
    V( g_pEffect->SetFloat( g_hOpacity, pMaterial->fAlpha ) );
    V( g_pEffect->SetFloat( g_hSpecularPower, pMaterial->fShininess ) );

    V( g_pEffect->SetTechnique( pMaterial->hTechnique ) );
    V( g_pEffect->Begin(&cPasses, 0) );

    for (iPass = 0; iPass < cPasses; iPass++)
    {
        V( g_pEffect->BeginPass(iPass) );

        // Render the mesh with the applied technique
        V( pMesh->DrawSubset( iSubset ) );

        V( g_pEffect->EndPass() );
    }
    V( g_pEffect->End() );
}

The next section demonstrates how to import mesh data from a .obj file. Note that the simple parser created for this sample is not intended to be a complete parser for the .obj format nor any of its extensions.

Loading the geometry from file

Wavefront Object (*.obj) files are an ASCII format for describing meshes composed of triangle lists. Vertices may contain texture coordinates and normals. Object files may also contain a reference to an MTL (*.mtl) file, which defines materials containing illumination variables and texture filenames. Mesh faces can be assigned a material to allow separate components of the mesh to retain individual material properties. Each line of the file begins with a token which indicates the type of information stored on that line:

token | Comment (ignored)
v float float float | Vertex position v (position x) (position y) (position z)
vn float float float | Vertex normal vn (normal x) (normal y) (normal z)
vt float float | Texture coordinate vt (tu) (tv)
f int int int | f (v) (v) (v) Faces are stored as a series of three vertices in clockwise order. Vertices are described by their position, optional texture coordinate, and optional normal, encoded as indices into the respective component lists.
f int/int int/int int/int | f (v)/(vt) (v)/(vt) (v)/(vt)
f int/int/int int/int/int int/int/int | f (v)/(vt)/(vn) (v)/(vt)/(vn) (v)/(vt)/(vn)
mtllib string | Material file (MTL) mtllib (filename.mtl) References the MTL file for this mesh. MTL files contain illumination variables and texture filenames.
usemtl string | Material selection usemtl (material name) Faces which are listed after this point in the file will use the selected material

The mesh files are parsed within the CMeshLoader::LoadGeometryFromOBJ, which builds a vertex buffer, an index buffer, and an attribute buffer. After the file is completely parsed, these buffers can be copied into an empty ID3DXMesh object. LoadGeometryFromOBJ builds vertex position, texture coordinate, and vertex normal lists directly from file input. When a mesh face element is encountered within the input file, the vertex components are retrieved from the respective component lists.

Since multiple vertices may share the same position but have different texture coordinates or vertex normals, a little extra work must be done when storing vertices, otherwise duplicate vertices will be added to the vertex buffer (in which case there's no point to having an index buffer). To make this check relatively quick, vertices are stored in a hash table cache according to their position index as they are added to the vertex buffer. This cache is checked for duplicates by CMeshLoader::AddVertex for each new face. After the mesh has been completely loaded from file, this vertex cache is destroyed by calling the CMeshLoader::DeleteCache.

Most .obj files will also reference a .mtl file, which contains named material sets. The parser builds a list of materials it expects to find within the .mtl file, and keeps track of which material is selected as each mesh face is read. This material index is also used as the attribute number for a given face; these attribute numbers divide the mesh faces into material type subsets. Although the material groupings may be scattered throughout the .obj file, the vertex buffer will be reordered into material subsets as part of the call to ID3DXMesh::Optimize, so no additional sorting is required of the parser.

Loading the Materials from file

If an MTL file was referenced within the Object file, it's parsed immediately after the Object file. The MTL file format uses an ASCII encoding very similar to .obj files, using these tokens:

Token | Comment (ignored)
newmtl string | Material newmtl (material name). Begins a new material description.
Ka float float float | Ambient color Ka (red) (green) (blue)
Kd float float float | Diffuse color Kd (red) (green) (blue)
Ks float float float | Specular color Ks (red) (green) (blue)
d float Tr float | Transparency Tr (alpha)
Ns int | Shininess Ns (specular power)
illum int | Illumination model illum (1 / 2); 1 if specular disabled, 2 if specular enabled.
map_Kd string | Texture map_Kd (filename)

When the .obj file is parsed and new material names are encountered, material structures containing default values are created and added to the material list. When the .mtl file is parsed, these structures are retrieved from the material list and filled with the correct values. In addition, a default material is created to contain all the faces which aren't otherwise assigned a material. These conventions guarantee that all faces will be assigned a material and missing material descriptions will be filled with default values.

Texture filenames are stored within the material structures, and the corresponding textures are created upon device creation. When creating textures, the material list is scanned for duplicate texture filenames to ensure that materials which use the same texture point to a single created instance. After the .mtl file has been parsed, each item in the material list will correspond to a subset in the ID3DXMesh object. As described above, this material list is iterated through in combination with corresponding mesh subsets when rendering the entire mesh.


MultiAnimation Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

MultiAnimation Sample

This sample demonstrates mesh animation with multiple animation sets using high-level shader language (HLSL) skinning and the D3DX animation controller. The animation controller blends animation sets together to ensure a smooth transition when moving from one animation to another.

MultiAnimation sample screenshot

Path

Source: | (SDK root)\Samples\C++\Direct3D\MultiAnimation
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\MultiAnimation.exe

Overview

This sample shows how an application can render 3-D animation utilizing D3DX animation support. D3DX has application programming interfaces (APIs) that handle the loading of the mesh to be animated, as well as the blending of multiple animations. The animation controller supports animation tracks for this purpose, and allows transitioning from one animation to another smoothly. The sample is divided into two parts: the animation class library and the application.

The animation class library is a general-purpose library that sits between the application and D3DX. It encapsulates the details of loading the mesh from a .x file and manipulating its frame hierarchy to prepare it for rendering, as well as rendering the animated mesh using a vertex shader and a matrix palette for indexed skinning. It is designed to be reusable and customizable.

The application portion contains code specific only to this sample. It uses the animation class library to create instances of the Tiny character, which are animated according to the action they perform. Each instance can be controlled by either the user or the sample. This portion also handles collision detection among instances of Tiny, out of bound detection, and behavior management for instances that are controlled by the sample.

The Application

The application portion of this sample consists of two parts. The first part is the CTiny class. It handles the behavior of the animated mesh in the sample loaded from the tiny_4anim.x file. The second part contains CMyD3DApplication and all of the code that is normally generated by the Microsoft DirectX application wizard.

In this sample, Tiny can be controlled by either the user or the application (default). When Tiny is controlled by the application, the following happens: First, a random location on the floor is chosen and a move speed (run or walk) is determined. Next, Tiny is turned at the current position toward the new destination and is moved in that direction. After Tiny arrives at the new destination, there is a brief period of idle time before another location is selected where to move Tiny, and the whole process repeats. There can be more than one instance of Tiny. Collision detection is done for the instances, so they can block each other's movement.

The CTiny class has a CAnimInstance member, a class defined by the animation library. CTiny uses this member and its animation controller to perform the animation tasks necessary. In this sample, Tiny has three sets of animation: Loiter, Walk, and Run. The animation controller of Tiny supports two animation tracks. Most of the time, one of these two tracks is active with an animation set. When Tiny's action calls for a change of animation (for instance, going from loitering to walking, or stopping from running), enable the second track with the new animation set to play and set a transition period to complete the transition from the first track to the second. Then, as time is advanced, the animation controller will generate the correct frame matrices that reflect the transition smoothly by interpolating between the two tracks. After the transition period passes, the first track is disabled, and the second track plays the new animation in which Tiny is seen.

CTiny also takes advantage of the callback system to play the footstep sound at appropriate instances in the animation. At initialization time, CTiny sets up a structure, CallbackDataTiny, containing the data to pass to the callback handler. The structure has three members: m_dwFoot indicates which foot is triggering the sound, m_pvCameraPos points to the camera position when the callback is made, and m_pvTinyPos points to the world space coordinates of Tiny. This data is used to determine which sound to play (left or right), and how loud it should be. The sample defines a class called CBHandlerTiny, derived from ID3DXAnimationCallbackHandler, that contains the callback handler function to be called by the animation controller. The callback handler function, HandleCallback, retrieves the data passed as a CallbackDataTiny structure then plays a Microsoft DirectSound buffer with the appropriate volume based on the values in the CallbackDataTiny structure.

In FrameMove, the sample iterates through the array of CTiny instances and calls Animate on each one of them. This updates the behaviors of all instances, changing them if needed.

The rendering code of the application is relatively simple. It first sets up the view and projection matrices based on the camera position and orientation, then it renders the mesh object representing the floor. Next, it goes through the array of Tiny instances and calls AdvanceTime and Draw on each one of them. AdvanceTime makes the animation controller update the frame hierarchy's matrices, then Draw renders the instance using the updated matrices. Finally, the code renders the informational text as necessary.

The Animation Class Library

The library consists of the following structures and classes:

  • CMultiAnim
  • CAnimInstance
  • CMultiAnimAllocateHierarchy
  • MultiAnimFrame Structure
  • MultiAnimMC Structure

CMultiAnim

This class is the heart of the library. Its function is to encapsulate the mesh hierarchy loaded from a .x file. It can also create instances of the animating mesh, of the type CAnimInstance, that share the mesh hierarchy from the .x file. These instances are associated with the CMultiAnim object that creates them.

In its initialization method, CMultiAnim::Setup, CMultiAnim determines the maximum size of the matrix palette based on the version of the vertex shader present. It then loads the mesh hierarchy from the given .x file and creates an effect object from the given .fx file that contains the vertex shader with which the mesh is rendered. The frames of the mesh hierarchy and the animation controller are created in this process.

The frames consist of a tree structure representing the hierarchy of the bones, as well as the mesh objects. This structure is shared by all associated instances.

The animation controller is associated with the mesh hierarchy frames. The animation controller that CMultiAnim holds is not used for animation. Instead, when a new animation instance is created, the animation controller is cloned and the new animation controller is owned by the new instance. The application uses an instance's own animation controller to control its animation. Because each instance has its own copy of animation controller, it can animate independent of all other instances.

When the ID3DXAnimationController::AdvanceTime method of an animation controller in an animation instance is called, the animation controller will update the transformation matrix for each frame in the mesh hierarchy. The frames are then used in the rendering of the instance.

CAnimInstance

This class represents an animation entity, or an animation instance. Each animation instance has its own animation controller, which allows the instances to be animated independent of each other. Each instance is also associated with a CMultiAnim object, which holds the mesh hierarchy that is shared by all associated instances. The following table lists the methods that are the most interesting for animation control and which are used extensively by the application when animating and rendering.

Method Name | Description
GetAnimController | Returns the animation controller for this instance, of type ID3DXAnimationController. With the animation controller, the application can set the animation it needs to play.
SetWorldTransform | Sets the top level world transformation matrix for this instance. When the animation time advances, each frame in the mesh hierarchy is recursively transformed by this world transformation to bring it to the correct world space coordinate and orientation.
AdvanceTime | Advances the local animation time for this instance with an optional callback handler. The time advancement causes the animation controller to update the bone positions for this instance. The animation controller will also invoke the callback handler if the keyed event is reached.
ResetTime | Resets the local time for this instance.
Draw | Renders this instance with the HLSL vertex shader. This is normally called after calling AdvanceTime so that the frames are set up properly for rendering.

When an animation instance is rendered, it uses the effect object of its associated CMultiAnim to set the rendering parameters, including the vertex shader. The vertex shader function is responsible for skinning the mesh, transforming the position to screen space, and computing the color. The skinning portion is done by the function VS_Skin. This function is located in the vertex shader file Skin.vsh. The file contains an array of float4x3 named amPalette, which represents the matrix palette for skinning meshes, and the VS_Skin skinning function. VS_Skin is designed to be invoked by another vertex shader function, so an application can call it in its own vertex shader function to handle the skinning process. VS_Skin takes the object space position and normal, up to three blending weights (the last blending weight is computed by subtracting the sum of all other weights from 1), and up to four indices for the matrix palette. The function then transforms the position and normal up to four times with the corresponding matrices in the matrix palette and blending weights, and adds the result together to form the world space position and normal.

CMultiAnimAllocateHierarchy

This class inherits from ID3DXAllocateHierarchy. Its purpose is to handle the allocation and deallocation of resources during the loading and releasing of a mesh hierarchy. In this sample, CMultiAnimAllocateHierarchy initializes all members of new frames and mesh containers in CreateFrame and CreateMeshContainer called during the mesh hierarchy creation. In DestroyFrame and DestroyMeshContainer, it frees up all resources allocated in CreateFrame and CreateMeshContainer, respectively.

CreateMeshContainer does a little more work than simply allocating and copying. It also has to do the following:

  • Create all of the textures used by the mesh.
  • Initialize the mesh container's bone offset array, given by pSkinInfo.
  • Obtain the palette size that the mesh has to work with, and call ConvertToIndexedBlendedMesh to create a working mesh that is compatible with the palette size.

MultiAnimFrame Structure

This structure is derived from D3DXFRAME. It represents a single frame, or bone, in a mesh hierarchy. A frame may contain siblings or children. The entire mesh hierarchy is structured similar to a tree. The application can add members to a structure derived from D3DXFRAME as necessary. In this sample, no additional members are needed.

MultiAnimMC Structure

This structure is derived from D3DXMESHCONTAINER. It contains a mesh object attached to the mesh hierarchy along with relevant data for the mesh. A mesh hierarchy can contain any number of mesh containers. In this sample, additional members are defined as listed in the following table.

Type | Name | Description
LPDIRECT3DTEXTURE9* | m_apTextures | Array of Microsoft Direct3D texture objects used by the mesh.
LPD3DXMESH | m_pWorkingMesh | A copy of the mesh compatible with the matrix palette size available.
D3DXMATRIX* | m_amxBoneOffsets | Array of matrices representing the bone offsets. This information is obtained from the pSkinInfo member, copied here for convenience.
D3DXMATRIX** | m_apmxBonePointers | Array of pointers to matrix. They point to the TransformationMatrix of various frames of this mesh hierarchy. This array provides an easy mapping from bone index to bone matrix.
DWORD | m_dwNumPaletteEntries | Size of the matrix palette that this mesh uses when rendering. The size cannot exceed the maximum palette size allowed by our vertex shader due to limited registers, and it also cannot be larger than the number of bones in this mesh.
DWORD | m_dwMaxNumFaceInfls | Maximum number of bones that may affect a single face. This value is obtained from ID3DXSkinInfo::ConvertToIndexedBlendedMesh. The vertex shader needs this value when rendering in order to know when to compute the last weight.
DWORD | m_dwNumAttrGroups | Number of attribute groups in working mesh. An attribute group is a subset of the mesh that can be drawn in a single draw call. If the working palette size is not large enough to render the mesh in its entirety, it needs to be broken down into separate attribute groups. This is done by ID3DXSkinInfo::ConvertToIndexedBlendedMesh.
LPD3DXBUFFER | m_pBufBoneCombos | Contains the bone combination table, in the form of an array of D3DXBONECOMBINATION structures. There is one D3DXBONECOMBINATION for each attribute group. It identifies the subset of the mesh (vertices, faces, and bones) that can be drawn in a single draw call.

User's Guide

The following general controls are defined in the sample.

Key | Action
Q | Add instance
N | Next view
P | Previous view
R | Reset camera
I | Reset time
T | Toggle behavior text
F2 | Change device
Esc | Quit
V | Relinquish control for all mesh instances

The following controls are valid when you are viewing a specific mesh instance.

Key | Action
C | Take control
W | Move forward
A,D | Turn
Spacebar | Hold for run mode

Pitfalls and Alternatives

Some of what this sample does can be done differently, with different trade-offs.

Because all instances of Tiny share the same frame hierarchy matrices, the sample must advance time on a specific instance and render it before moving on to another instance. Generally, this does not present a problem. However, if an application wishes to update the matrices for all of the instances first then render them, it can make new animation controllers point to a different set of matrices when cloning. This way, each animation controller has its own set of matrices to work with, and overwriting will not occur, at the expense of more memory usage.

It is also worth noting that the matrix palette in the skinning vertex shader is an array of matrices, and naturally takes up a significant number of constant registers. An application may experience the problem of insufficient constant registers for other use. The application can work with a smaller-sized matrix palette by setting the MATRIX_PALETTE_SIZE_DEFAULT shader #define to a smaller value when creating the effect object in CMultiAnim. The drawback of this approach is that the mesh may contain more subsets that need to be drawn separately.

Note that this sample specifically demonstrates rendering animated meshes. It does not handle static meshes, although the code can be extended to do that.

Another task that the sample only does partially is the complete preservation of animation controllers' states when the Direct3D device is released and re-created. This generally happens when the application switches from HAL to REF device (see Device Types), or vice versa, or from one Direct3D device to the other on a dual-monitor system. In MultiAnimation, when the Direct3D device is released, all animation controllers are also released. The animation controllers are then re-created when the sample initializes the new Direct3D device. This presents a problem, because animation states stored in animation controllers are lost. The sample loses the knowledge of what animation each track is playing, what tracks are enabled, and the speed and weight of each track before the old device is released. To remedy this issue, an application should, before releasing Direct3D objects in its cleanup function (DeleteDeviceObjects for MultiAnimation), retrieve the animation controllers' states and save them in a buffer. Then, after it re-creates the animation controllers that it needs (in InitDeviceObjects for MultiAnimation), it should restore the animation controllers' states from the buffer. For each animation controller, the following states should be saved.

  • Current time of the animation controller, obtained with ID3DXAnimationController::GetTime.
  • Name of the animation set that each track is playing. Obtain this information by calling ID3DXAnimationController::GetTrackAnimationSet, then ID3DXAnimationSet::GetName.
  • Track description of all tracks. Use ID3DXAnimationController::GetTrackDesc to obtain this description.
  • Current events for all tracks, if there are events running. This can be retrieved with ID3DXAnimationController::GetCurrentTrackEvent and ID3DXAnimationController::GetEventDesc.
  • All keyed track events. To receive every event keyed, first call ID3DXAnimationController::GetUpcomingTrackEvent with hEvent set to NULL. This returns an event handle to the keyed event to happen next. Then, pass the handle to ID3DXAnimationController::GetEventDesc to obtain the description for this event. After that, take the handle received from the previous ID3DXAnimationController::GetUpcomingTrackEvent call and call ID3DXAnimationController::GetUpcomingTrackEvent again with it. This gives you the handle to the second keyed event. Repeat this process to receive all keyed events.
  • Current priority blend for the animation controller, by calling ID3DXAnimationController::GetPriorityBlend.
  • Current priority blend event, if one is running, by calling ID3DXAnimationController::GetCurrentPriorityBlend and ID3DXAnimationController::GetEventDesc.
  • All keyed priority blend events. This is done by calling ID3DXAnimationController::GetUpcomingPriorityBlend and ID3DXAnimationController::GetEventDesc. The way to handle all events is similar to handling keyed events in the tracks.

For reasons of simplicity, MultiAnimation does not preserve all of its animation controllers' states, but rather it saves only the animation set that its current track is playing. Consequently, if the Direct3D device object is released and re-created during an animation transition, the animation will not appear the same after the transition as before; it will appear as if the transition has been completed. In addition, all keyed events will not be restored after re-initialization.


OptimizedMesh Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

OptimizedMesh Sample

This OptimizedMesh Sample sample demonstrates the different types of meshes D3DX can load and optimize, as well as the different types of underlying primitives it can render. An optimized mesh has its vertices and faces reordered so that rendering performance can be improved.

Path

Source: | (SDK root)\Samples\C++\Direct3D\Meshes\OptimizedMesh
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\OptimizedMesh.exe

How the Sample Works

The sample can be divided into two areas: loading and rendering.

Loading

The loading code first initializes the mesh from data in the mesh file and calls OptimizeMeshData three times, each with a different optimization type. The optimization types used are D3DXMESHOPT_ATTRSORT, D3DXMESHOPT_VERTEXCACHE, and D3DXMESHOPT_STRIPREORDER. The optimization type is passed to ID3DXMesh::Optimize which reorders the mesh's vertices and faces accordingly.

After the meshes are set up, OptimizeMeshData creates a number of index buffers to hold the face information in the form of triangle strips. First, it calls D3DXConvertMeshSubsetToSingleStrip once for each material in the mesh. This returns an index buffer that represents the mesh triangles of that material with a single triangle strip. This index buffer can then be used to render the mesh. Next, OptimizeMeshData calls D3DXConvertMeshSubsetToStrips for each material in the mesh, and returns an index buffer representing a series of triangle strips. To return a single triangle strip, call D3DXConvertMeshSubsetToSingleStrip instead.

After the loading is complete, the sample has three sets of mesh data. Each set of mesh data includes an ID3DXMesh optimized with a different flag, one index buffer per material that represents the triangle subset as a single strip, and one index buffer per material that represents the subset as a series of strips.

Rendering

The rendering code is simpler compared to the loading code, because the mesh data sets have already been set up during the load time and are ready for use directly with rendering calls. To render, the sample calls DrawMeshData. This function takes a mesh data set and performs the rendering with it. Based on the current optimization setting, the appropriate mesh data set is passed to DrawMeshData.

Inside DrawMeshData, the mesh is rendered according to the primitive type selected by the user. For triangle lists, the mesh object's ID3DXMesh::DrawSubset is called once per material, because the mesh stores its geometry as triangle lists internally. For strips, DrawMeshData sets up primitive sources by calling IDirect3DDevice9::SetStreamSource and SetIndices(). The index buffer that is passed to IDirect3DDevice9::SetIndices is one of the index buffers created in OptimizeMeshData. If the mesh is to be rendered with a single triangle strip, the index buffer returned by D3DXConvertMeshSubsetToSingleStrip is used. If multiple triangle strips are desired, the buffer returned by D3DXConvertMeshSubsetToStrips is used instead. Once the vertex and index data are properly initialized, DrawMeshData renders the mesh by calling IDirect3DDevice9::DrawIndexedPrimitive.


PixelMotionBlur Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

PixelMotionBlur Sample

Motion blur adds realism to the scene. It has the perceptual effect of creating high-speed motion. Instead of rendering the geometry multiple times with different alpha values to create a blur effect, this sample shows off a realistic image-based motion blur effect. While the scene is rendered, the shaders record the per-pixel velocity relative to the previous frame. This per-pixel velocity is then used in a post-process pass to blur the pixels in the final image.

Path

Source: | (SDK root)\Samples\C++\Direct3D\PixelMotionBlur
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\PixelMotionBlur.exe

Background

In CMyD3DApplication::InitDeviceObjects, the sample:

  1. Loads the geometry with D3DXLoadMeshFromX.
  2. Calls D3DXComputeNormals to create mesh normals if there aren't any.
  3. Calls ID3DXMesh::OptimizeInplace to optimize the mesh for the vertex cache.
  4. Loads the textures using D3DXCreateTextureFromFile.
  5. Sets up the structures to describe the scenes.
  6. Sets up the camera.

In CMyD3DApplication::RestoreDeviceObjects, the sample:

  • Uses D3DXCreateTexture to create a D3DFMT_A8R8G8B8 render target that is the same size as the back buffer. This render target will be used by the pixel shader to render the scene's RGB color.
  • Uses D3DXCreateTexture to create two more render targets that are the same size as the back buffer, but are instead floating point 16 bits per channel D3DFMT_G16R16F. These textures are used by the pixel shader to render the pixel's velocity. One of these textures will hold the per-pixel velocity of the previous frame and the other will hold the per-pixel velocity of the current frame. The usage of these render targets are explained in more detail below.
  • Uses D3DXCreateEffectFromFile to load the .fx file into an ID3DXEffect and it caches the D3DXHANDLE to all the parameters that it will use every frame.
  • Creates a quad of vertices to be used in the post-processing pass. The quad has a single set of texture coordinates defined. These texture coordinates are set up so that the texels of the render target will map directly to pixels. How this quad is used is explained in more detail below.
  • Clears all of the render targets and sets some ID3DXEffect parameters to default values.

In CMyD3DApplication::FrameMove, the sample:

  • Calls FrameMove on the camera class so it can move the view matrix according the user input over time.
  • Swaps the pointers of the current frame's per-pixel velocity texture and the last frame's per-pixel velocity texture.
  • Animates the objects in the scene, based on a simple function of time.
  • Calls Sleep World Wide Web link based on a user's setting. This simulates time spent doing complex graphics, artificial intelligence (AI), physics, networking, etc. This is useful in this sample to slow down the frame rate and thus have more motion between each frame.

The sample essentially does two things in CMyD3DApplication::Render:

  1. Renders the scene's RGB into one render target, m_pFullScreenRenderTargetSurf, while it simultaneously renders the pixel's velocity into a second render target, m_pCurFrameVelocitySurf. This is possible only if the device caps report NumSimultaneousRTs greater than one; otherwise, this will need to be done in two passes.
  2. Does a post-process pass. It renders a full-screen quad to execute a pixel shader for each pixel. The pixel shader uses the render target with velocity information to blur the color of the pixel using a filter, based on the direction of pixel's velocity.

In more detail, the first part of CMyD3DApplication::Render uses the technique WorldWithVelocity, which uses a vs_2_0 vertex shader called WorldVertexShader. This vertex shader transforms vertex position into screen space, performs a simple N • L lighting equation, copies texture coordinates, and computes the velocity of the vertex by transforming the vertex by both the current and previous [world * view * projection] matrix and taking the difference. The difference will be the amount that this vertex has moved in screen space since the last frame. This per-vertex velocity is passed to the pixel shader by TEXCOORD1.

The technique WorldWithVelocity then uses a ps_2_0 pixel shader called WorldPixelShader, which modulates the diffuse vertex color with the mesh's texture color and writes this to COLOR0 and also writes the velocity of the pixel per frame in COLOR1. The render target for COLOR1 is D3DFMT_G16R16F, a floating point, 16-bits-per-channel texture. This render target records the amount the pixel has moved in screen space. The x direction change is the red channel, and the y direction change is in the green channel. The interpolation from per-vertex velocity to per-pixel velocity is done automatically because the velocity is passed to the pixel shader using a texture coordinate.

The second part of CMyD3DApplication::Render is where the motion blur actually happens. It uses the technique called PostProcessMotionBlur to do the post-process motion blur. The technique PostProcessMotionBlur uses a ps_2_0 pixel shader called PostProcessMotionBlurPS. This pixel shader does two texture look-ups to get the per-pixel velocity of the current frame (from CurFrameVelocityTexture) and of the last frame (from LastFrameVelocityTexture). If it just used the current frame's pixel velocity, then it wouldn't blur where the object was in the last frame because the current velocity at those pixels would be 0. Instead, you could filter neighboring pixels to see if any have a nonzero velocity. This requires a large number of texture look-ups which are limited and also may not work if the object has moved too far. So instead, the shader uses the larger of the current velocity or the last frame's velocity.

Once it has chosen the value to use as the pixel's velocity, it samples twelve times along the direction of the pixel's velocity. While sampling, it accumulates the color and divides by the number of samples to get the average color of all the samples and writes this as the final color for that pixel.

For example, here is an original unblurred scene:

And here's what a blurred scene looks like:

What are the pitfalls of this technique? Because the final post-process pixel shader is blurring the whole scene at once without knowledge of object edges, artifacts will arise if objects are occluded because the blur kernel from one object will sample color from another nearby object. For example:

Also, it will be noticeable if the pixels in an object have moved too far since the last frame.

To correct this, you can either increase the frame rate so that the pixels do not move as far between frames, or reduce the blur factor.


PostProcess Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

PostProcess Sample

This sample demonstrates some interesting image-processing effects that can be achieved interactively. Traditionally, image processing takes a significant amount of processor power on the host CPU, and is usually done offline. With pixel shaders, these effects can now be performed on the hardware more efficiently, allowing them to be applied in real time.

Note that the techniques shown here require pixel shader 2.0 and floating-point textures. Thus, not all cards support all of the postprocessing techniques.

Path

Source: | (SDK root)\Samples\C++\Direct3D\PostProcess
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\PostProcess.exe

Post Processing Effects

Image-processing techniques can improve the quality and realism of a scene, as well as achieve some specific effects, such as scene-wide blurring. In Microsoft Direct3D, image processing is usually performed as a postprocess after the rendering is completed. An application first renders its scene onto a texture, then processes the texture with a pixel shader to produce a different image with the enhancement or alteration. The use of pixel shaders makes this operation very efficient, so it can be performed in real time.

Postprocess effects can achieve interesting results particularly when a sequence of one or more postprocesses are applied to the original scene. Four such postprocess effects are included in this sample:

  • Blur - Combine a pixel color with surrounding pixel colors to blur the focus.
  • Bloom - Magnify bright spots in the image, as well as the area around the bright spots.
  • Depth of Field - Blur a pixel based on the pixel's depth or z value. Pixels very far away or very close get blurred.
  • Edge Glow - Use object normals to find an object's edge, and then use blur to help create a glow on the edges.

How the Sample Works

The scene contains a mesh object that can either be textured or environment-mapped, and a background in the form of a skybox cube. The sample can be divided into two parts: the first part renders scene data into three source render targets, and the second part uses pixel shaders to implement 2-D effects into three destination render targets.

Part 1 of the sample renders per-pixel data into three scene render targets: 0, 1, and 2.

Part 2 of the sample may use source material from the three scene render targets and the source render targets (0,1,2), and renders a full-screen quad with a pixel shader into the destination render targets (3,4,5). The six render targets in Part 2 are organized into three swap chains indicated by the curved arrows in the figure. When a pixel shader completes, the destination render target is swapped with its respective source render target. As a result, this sample can be used to cascade postprocessed effects. For instance, [Color] Monochrome is a postprocess effect that samples the color source texture (target 3), converts it to grayscale, then outputs the result to the other texture in the swap chain for the color channel (target 6).

Not all postprocess effects require all three render targets. However, using three render targets provides more options for the postprocess effects. Most of the time, the color render target gets updated and replaced. However, allowing other textures to be replaced gives more flexibility. Creative postprocess effects that change the normal and position textures are possible with the sample's architecture. The number of postprocess effects that can be rendered is only limited by system resources.

Running the Sample

When the sample is run, the user sees a typical Direct3D sample window and a Select Post Process Effects dialog that looks like this:

At the top of the dialog are two list controls. The first list displays the post-process effects that are available. The second list displays the active effects. After a scene is rendered, the active post-process effects are applied to the scene image in the order listed before displaying the result to the user. When the user modifies the active list, the visual change to the scene is immediately reflected.

Below the lists are buttons for changing the order the effects are applied. The button also clears the list. In the parameter section, some effects (such as bright pass) have parameters that the user can tweak to generate different visual appearances. The user can highlight an active post-process to adjust its parameters, if it has any.

At the bottom is the predefined post-process combinations that demonstrate how the different post-process effects can be used together to achieve even more interesting results.

The Effect Files

Each postprocess is implemented in one D3DX effect file. One technique, called PostProcess, exists in each file that is selected when its postprocess effect is needed. The technique can have one or more passes. Each pass specifies a pixel shader that does the actual work of image processing when invoked. The technique can have an integer annotation, named nRenderTarget, that specifies to which texture the pixel shader output should go. Assign it a value of 0, 1, or 2 to indicate that the pixel shader output is to be written to the color, normal, or position texture, respectively. If this annotation is missing, the output is assumed for the color texture.

The passes can optionally have two floating-point annotations named fScaleX and fScaleY. These two values specify the amount that the output image is scaled before written to the render target. After a postprocess scales the image to a size smaller than the render target texture, all subsequent postprocesses work with that image size until it is scaled again. This can have a significant performance boost, because the pixel shaders have fewer pixels to process. A common postprocessing practice is to scale down the image, apply postprocess effects to the sub-area of the texture, then scale up the result image to the original size. The performance gain from having fewer pixels to process usually far exceeds the penalty of performing the extra steps of scaling.

In the effect file, there are six texture objects with samplers from which the postprocess pixel shader will sample. g_txSrcColor, g_txSrcNormal, and g_txSrcPosition contain the colors, normals, and camera space positions from the result of the previous postprocess. g_txSceneColor, g_txSceneNormal, and g_txScenePosition are the result from the scene renderer. For the first postprocess in the sequence, these two sets of textures will be identical.

Often, the postprocess pixel shader will need to sample a source texture multiple times for a single destination pixel, each at a different location near the destination pixel. When this is the case, the effect file declares a kernel which is an array of texel offsets (float2) from the destination pixel. The effect file then defines another equally-sized array of float2. This second array has a string annotation, named ConvertPixelsToTexels, that contains the name of the first kernel array. When the sample loads the effect file and sees this annotation, it will translate the offsets from pixel coordinates to texel coordinates, which are compatible with the texture sampling functions such as tex2D. When the source texels are sampled, the offsets in the kernel are added to the texture coordinates to obtain the texel values near the destination pixel.

Some effects use parameters that the user can adjust. For instance, the Bright Pass effect has parameters that the user can tweak to give different visual appearances. Each PostProcess technique can define one or more annotations for this purpose. The maximum number of parameters supported by a single technique is four.

Annotation Name | Type | Description
Parameter0 | string | Contains the name of the variable that the user can adjust.
Parameter0Def | float4 | Default value for Parameter0. This is always a float4. If fewer than four floats are needed, use Parameter0Size to specify it.
Parameter0Size | int | Specifies how many components of Parameter0 are used. If this is 2, then only the first two components (x and y) are used.
Parameter0Desc | string | A string that describes this parameter.

The Sample Code

In the sample code, each postprocess effect type is represented by a CPostProcess class. This class encapsulates the effect files and provides a mechanism to activate the effect technique and change its parameters. At initialization, an array of CPostProcess objects is created, one for each postprocess effect file.

In the active postprocess effect list, each entry is represented by the CPProcInstance class. This class merely contains an index to the CPostProcess array to indicate the effect and the parameters to apply to this postprocess.

The Render method in the sample first renders the scene onto a set of render target textures. Three render targets are used simultaneously here for color, normal, and position. After that is complete, it calls PerformPostProcess, which handles every aspect of applying postprocesses to the scene image. After PerformPostProcess returns, the code calls IDirect3DDevice9::StretchRect to copy the postprocessing result to the device backbuffer so that the user can see the final image.

The postprocess work is done in two functions: PerformPostProcess and PerformSinglePostProcess.

The first thing that PerformPostProcess does is to set up a quad that defines how the rendering is done for the postprocess. Next, it creates a vertex buffer containing the quad created above. Then, it simply iterates through the active effect list and calls PerformSinglePostProcess for each entry in the list.

PerformSinglePostProcess applies a postprocess effect once to a render target texture. First, it initializes the textures and parameters for the effect. Then, it goes into a loop to render all passes of the technique. For each pass, it checks the scaling values and makes the necessary adjustment to the quad. After that, it renders the quad onto the render target texture with a IDirect3DDevice9::DrawPrimitive call. Finally, it swaps the render target texture with the corresponding source texture so that the next postprocess will have the correct textures from which to read and to which to write.

The following section lists the postprocesses included by this sample with a description of what each does.

Post Processes

Name | Implementation File | Description
[Color] Monochrome | PP_ColorMonochrome.fx | Converts the color image to monochrome.
[Color] Gaussian Blur Horizontal | PP_ColorGBlurH.fx | Performs Gaussian blur horizontally. The pixel shader achieves this by sampling several texels to the left and right of the source texture coordinate and performing a weighted average among the samples.
[Color] Gaussian Blur Vertical | PP_ColorGBlurV.fx | Performs Gaussian blur vertically. The pixel shader achieves this by sampling several texels to the top and bottom of the source texture coordinate and performing a weighted average among the samples.
[Color] Bloom Horizontal | PP_ColorBloomH.fx | Performs Gaussian blur horizontally and magnifies the image at the same time.
[Color] Bloom vertical | PP_ColorBloomV.fx | Performs Gaussian blur vertically and magnifies the image at the same time.
[Color] Bright Pass | PP_ColorBrightPass.fx | Performs a bright pass on the image. The Luminance is adjustable.
[Color] Tone Mapping | PP_ColorToneMapping.fx | Performs tone mapping on the image. The Luminance is adjustable.
[Color] Edge Detection | PP_ColorEdgeDetect.fx | Performs edge detection based on the color texture. For each pixel shader pass, the shader samples the texel at texcoord and its four neighboring texels. Then, it computes the differences between the texel and each of its neighbors. Finally, the shader sums the four absolute values of the differences and outputs it. The end result is that if a pixel has significantly different color from its neighbors, the postprocess result pixel will look bright.
[Color] Down Filter 4x | PP_ColorDownFilter4.fx | Performs a down-filtering pass. The dimension to work with scales to 0.25 times the original. A down filter shrinks the image.
[Color] Up Filter 4x | PP_ColorUpFilter4.fx | Performs an up-filtering pass. The dimension to work with scales to 4 times the original. An up filter enlarges the image.
[Color] Combine | PP_ColorCombine.fx | Adds the result from previous postprocesses and the original scene together and outputs the sum.
[Color] Combine 4x | PP_ColorCombine4.fx | Adds the result from previous postprocesses and the original scene together and outputs the sum, as well as performing a 4x up-filtering pass.
[Normal] Edge Detection | PP_NormalEdgeDetect.fx | Performs an edge detection similar to [Color] Edge Detection except that this technique compares the normals of the neighboring texels instead of colors. An advantage of this method over the colored-based one is that texture patterns will not be treated as edges.
DOF Combine | PP_DofCombine.fx | Performs a linear interpolation between the result texel from previous postprocesses and the original image based on the z coordinate at the pixel. A vector parameter representing the focal plane is used to determine the weights from the two source textures.
Normal Map | PP_NormalMap.fx | Takes the normal (texel on the normal texture) at the pixel and outputs it as the color. This is simply provided as a way of visualizing normals in a scene.
Position Map | PP_PositionMap.fx | Takes the position (texel on the position texture) at the pixel and outputs the z value as the color. This is simply provided as a way of visualizing depth information in a scene.

Blur

Blur is a very common image-based effect, and it is also rather straightforward. First, a down filter is performed to reduce the number of pixels that will be drawn (and therefore improve performance). Then, one horizontal blur and one vertical blur are performed. If more blurring is desired, repeat the blur effects. Finally, an up filter is performed to get the result image to the original size.

Bloom

The visual effect that bloom achieves is that bright spots in a scene get magnified and brighten the area around those spots. In order to achieve this, two passes of down filter are first performed. Because bringing out the bright spots does not require much detail, two passes of down filter boost the performance without sacrificing quality. Next, a bright pass is done. This postprocess picks up the areas in the image that are above a certain threshold, makes them white, then makes the rest of the image black. After that, two alternating passes each of horizontal bloom and vertical bloom are performed. Finally, two passes of up filter are performed, then the result is combined with the original image. Note that the second up filter pass and the combine are done in a single effect, [Color] Combine 4x.

Depth of Field

The depth of field (DOF) effect blurs the pixel of the image based on the z distance at that pixel. The steps that are needed to perform this are identical to that for the blur effect, except that a DOF Combine effect is added to the end of the sequence. Before the DOF combine, there are two textures available from which to sample: the blurred image from previous postprocesses and the original unblurred image. The DOF Combine examines the z coordinate at each pixel and computes a color by linearly interpolating between the two textures.

Edge Glow

This effect is very similar to bloom in concept, which is to take an image, make a part of it colored and everywhere else black, then combine with the original image. In this case, the area where it is emphasized is around the edges in the scene. First, a normal-based edge detection is performed. This produces white lines along the edges in the image (where normals change dramatically between neighboring pixels). Then, a blur effect is performed, by down-filtering, blurring, and up-filtering. Finally, the result is combined with the original image to produce the effect of glow along the edges. Note that the up-filtering and the final combination are done in a single effect.


ProgressiveMesh Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

ProgressiveMesh Sample

This ProgressiveMesh Sample sample shows how an application can use the D3DX progressive mesh functionality to simplify meshes for faster rendering. A progressive mesh is a specialized mesh object that can increase or decrease its geometry complexity, thereby providing flexibility when drawing the mesh so that performance can be maintained at a steady level. This feature is useful when providing level of detail (LOD) support in an application.

Note The simplification algorithm used to generate progressive meshes is based on Hugues Hoppe's SIGGRAPH papers.

Path

Source: | (SDK root)\Samples\C++\Direct3D\Meshes\ProgressiveMesh
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\ProgressiveMesh.exe

How the Sample Works

The functionalities of progressive meshes are provided by ID3DXPMesh. This mesh interface is similar to ID3DXMesh with additional methods for managing the mesh's complexity. To generate a progressive mesh, call D3DXGeneratePMesh. The progressive mesh can be used just like a regular mesh. To render it, the sample loops through its materials and calls ID3DXPMesh::DrawSubset to send the geometry subset to the device. To adjust the progressive mesh's LOD, the sample calls ID3DXPMesh::SetNumVertices passing it the desired number of vertices. A progressive mesh will simplify or enhance its geometry to match the number of vertices as closely as possible.

The sample also shows an optimization technique for progressive meshes by trimming multiple progressive meshes. Trimming limits the maximum and minimum number of vertices or faces a progressive mesh can have. The sample divides the range (maximum - minimum) of the progressive mesh vertices into ten sub-ranges. After the sub-ranges are computed, the sample creates ten progressive meshes by calling ID3DXPMesh::ClonePMeshFVF on the original mesh. Then the sample calls ID3DXPMesh::TrimByVertices on each progressive mesh using a different sub-range. After setting the range of vertices, the sample calls ID3DXPMesh::OptimizeBaseLOD to optimize the mesh's vertex and index buffers. Whenever the user changes the vertex count, the new vertex count is checked against the range of the optimized progressive mesh set, and the mesh whose range contains the desired vertex count is selected by calling ID3DXPMesh::SetNumVertices.

The advantage of using multiple meshes is that adjusting LOD is more efficient than using a single progressive mesh. The performance load of changing LOD is directly proportional to the difference in complexity (represented by vertex count in this sample). Simplifying a mesh by reducing the number of vertices by ten takes less time than reducing the vertex count by 100. That is why this sample achieves better performance by trimming several progressive meshes, each of which covers a smaller LOD range.


PRTPerVertex Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

PRTPerVertex Sample

Similar to the PRTPerVertex Sample, this sample demonstrates how to use ID3DXPRTEngine, a precomputed radiance transfer (PRT) simulator that uses low-order spherical harmonics (SH). The sample then demonstrates how to compress the results with clustered principal component analysis (CPCA) and view the compressed results with arbitrary lighting in real time with a vs_1_1 vertex shader.

SHPRTVertex sample screenshot

Path

Source: | (SDK root)\Samples\C++\Direct3D\PRTPerVertex
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\PRTPerVertex.exe

Why This Sample Is Interesting

PRT using low-order SH basis functions has a number of advantages over typical diffuse (N • L) lighting. Area light sources and global effects such as interreflections, soft shadows, self shadowing, and subsurface scattering can be rendered in real time after a precomputed light transport simulation. CPCA allows the results of the simulator to be compressed so the shader does not need as many constants or per-vertex data.

Overview

The basic idea is first to run a PRT simulator offline as part of the art content creation process and save the compressed results for later real-time use. The light transport simulator models global effects that would typically be very difficult to do in real time. The real-time engine evaluates the lights in terms of SH basis functions and sums them up into a single set of SH basis coefficients describing the entire lighting environment. It then uses a vertex shader to arrive at the vertex's diffuse color by combining the compressed simulator results and the lighting environment. Because the offline simulator did the work of computing the interreflections and soft shadows, this technique is visually impressive, efficient, and can be used for real-time lighting.

For more detail about the math behind PRT, CPCA, and SH, see PRT Equations and the following references.

  • Sloan, Peter-Pike, Jan Kautz, and John Snyder. "Precomputed Radiance Transfer for Real-Time Rendering in Dynamic, Low-Frequency Lighting Environments" World Wide Web link. ACM Transactions on Graphics (TOG), Proceedings of the 29th Annual Conference on Computer Graphics and Interactive Techniques (SIGGRAPH), pp. 527-536. New York, NY: ACM Press, 2002.
  • Sloan, Peter-Pike, Jesse Hall, John Hart, and John Snyder. "Clustered Principal Components for Precomputed Radiance Transfer" World Wide Web link. ACM Transactions on Graphics (TOG), Vol. 22, Issue 3 (SIGGRAPH), pp. 382-391. New York, NY: ACM Press, July 2003.
  • Green, Robin. "Spherical Harmonic Lighting: The Gritty Details" World Wide Web link. Game Developers' Conference, San Jose, CA, March 2003.

Related Topics

  • Precomputed Radiance Transfer


ShadowMap Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

ShadowMap Sample

This sample demonstrates one popular shadowing technique called shadow mapping. A shadow map (in the form of a floating-point texture) is written with the scene's depth information with the camera placed at the light's position. Once generated, the shadow map is projected onto the scene during rendering. The depth values in the scene are compared with those in the shadow map. If they do not match for a particular pixel, then that pixel is in shadow. Shadow mapping is a very efficient real-time shadow casting technique.

Note

This sample requires ps_2_0 which supports floating-point textures. On cards that do not support ps_2_0, the sample will revert to a reference device which will degrade performance, but is useful for verifying functionality.

Path

Source: | (SDK root)\Samples\C++\Direct3D\ShadowMap
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\ShadowMap.exe

How the Sample Works

Rendering real-time shadows has been an advanced topic in computer graphics. Shadows enhance the realism of the scene and give better spatial cue to the viewers. The two most common shadow-rendering techniques are shadow volumes and shadow maps. The major advantage of using shadow maps over shadow volumes is efficiency since a shadow map only requires the scene to be rendered twice. There is no geometry-processing needed and no extra mesh to generate and render. An application using shadow maps can therefore maintain good performance regardless of the complexity of the scene.

The concept of shadow mapping is straight-forward. First, the scene is rendered to a texture from the light's perspective. This texture is called a shadow map and is generated from specialized vertex and pixel shaders. For each pixel, the pixel shader writes the pixel depth instead of the pixel color. When the scene is rendered, the distance between each pixel and the light is compared to the corresponding depth saved in the shadow map. If they match, then the pixel is not in shadow. If the distance in the shadow map is smaller, the pixel is in shadow, and the shader can update the pixel color accordingly. The most suitable type of light to use with shadow maps is a spotlight since a shadow map is rendered by projecting the scene onto it.

During initialization, the sample creates a texture of the format D3DFMT_R32F to be used for the shadow map. The format is chosen because the shadow map only requires one channel, and 32-bits will provide good precision. Rendering is done in two parts: the first part constructs the shadow map, and the second part renders the scene with shadows.

Constructing the Shadow Map

The shadow map is constructed by rendering the scene with the shadow map texture as the render target. The shaders used for this process are VertShadow and PixShadow. VertShadow transforms the input coordinates to projected light space (the projected coordinates as if the camera is looking out from the light). The vertex shader passes the projected z and w to the pixel shader, as texture coordinates, so that the pixel shader has a unique z and w for each pixel. PixShadow outputs z / w to the render target. This value represents the depth of the pixel in the scene, and has a range from 0 to 1. At the near clip plane, it is 0; at the far clip plane, it is 1. When the rendering completes, the shadow map contains the depth values for each pixel.

Rendering with the Shadow Map

The shadowed scene is rendered with two shaders: VertScene and PixScene. VertScene transforms position to projected coordinates and passes the texture coordinates to the pixel shader. In addition, it outputs: the vertex coordinates in view space, the vertex normal in view space, and the vertex coordinates in projected light space. The first two are used for lighting computation. The vertex coordinate in projected light space is the shadow map coordinate. The coordinate is obtained by transforming the world position to light view-space using a view matrix as if the camera is looking out from the light, then transforming the position by the projection matrix for the shadow map.

The pixel shader tests each pixel to see if it is in shadow. First, a pixel is tested to see if it is within the cone of light from the spotlight using the dot product of the light direction and the light-to-pixel vector. If the pixel is within the cone, the shader checks to see if its in shadow. This is done by converting the range of vPosLight (between 0 and 1 to match a texture address range), inverting y (positive y direction is down rather than up when addressing a texture), and then using the coordinate to perform a shadow map look-up.

For each texture lookup, the pixel shader does a 2-by-2 percentage closest filtering (by fetching from each of the four closest texels). For each texel fetched, the texel value is compared to the current pixel depth from the light, or vPosLight.z / vPosLight.w. If the value from the shadow map is smaller, then the pixel is in shadow and the lighting amount for this texel is 0. Otherwise, the lighting amount for this texel is 1. After this is done for all four texels, a bilinear-interpolation is done to calculate the lighting factor for the pixel. The light source will be scaled by this factor to provide the darkening effect of the shadow.

Limitations

One of the limitations is that the shadows generated with shadow maps do not have sharp edges like some shadows in real life, or shadows generated with shadow volumes. Shadows with shadow maps generally have aliasing near the shadow edges that can be noticeable when viewed close-up, as shown in the figure below. This is an inherent behavior of shadow mapping, because it is an image-based technique. Filtering helps reduce the aliasing, but it cannot completely eliminate the artifact.

Another type of artifact with shadow maps is caused by the limited precision of depth values. Shadow mapping technique compares two depth values to detect shadows. When the shadow caster and the shadow receiver are close to each other, the limited precision for depth values may not be sufficient to accurately compare the depths of the two objects. Consequently, area that is in shadow may be mistakenly rendered with light, and vice versa, as illustrated in the figure below.

In addition, shadow maps do not work well with point light sources. However, this can be overcome by using a cube texture whose faces form 6 shadow maps around the light source. When constructing the shadow map in this setup, the application first renders the scene 6 times, with each pass rendering depth information onto one face of the cube texture. Then, the scene can be rendered using the cube shadow map.


ShadowVolume Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

ShadowVolume Sample

The sample demonstrates one common technique for rendering real-time shadows called shadow volumes. The shadows in the sample work by extruding faces of the occluding geometry (that are facing away from light) to form a volume that represents the shadowed area in 3D space. The stencil buffer is used as a mask for rendering additional geometry, and is updated as geometry is rendered.

Rendering real-time shadows has been an advanced topic in 3D computer graphics. This sample implements the shadow volume technique using the stencil buffer and a vertex shader. First, the occluding geometry is examined, and a different geometry (that represents the shadow volume) is created. When rendering the scene, the shadow volume geometry is rendered with a vertex-extruding vertex shader using the depth-fail stencil technique. The stencil buffer is updated during this process. Using the stencil buffer as a mask, pixels that lie in the shadow volume do not receive lighting. The depth-fail shadow technique requires that the shadow volume must be a closed volume.

The sample supports up to 6 lights and can render the scene three ways:

  • With shadows as you would normally view the scene.
  • With shadows and the shadow volume.
  • With the shadow volume only, but no shadows. This option renders a color code for each pixel based on the complexity of the shadow volume at each pixel (i.e., how many times a pixel is rendered with the shadow volume).

Path

Source: | (SDK root)\Samples\C++\Direct3D\StencilBuffer\ShadowVolume
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\ShadowVolume.exe

How the Sample Works

A shadow volume of an object is the region in the scene that is covered by the shadow of the object caused by a particular light source. When rendering the scene, all geometry that lies within the shadow volume should not be lit by the particular light source. A closed shadow volume consists of three parts: a front cap, a back cap, and the side. The front and back caps can be created from the shadow-casting geometry: the front cap from light-facing faces and the back cap from faces facing away from light. In addition, the back cap is translated a large distance along the direction of light, to make the shadow volume long enough to cover enough geometry in the scene. The side is usually created by first determining the silhouette edges of the shadow-casting geometry then generating faces that represent the silhouette edges extruded for a large distance along the light direction. Figure 1 shows different parts of a shadow volume.

Figure 1: Creation of a shadow volume. The front cap (blue) and back cap (red) are created from the occluder's geometry. The back cap is translated to prolong the shadow volume, and the side faces (purple) are generated to enclose the shadow volume.

This sample demonstrates a specific implementation of shadow volumes. Instead of determining the silhouette and generating the shadow volume geometry on the CPU, the sample first generates a mesh that can represent the shadow volume of the occluding geometry regardless of light direction and uses a vertex shader to perform vertex extrusion as the shadow volume mesh is rendered. The underlying idea is that for triangles that face the light, we can use them as-is for the front cap of the shadow volume. For triangles that face away from the light, their vertices are translated a large distance along the light direction at each vertex, then they can be used as the back cap. However, a problem occurs at silhouette edges where one triangle faces the light and its neighbor faces away from the light. In this situation, each triangle causes its vertices to be processed differently, and it must be determined how the vertices that are shared by the two triangles should be handled.

To solve this, the two triangles are split by duplicating the shared vertices so that each triangle has its own unique three vertices. When the common edge between the triangles becomes a silhouette edge, one triangle stays where it is and the other moves along the light direction. This, however, creates a gap between the two triangles, but a closed shadow volume cannot have any gap or hole. This can be fixed by adding a quad to the shadow volume mesh between the two triangles. The edge that is shared by the two triangles gets split, and then the four vertices define the quad. Before extrusion, the quad is degenerate because the triangles are next to each other. However, when the triangles are far apart, the quad is stretched and automatically forms the side of the shadow volume. Figure 2 illustrates this process.

Figure 2: The process of splitting two faces. Left: The two faces share vertices A and B. Center: Generate vertices A' (duplicate of A) and B' (duplicate of B) and then let one of the faces reference them. Right: Generate a quad using vertices A, A', B, and B'. For illustration purpose, A' and B' are drawn at a distance from A and B. In actuality, A and A' are coincident in the mesh's vertex buffer, and so are B and B'. The newly created quad would therefore be degenerate.

Generating the Shadow Volume Mesh

The biggest advantage of generating a static mesh for the shadow volume and having a vertex shader extrude its vertices is that very few CPU cycles are required to render shadows. The shadow volume mesh, once generated, does not need to change no matter where the light position is because the vertex shader can extrude vertices in the correct direction as it receives the vertices from the sample. The function that generates shadow volumes is called GenerateShadowMesh. This function takes an input mesh and outputs a different mesh that represents the shadow volume for the input mesh. There are several things that this function does in order to generate the proper shadow volume for the input mesh.

For every edge in the input mesh, the function must split it up into two edges, effectively separating the two faces that share the edge. Then, it creates a quad (or two triangles) that connects the two split edges. Figure 3 visualizes this process. By default, these quads are degenerate, because the split edges are co-linear. However, when one face is extruded and the other is not, the quad between them gets stretched and forms the side of the shadow volume.

Figure 3: Mesh faces (green) are split, and then quads (red) are inserted.

The algorithm that creates the shadow volume mesh works by iterating through the faces in the input mesh. For each face iterated, three things happen.

  • First, three new vertices and one new face are generated for the shadow volume mesh. Each face must have its own unique three vertices because the faces are separated by degenerate quads.
  • Then, the normal of the new vertices are computed to be the normal of the new face, as illustrated in figure 4. The reason that this is necessary is because vertex extrusion is done by a vertex shader, and vertex shaders only see vertex normals, not face normals. By setting the vertex normals to match their face normals, the vertex shader will correctly extrude vertices when the faces they belong are facing away from the light.
  • Finally, the three edges of a face are added to an edge mapping table. An edge mapping entry contains one source edge, representing the edge in the input mesh, and two output edges, representing the split edges in the output mesh. Essentially, the table records the edges in the source mesh and what edges they split into in the output mesh. This information is needed when the quads are generated later. For each edge of the added face, the algorithm looks through the edge mapping table, and if it cannot find an existing entry for the source edge, it creates one and initializes the source edge and one output edge of the edge mapping entry. However, if it finds that the source edge already has an entry in the table, then it has the four vertices of the quad for this edge, so it adds the two faces for the quad to the output mesh and remove the edge mapping entry from the table.

Figure 4: Vertex normals are set up to be identical as the face normals.

At this point, the output mesh contains all of the faces that are in the input mesh, and every edge in the input mesh has been converted to a quad in the output mesh. There is also a list of edges in the mapping table that represents the edges that are not shared in the input mesh. The existence of these edges implies that the input mesh has holes in it, and the holes must be patched so that the shadow mesh becomes a closed volume. This is essential for rendering the shadows with the depth-fail stencil technique. The patching algorithm looks through the mapping table and finds two edges that share a vertex in the original mesh. Then it patches the hole by generating a new face and three new vertices out of the two neighboring edges' vertices. After that, the code generates two quads to connect the patch face to the existing geometry of the output mesh. This process is illustrated in figure 5.

Figure 5: Creating a colsed volume shadow mesh.

Rendering Shadows

At the top level, the rendering steps look like the following:

  • If ambient lighting is enabled, render the entire scene with ambient only.
  • For each light in the scene, do these:
    • Disable depth-buffer and frame-buffer writing.
    • Prepare the stencil buffer render states for rendering the shadow volume.
    • Render the shadow volume mesh with a vertex extruding shader. This sets up the stencil buffer according to whether or not the pixels are in the shadow volume.
    • Prepare the stencil buffer render states for lighting.
    • Prepare the additive blending mode.
    • Render the scene for lighting with only the light being processed.

The lights in the scene must be processed separately because different light positions require different shadow volumes, and thus different stencil bits get updated. Here is how the code processes each light in the scene in details. First, it renders the shadow volume mesh without writing to the depth buffer and frame buffer. These buffers need to be disabled because the purpose of rendering the shadow volume is merely setting the stencil bits for pixels covered by the shadow, and the shadow volume mesh itself should not be visible in the scene. The shadow mesh is rendered using the depth-fail stencil shadow technique and a vertex extruding shader. In the shader, the vertex's normal is examined. If the normal points toward the light, the vertex is left where it is. However, if the normal points away from the light, the vertex is extruded to infinity. This is done by making the vertex's world coordinates the same as the light-to-vertex vector with a W value of 0. The effect of this operation is that all faces facing away from the light get projected to infinity along the light direction. Since faces are connected by quads, when one face gets projected and its neighbor does not, the quad between them is no longer degenerate. It is stretched to become the side of the shadow volume. Figure 6 shows this.

Figure 6: The faces of the shadow volume that face away from light (left, shown in red) have their vertices extruded by the vertex shader to create a volume that encloses area covered by shadows (right).

When rendering the shadow mesh with the depth-fail technique, the code first renders all back-facing triangles of the shadow mesh. If a pixel's depth value fails the depth comparison (usually this means the pixel's depth is greater than the value in the depth buffer), the stencil value is incremented for that pixel. Next, the code renders all front-facing triangles, and if a pixel's depth fails the depth comparison, the stencil value for the pixel is decremented. When the entire shadow volume mesh has been rendered in this fashion, the pixels in the scene that are covered by the shadow volume have a non-zero stencil value while all other pixels have a zero stencil. Lighting for the light being processed can then be done by rendering the entire scene and writing out pixels only if their stencil values are zero.

Figure 7: The depth-fail technique.

Figure 7 illustrates the depth-fail technique. The orange block represents the shadow receiver geometry. Regions A, B, C, D and E are five areas in the frame buffer where the shadow volume is rendered. The numbers indicate the stencil value changes as the front and back faces of the shadow volume are rendered. In region A and E, both the front and back faces of the shadow volume fail the depth test, and therefore both cause the stencil value to change. For region A, the orange shadow receiver is causing the depth test to fail, and for region E, the cube's geometry is failing the test. The net result is that stencil values in this region stay at 0 after all faces are rendered. In region B and D, the front faces pass the depth test while the back faces fail, so the stencil values are not changed with the front faces, and the net stencil changes are 1. In region C, both the front and back faces pass the depth test, and so neither causes the stencil values to change, and the stencil values stay at 0 in this region. When the shadow volume is completely rendered, only the stencil values in regions B and D are non-zero, which correctly indicates that regions B and D are the only shadowed areas for this particular light.

Performance Considerations

Performing vertex extrusion in a vertex shader provides some advantages. Once the shadow volume mesh is generated for a mesh geometry, the application can send the mesh to the 3D device for rendering without modifying it in any way, thus removing the need to perform silhouette determination on the host CPU. However, this technique is not without its shortcoming. The static shadow volume mesh tends to have more vertices than the visible geometry. This is because the geometry needs to have its faces separated and quads generated to produce a valid, closed shadow volume. A completely welded mesh would have a shadow mesh with three times the number of vertices. The increase in vertex count could be so significant that it actually reduces performance by processing them in the vertex shader. Applications are encouraged to implement alternative techniques, such as silhouette determination on the CPU, and then compare the performance result to reach a reasonable conclusion about which technique should be used for each shadow-casting object in the scene.

It is beneficial to use separate meshes for the shadow-casting geometry and its shadow volume. If the additional vertices and faces reside in the original mesh, the application would unnecessarily need to process the extra vertices when rendering the geometry, even when these vertices do not serve any purpose during this process. These extra vertices would also come with the vertex data that do not get used when rendering the shadow, such as texture coordinates and material colors. For the situation when less accurate shadows are adequate, a less-detailed version of the mesh can be used for shadow volume rendering.

Using separate meshes may increase the memory requirement for the geometry. This is the case in the sample, because ID3DXMesh is used for the mesh objects. However, applications can eliminate the need for additional memory by directly utilizing vertex buffers, index buffers, and vertex streams. First, the scene mesh's vertex buffer needs to be split into multiple vertex buffers so that one vertex buffer contains the positions and normals, while other vertex buffers contain the rest of the vertex data, such as material attributes, texture coordinates, and blending parameters. When rendering the geometry, the application must set up multiple vertex streams, one for each vertex buffer. Next, after the shadow volume mesh is generated, the application must reorder its vertex buffer and fix-up its index buffer, so that all vertices that are originally in the input mesh come before the newly created ones. When this is done, the input mesh's vertex buffer for positions and normals would be identical to the first half of the shadow mesh's vertex buffer. Therefore, the input mesh's vertex buffer can be released and the mesh can simply reference the shadow mesh's vertex buffer. Note that the two meshes still require different index buffers. See figure 8 for a visualization of this buffer-sharing arrangement.

Figure 8: Sharing vertex data between the scene mesh and shadow volume mesh. The scene mesh here (enclosed by the green rectangle) has N vertices that span across two distinct vertex buffers, one for positions and normals (shown in red) and the other for everything else (shown in blue). The shadow volume mesh (enclosed by the orange rectangle) has a vertex count higher than the scene mesh. Therefore, its vertex buffer (in red) contains more than N vertices, of which the first N vertices are shared by the scene mesh.

The drawback of using this technique is that the application must manage the vertex and index buffers of the meshes on its own, and can no longer make use of the ID3DXMesh interface for these. Each application should weigh this trade-off based on its own needs and goals.

Finally, there is another area that could call for some performance optimization. As shown earlier, the rendering algorithm with shadow volumes requires that the scene be rendered in multiple passes (one plus the number of lights in the scene, to be precise). Every time the scene is rendered, the same vertices get sent to the device and processed by the vertex shaders. This can be avoided if the application employs deferred lighting with multiple rendertargets. With this technique, the application renders the scene once and outputs a color map, a normal map, and a position map. Then, in subsequent passes, it can retrieve the values in these maps in the pixel shader and apply lighting based on the color, normal and position data it reads. The benefit of doing this is tremendous. Each vertex in the scene only has to be processed once (during the first pass), and each pixel is processed exactly once in subsequent passes, thus ensuring that no overdraw happens in these passes.

Shadow Volume Artifact

It is worth noting that a shadow volume is not a flawless shadow technique. Aside from the high fill-rate requirement and silhouette determination, the image rendered by the technique can sometimes contain artifacts near the silhouette edges, as shown in figure 9. The prime source of this artifact lies in the fact that when a geometry is rendered to cast shadow onto itself, its faces are usually entirely in shadow or entirely lit, depending on whether the face's normal points toward the light. Lighting computation, however, uses vertex normals instead of face normals. Therefore, for a face that is near-parallel to the light direction, it will either be all lit or all shadowed, when in truth, only part of it might really be in shadow. This is an inherent flaw of stencil shadow volume technique, and should be a consideration when implementing shadow support. The artifact can be reduced by increasing mesh details, at the cost of higher rendering time for the mesh. The closer to the face normal that the vertex normals get, the less apparent the artifact will be. If the application cannot reduce the artifact down to an acceptable level, it should also consider using other types of shadow technique, such as shadow mapping or pre-computed radiance transfer.

Figure 9: Shadow volume artifact near the silhouette edges.

Figure 10: Displaying the shadow volume reveals that the jagged edge is caused by faces that are treated as being entirely in shadow when they are actually only partially shadowed.


SkinnedMesh Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

SkinnedMesh Sample

The SkinnedMesh Sample illustrates mesh animation with skinning using D3DX. Skinning is an animation technique that takes data organized in a skeletal-mesh hierarchy and applies geometry blending to transform mesh vertices. The geometry blending generates smooth surfaces with fewer artifacts.

Path

Source: | (SDK root)\Samples\C++\Direct3D\Meshes\SkinnedMesh
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\SkinnedMesh.exe

Sample Overview

Microsoft Direct3D and D3DX can be used to animate meshes. Applications can load X files containing animation data, then control and render the animated meshes. This sample demonstrates five skinning techniques: fixed-function non-indexed, fixed-function indexed, software, assembly shader, and high-level shader language (HLSL) shader. Each technique has its advantages and disadvantages, and application developers should weigh these and choose the appropriate techniques for the needs of their application.

Skinning is a popular animation technique that is modeled like a human body. Skinning uses a set of interconnected bones (or frames) that form a hierarchy. Moving or rotating the bones cause the mesh surface to move or rotate. The mesh surface is analagous to the skin of the human body. Each point (or vertex) on the mesh surface is associated with a number of bones. Its position is determined by the position of the associated bones. For instance, consider the hierarchy in figure 1 that describes a human limb:

Clavicle
  Upper Arm
    Forearm
      Hand
        Finger0
        Finger1
        Finger2
        Finger3
        Finger4

Figure 1. The hierarchy of a human limb.

The skin at the elbow is influenced by the upper arm bone and the forearm bone. If the upper arm remains stationary and the forearm moves, the elbow skin position is affected; the same is true when holding the forearm stationary and moving the upper arm. It can be concluded that the skin at the elbow is associated with both the upper arm and forearm bones. Transforming vertices with multiple matrices are done with geometry blending. Each matrix has a blending weight ranging from 0 to 1, with the sum of all blending weights equal to 1. The blending operation is carried out by first transforming the vertex with each matrix, yielding several transformed vertex coordinates. Then, these coordinates are interpolated based on the corresponding blending weights. Vertices can have different blending weights even if they are influenced by the same bones. This geometry blending allows surfaces to stay smooth when animated.

Furthermore, any movement by an ancestor bone may affect the skin position. For instance, if both the upper arm and forearm bones remain stationary (that is, no rotation), and the clavicle bone moved, the skin between the upper arm bone and the forearm bone should change position. This explains why the child bones are modeled in a hierarchy to generate this dependency.

Figure 2. The effect of bone offset transformation on the character's left forearm.

  • Left: The character as it is stored on the disk.
  • Middle: The bone offset transformation changes the vertex coordinates from the mesh space to bone space.
  • Right: Now that vertices are in bone space, animation transformation can be performed. In this case, a rotation is applied to the forearm.

How the Sample Works

The first step in loading a mesh is to call D3DXLoadMeshHierarchyFromXInMemory. This call is similar to D3DXLoadMeshHierarchyFromX, in that they both load a mesh from an X file into memory. However, D3DXLoadMeshHierarchyFromXInMemory returns the mesh in the form of a hierarchy tree composed of bones (or frames). This form matches how the mesh is structured in the X file. In D3DX, an animatable mesh is composed from a frame hierarchy. At the very top, there is a root frame. The root frame has one or more child frames, each child frame has its own child frames, and so forth.

A frame in the hierarchy is represented by a structure derived from a D3DXFRAME. An application may store private information with each frame by deriving the format of each hierarchy node from D3DXFRAME. D3DXFRAME, as shown in figure 3, provides the bare minimum data required by the hierarchy. Each frame has a name, a transformation matrix, and a mesh container for the geometry data. Each frame also contains a link to a sibling and a child frame.

typedef struct _D3DXFRAME {
    LPSTR Name;
    D3DXMATRIX TransformationMatrix;
    LPD3DXMESHCONTAINER pMeshContainer;
    struct _D3DXFRAME *pFrameSibling;
    struct _D3DXFRAME *pFrameFirstChild;
} D3DXFRAME, *LPD3DXFRAME;

Figure 3. D3DXFRAME is the building block of a mesh hierarchy.

The SkinnedMesh Sample derives D3DXFRAME and augments the struct with another matrix named a combination matrix which will be used when advancing the animation.

In a hierarchy, some frames will have valid container values, which are the mesh geometry data. When rendering the mesh, the container is drawn regardless of its location in the mesh hierarchy. Similar to a frame, an application should define its own mesh container type by deriving from a D3DXMESHCONTAINER, shown in figure 4.

typedef struct _D3DXMESHCONTAINER {
    LPSTR Name;
    D3DXMESHDATA MeshData;
    LPD3DXMATERIAL pMaterials;
    LPD3DXEFFECTINSTANCE pEffects;
    DWORD NumMaterials;
    DWORD *pAdjacency;
    LPD3DXSKININFO pSkinInfo;
    struct _D3DXMESHCONTAINER *pNextMeshContainer;
} D3DXMESHCONTAINER, *LPD3DXMESHCONTAINER;

Figure 4. A standard mesh container.

All data fields in a D3DXMESHCONTAINER also exist for an ordinary mesh, except for Name and pSkinInfo. Name is a unique string that identifies the mesh container in the hierarchy. pSkinInfo is an object that holds bone matrices information. This information consists of the bones by which each vertex is influenced, and is important when setting up the mesh into attribute groups.

In addition to returning a mesh hierarchy, D3DXLoadMeshHierarchyFromX returns an ID3DXAnimationController interface associated with the mesh frames. The animation controller controls the flow of the animation available to the mesh; use it specify what animation sequences to play and how fast each sequence plays.

Because the two fundamental structures of a frame hierarchy are often derived and defined by the application itself, the application has to define functions that handle the allocation and deallocation of the frames and mesh containers. ID3DXAllocateHierarchy is an interface that describes how the application can define such allocation and deallocation functions. To use it, an application first defines a class derived from ID3DXAllocateHierarchy. Then, implement the four methods declared by the interface: ID3DXAllocateHierarchy::CreateFrame, ID3DXAllocateHierarchy::DestroyFrame, ID3DXAllocateHierarchy::CreateMeshContainer, and ID3DXAllocateHierarchy::DestroyMeshContainer. The create methods allocate a new instance of frame or mesh container struct, allocate other resources as necessary, initialize the struct fields, and return the object instance back to the caller.

The destroy methods should free all resources allocated during the creation of the frame or mesh container, including the frame or mesh container instance itself. In the SkinnedMesh Sample, ID3DXAllocateHierarchy::CreateMeshContainer also initializes the application-defined fields in the mesh container structure. The structure is shown in figure 5.

struct D3DXMESHCONTAINER_DERIVED: public D3DXMESHCONTAINER
{
    LPDIRECT3DTEXTURE9*  ppTextures;

    // SkinMesh info
    LPD3DXMESH           pOrigMesh;
    LPD3DXATTRIBUTERANGE pAttributeTable;
    DWORD                NumAttributeGroups;
    DWORD                NumInfl;
    LPD3DXBUFFER         pBoneCombinationBuf;
    D3DXMATRIX**         ppBoneMatrixPtrs;
    D3DXMATRIX*          pBoneOffsetMatrices;
    DWORD                NumPaletteEntries;
    bool                 UseSoftwareVP;
    DWORD                iAttributeSW;
};

Figure 5. A derived mesh container.

After retrieving the bone offset matrices from pSkinInfo, ID3DXAllocateHierarchy::CreateMeshContainer calls GenerateSkinnedMesh to set up the mesh hierarchy for animating and rendering. GenerateSkinnedMesh divides the mesh vertices into groups based on the skinning method used, which makes rendering the mesh optimal.

After D3DXLoadMeshHierarchyFromX returns, the sample calls SetupBoneMatrixPointers. This function traverses the frame hierarchy to search for mesh containers. When it finds a mesh container, it calls SetupBoneMatrixPointersOnMesh to initialize the ppBoneMatrixPtrs member of the mesh container. This member is an array of matrix pointers, where each element in the array points to a particular frame matrix. This array provides a quick lookup for frame matrices by frame index. Because the hierarchy is structured as a tree, performing an index-to-matrix lookup is not a straightforward process. This matrix serves as a helper lookup table for efficiency.

Rendering the Mesh

Rendering the animated mesh is a two-step process: setting up the matrices and the actual rendering. To set up the matrices, ID3DXAnimationController::AdvanceTime is called first. This method takes a TimeDelta parameter that indicates how much to advance since the last call, then it updates the frame hierarchy's transformation matrices with matrices that correspond to the bone positions at that instance of time. These matrices contain transformation with respect to their parent frames, consisting of a scaling plus rotation plus translation transformation. Next, the sample calls UpdateFrameMatrices. This function updates the frame hierarchy's combined transformation matrix. The combined transformation matrix holds the product of all of the ancestor frames' matrices, including the frame's own matrix. Recall that bones are influenced by their parent bones, and the parent bones are influenced by the grandparent bones, and so forth. Combining all influencing matrices makes the combined transformation matrix absolute, or relative to the world, which is more suitable for rendering. UpdateFrameMatrices achieves this by recursively traversing the hierarchy tree. For each frame, it writes the product of the transformation matrix and the parent's matrix to the combined transformation matrix. Then it calls UpdateFrameMatrices on its sibling and first child nodes, passing its parent matrix to the sibling and passing its own combined transformation matrix as the parent matrix for the children.

The actual rendering, like all other samples, starts in OnFrameRender. The rendering of the mesh is done by the DrawFrame. This function takes a pointer to a frame node, draws the frame's mesh if one exists, then recursively calls itself again with the frame's sibling and children. The result is that all mesh containers in the frame hierarchy will be drawn when the top DrawFrame returns. When a frame holds a valid mesh container, DrawFrame calls the DrawMeshContainer, which is where all the mesh rendering takes place.

DrawMeshContainer renders the mesh in different ways:

  • Rendering with Fixed-Function Non-Indexed Skinning
  • Rendering with Fixed-Function Indexed Skinning
  • Rendering with Shader-Based Skinning
  • Rendering with Software Skinning

Rendering with Fixed-Function Non-Indexed Skinning

When this skinning technique is active, the device can load up to four world matrices at a time and transform the vertices influenced by those four matrices. After these vertices are rendered, a different set of matrices can be loaded, and vertices influenced by the second set of matrices can be rendered. This rendering process continues until all faces of the mesh are rendered. GenerateSkinnedMesh calls ID3DXSkinInfo::ConvertToBlendedMesh which divides a mesh's faces into attribute groups. Each attribute group identifies geometry influenced by a particular set of four matrices. At render time, each attribute group can be rendered with a single IDirect3DDevice9::DrawIndexedPrimitive.

For non-indexed skinning, DrawMeshContainer loops through each attribute group in the mesh and renders one attribute group at a time. The mesh is set up so that each attribute group is influenced by up to four matrices. Before the vertices can be sent to the device, the influencing matrices first need to be sent to the device. To set the matrices, IDirect3DDevice9::SetTransform is called with the transformation type D3DTS_WORLDMATRIX( i ), where i ranges from a minimum of 0 to a maximum of 3. The matrices that the function sends to the device for a particular attribute group are obtained from pBoneCombinationBuf of the mesh container. This member points to a buffer containing an array of type D3DXBONECOMBINATION. Each D3DXBONECOMBINATION identifies the bone matrices influencing this attribute group. With this information, the sample knows which four matrices to load on the device to properly render an attribute group. Before actually setting the matrices, however, the matrices need to have the bone offset matrices applied to them. Recall that bone offset matrices transform the vertices from the mesh's default pose on the disk to the parent bone's frame of reference. Therefore, a matrix that gets sent to the device is the product of the bone matrix and the frame's combined transformation matrix. After loading the matrices, the faces of the attribute group can be rendered by calling ID3DXMesh::DrawSubset.

Rendering with Fixed-Function Indexed Skinning

With the fixed-function indexed skinning, the device has a matrix palette. The size of the palette can be obtained from the device capability information. The application can load as many matrices as the palette could hold. Each vertex in the mesh has up to four indices to identify the matrices in the palette that influence the vertex. In the sample, the code uses a maximum 12-matrix palette. Using a larger palette is more efficient, but using a smaller palette makes the code compatible with more devices. To obtain a mesh suitable for indexed skinning, GenerateSkinnedMesh calls ID3DXSkinInfo::ConvertToIndexedBlendedMesh (which is similar to ID3DXSkinInfo::ConvertToBlendedMesh) but it takes a palette size and divides the mesh vertices into attribute groups to work with the matrix palette. Each attribute group is influenced by one specific set of matrices that can fit in the palette, and can be drawn with a single IDirect3DDevice9::DrawIndexedPrimitive.

The render code for indexed skinning looks extremely similar to the non-indexed case. GenerateSkinnedMesh loops through the attribute groups and sets up the matrices to send to the device, just as it would for non-indexed skinning. Here, each attribute group identifies the vertices influenced by a particular set of matrices in the palette. In the D3DXBONECOMBINATION array, each element identifies the bone matrices with which to load the palette when rendering this attribute group. After the matrices are set, this attribute group's faces are rendered with a call to ID3DXMesh::DrawSubset.

Rendering with Shader-Based Skinning

Shader-based skinning is, in concept, similar to fixed-function indexed skinning. Instead of using the hardware-supported matrix palette, the application uses shader constants to load the matrices. Then, the vertex shader can read in the matrix values and perform the skinning transformation. The sample supports two types of shader-based skinning: assembly and HLSL. Virtually, the only difference between the two is how the shader is written. Similar to fixed-function indexed skinning, GenerateSkinnedMesh computes the number of constants required for the palette, then calls ID3DXSkinInfo::ConvertToBlendedMesh to obtain a mesh that is attribute-sorted by palette. It is worth noting that each matrix in the palette only requires three shader constants because the fourth column is always (0, 0, 0, 1) and does not need to be explicitly stored.

Shader-based skinning is a form of indexed skinning. Instead of loading the matrices with IDirect3DDevice9::SetTransform, they are loaded as shader constants. The sample computes the matrices to send to the device in exactly the same manner as in the fixed-function indexed case. When sending the matrices, the sample calls IDirect3DDevice9::SetVertexShaderConstantF when using an assembly shader, or ID3DXEffect::SetMatrixArray when using an HLSL shader. After this is done and the shader is set up, the attribute group can be rendered with ID3DXMesh::DrawSubset.

Rendering with Software Skinning

Software skinning, as the name suggests, performs the skinning work completely in software. The process takes an input mesh and the bone matrices, carries out the transformation and blending, then writes the result into another mesh. This resulting geometry represents the animation pose desired and can be sent to the device for rendering. The biggest drawback of software skinning is performance. Software skinning is inherently slow because it is done by software instead of the efficient hardware. However, software skinning is also the only technique that is guaranteed to work regardless of the device on which the application runs. (Note that other skinning techniques can also work on all devices by using software vertex processing. However, software skinning can be useful in certain situations, such as performing a hit test on the animated mesh.) To set up for software skinning, the sample allocates an array of matrices to function as the software matrix palette. During rendering, this matrix array will be filled with skinning matrices and used to animate the mesh.

Essentially, software skinning can be thought of as the indexed skinning with an infinitely large palette (or as large as the system memory allows) done completely in software. All matrices can be loaded simultaneously for rendering. In the sample, DrawMeshContainer computes all matrices for the mesh and stores the result in a matrix array. ID3DXSkinInfo::UpdateSkinnedMesh implements software skinning on a set of source vertices using the passed transformation matrices and fills a set of output vertices with animated coordinates. When it returns, the MeshData member of the mesh container holds a skinned and animated mesh; the entire mesh can now be drawn by calling ID3DXMesh::DrawSubset. The code still has to draw each attribute group at a time if the mesh contains multiple materials.


StateManager Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

StateManager Sample

This sample demonstrates how to implement a set of callbacks using the ID3DXEffectStateManager to measure the number and types of state changes in a render loop managed by the effect system. The sample also demonstrates how to use the callbacks to override the default state managment, which gives an application the option of implementing a custom approach to state filtering. An application that is CPU-bound is very likely to improve performance dramatically by controlling the amount of redundant state changes that occur in a complex render loop.

Path

Source: | (SDK root)\Samples\C++\Direct3D\StateManager
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\StateManager.exe

Prerequisites:

How The Sample Works

This sample renders a scene composed of several mesh objects including a gazebo, trees, rocks, terrain, and a skybox. Each mesh may be composed of multiple materials (snow, wood, etc). Each material is implemented by a different effect. Because of the scene complexity, the render sequence has many state changes to render the variety of materials and objects. The render sequence is created after calling these functions in OnCreateDevice:

  • BuildSceneFromX - This method loads the scene .x file, which specifies each of the meshes and their world transform. Each mesh then loads it's corresponding materials, which consists of an effect instance and the associated textures (if any).
  • QueueAndSortRenderables - This method does two things. First, it adds to the render queue all the state changes necessary to render the scene. Second, it reorders the queue according to the type of device, and the state manager.
  • SetStateManager - This method propogates the state manager to each of the effects in preparation for rendering.

The sample demonstrates the benefits of filtering redundant state changes with a per device. When a device is created (IDirect3D9::CreateDevice), the type of device is specified with D3DDEVTYPE. A pure device (created with D3DCREATE_PUREDEVICE) filters a smaller subset of possible state change commands. It is very fast because is essentially streams the pipeline commands striaght to the hardware. A pure device does not do any validation of parameters, and does little or no redundant state filtering. In constrast, a non-pure device (created without D3DCREATE_PUREDEVICE) will check each state change for redundancy, and discard them. This reduces the amount of work that the device will need to perform.

The ID3DXEffectStateManager make it possible to write custom user handlers for state changes. You can measure the number of state changes, that are happening, or even write handlers that perform custom processing (such as filtering out redundant state changes. This is precisely what the StateManager Sample does. When you run the sample, it defaults to: running a pure device, and filtering redundant states with the ID3DXEffectStateManager. This is done by creating a CPureDeviceStateManager class which derives from the ID3DXEffectStateManager interface.

CPureDeviceStateManager counts the state changes, filters redundant IDirect3DDevice9::SetRenderState, IDirect3DDevice9::SetSamplerState and IDirect3DDevice9::SetTextureStageState commands, and invokes the corresponding Microsoft Direct3D command. The number of redundant state changes that were filtered is returned to the application.

For instance:

State Changes | Filtered State Changes | Number of Rocks | % Reduction in State Changes
120 | 38 | 1 | -31
7971 | 3856 | 200 | -48

Another Performance Tip: Reordering The Render Sequence

In addition to filtering redundant state changes, another option to improve performance is to re-order the render sequence. This can have an impact especially on a non-pure device, or in a scenario that is more limited by the amount of matrix transforms that are set (as opposed to the number of materials used). For example, here is a render sequence that is ordered by each mesh object:

// Render each mesh object
For each instance of mesh x
    Setup transforms (ID3DXEffect SetMatrix)
    For each material of mesh x
        Set up material (ID3DXEffect Begin/BeginPass)
        Draw

This is the same sequence re-ordered by material:

// Render each effect to minimize state changes
For each material y
    Set up material (ID3DXEffect Begin/Begin Pass)
    For each instance of material y
      Set up transforms (ID3DXEffect SetMatrix)
      Draw

Each sequence is better in some situations and worse in others. An application that has lots of materials may reduce the number of redundant state changes by ordering by material.

For further information about measuring the performance of a CPU bound scenario using similar techniques to a profiler, see Accurately Profiling Direct3D API Calls.


Text3D Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

Text3D Sample

The Text3D Sample shows how to draw 2-D text in a 3-D scene. This is useful for displaying statistics or game menus, for example.

Path

Source: | (SDK root)\Samples\C++\Direct3D\Text3D
Executable: | (SDK root)\Samples\C++\Direct3D\Bin\Text3D.exe

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

This sample uses ID3DXFont to display 2-D text in a 3-D scene. The source code for the class is of most interest to this sample. The class uses Microsoft Windows Graphics Device Interface (GDI) to load a font and output each letter to a bitmap. That bitmap, in turn, is used to create a texture.

When the DrawText function is called, a vertex buffer is filled with polygons that are textured using the font texture created as mentioned above. The polygons may be drawn as a 2-D overlay which may be useful for printing statistics.


Reference
Microsoft DirectX 9.0 SDK Update (October 2004)

Reference

This section contains the reference pages for the Microsoft Direct3D application programming interface (API). Information is contained in the following sections.

  • Direct3D Reference
  • D3DX Reference
  • HLSL Shader Reference
  • Asm Shader Reference
  • Effect Reference
  • Sample Framework Reference
  • X File Reference
  • X File Reference (Legacy)
  • DDS File Reference


Direct3D Reference
Microsoft DirectX 9.0 SDK Update (October 2004)

Direct3D Reference

This section contains reference information for the application programming interface (API) elements provided by Microsoft Direct3D. Reference material is divided into the following categories.

  • Interfaces
  • Functions
  • Macros
  • Structures
  • Enumerated Types
  • Constants


Interfaces
Microsoft DirectX 9.0 SDK Update (October 2004)

Interfaces

This section contains reference information for the Component Object Model (COM) interfaces provided by Microsoft Direct3D. The following interfaces are used with Direct3D.

Interfaces

  • ID3DXFile
  • ID3DXFileData
  • ID3DXFileEnumObject
  • ID3DXFileSaveData
  • ID3DXFileSaveObject
  • IDirect3D9
  • IDirect3DBaseTexture9
  • IDirect3DCubeTexture9
  • IDirect3DDevice9
  • IDirect3DIndexBuffer9
  • IDirect3DPixelShader9
  • IDirect3DQuery9
  • IDirect3DResource9
  • IDirect3DStateBlock9
  • IDirect3DSurface9
  • IDirect3DSwapChain9
  • IDirect3DTexture9
  • IDirect3DVertexBuffer9
  • IDirect3DVertexDeclaration9
  • IDirect3DVertexShader9
  • IDirect3DVolume9
  • IDirect3DVolumeTexture9


IDirect3D9 Interface

Applications use the methods of the IDirect3D9 interface to create Microsoft Direct3D objects and set up the environment. This interface includes methods for enumerating and retrieving capabilities of the device.

IDirect3D9 Members

CheckDepthStencilMatch | Determines whether a depth-stencil format is compatible with a render-target format in a particular display mode.
CheckDeviceFormat | Determines whether a surface format is available as a specified resource type and can be used as a texture, depth-stencil buffer, or render target, or any combination of the three, on a device representing this adapter.
CheckDeviceFormatConversion | Tests the device to see if it supports conversion from one display format to another.
CheckDeviceMultiSampleType | Determines if a multisampling technique is available on this device.
CheckDeviceType | Verifies whether a hardware accelerated device type can be used on this adapter.
CreateDevice | Creates a device to represent the display adapter.
EnumAdapterModes | Queries the device to determine whether the specified adapter supports the requested format and display mode. This method could be used in a loop to enumerate all the available adapter modes.
GetAdapterCount | Returns the number of adapters on the system.
GetAdapterDisplayMode | Retrieves the current display mode of the adapter.
GetAdapterIdentifier | Describes the physical display adapters present in the system when the IDirect3D9 interface was instantiated.
GetAdapterModeCount | Returns the number of display modes available on this adapter.
GetAdapterMonitor | Returns the handle of the monitor associated with the Direct3D object.
GetDeviceCaps | Retrieves device-specific information about a device.
RegisterSoftwareDevice | Registers a pluggable software device. Software devices provide software rasterization enabling applications to access a variety of software rasterizers.

Remarks

The IDirect3D9 interface is obtained by calling the Direct3DCreate9 function.

The LPDIRECT3D9 and PDIRECT3D9 types are defined as pointers to the IDirect3D9 interface.

typedef struct IDirect3D9 *LPDIRECT3D9, *PDIRECT3D9;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

Direct3DCreate9


IDirect3D9::CheckDepthStencilMatch Method

Determines whether a depth-stencil format is compatible with a render-target format in a particular display mode.

Syntax

HRESULT CheckDepthStencilMatch(

    UINT Adapter,
    D3DDEVTYPE DeviceType,
    D3DFORMAT AdapterFormat,
    D3DFORMAT RenderTargetFormat,
    D3DFORMAT DepthStencilFormat
);

Parameters

Adapter
[in] Ordinal number denoting the display adapter to query. D3DADAPTER_DEFAULT is always the primary display adapter.
DeviceType
[in] Member of the D3DDEVTYPE enumerated type, identifying the device type.
AdapterFormat
[in] Member of the D3DFORMAT enumerated type, identifying the format of the display mode into which the adapter will be placed.
RenderTargetFormat
[in] Member of the D3DFORMAT enumerated type, identifying the format of the render-target surface to be tested.
DepthStencilFormat
[in] Member of the D3DFORMAT enumerated type, identifying the format of the depth-stencil surface to be tested.

Return Value

If the depth-stencil format is compatible with the render-target format in the display mode, this method returns D3D_OK.

D3DERR_INVALIDCALL can be returned if one or more of the parameters is invalid. If a depth-stencil format is not compatible with the render target in the display mode, then this method returns D3DERR_NOTAVAILABLE.

Remarks

This method is provided to enable applications to work with hardware requiring that certain depth formats can only work with certain render-target formats.

The behavior of this method has been changed for Microsoft DirectX 8.1. This method now pays attention to the D24x8 and D32 depth-stencil formats. The previous version assumed that these formats would always be useable with 32- or 16-bit render targets. This method will now return D3D_OK for these formats only if the device is capable of mixed-depth operations.

The following code fragment shows how you could use IDirect3D9::CheckDeviceFormat to validate a depth stencil format.

BOOL IsDepthFormatOk(D3DFORMAT DepthFormat,
                      D3DFORMAT AdapterFormat,
                      D3DFORMAT BackBufferFormat)
{

    // Verify that the depth format exists
    HRESULT hr = pD3D->CheckDeviceFormat(D3DADAPTER_DEFAULT,
                                         D3DDEVTYPE_HAL,
                                         AdapterFormat,
                                         D3DUSAGE_DEPTHSTENCIL,
                                         D3DRTYPE_SURFACE,
                                         DepthFormat);

    if(FAILED(hr)) return FALSE;

    // Verify that the depth format is compatible
    hr = pD3D->CheckDepthStencilMatch(D3DADAPTER_DEFAULT,
                                      D3DDEVTYPE_HAL,
                                      AdapterFormat,
                                      BackBufferFormat,
                                      DepthFormat);

    return SUCCEEDED(hr);

}

The preceding call will return FALSE if DepthFormat cannot be used in conjunction with AdapterFormat and BackBufferFormat.


IDirect3D9::CheckDeviceFormat Method

Determines whether a surface format is available as a specified resource type and can be used as a texture, depth-stencil buffer, or render target, or any combination of the three, on a device representing this adapter.

Syntax

HRESULT CheckDeviceFormat(

    UINT Adapter,
    D3DDEVTYPE DeviceType,
    D3DFORMAT AdapterFormat,
    DWORD Usage,
    D3DRESOURCETYPE RType,
    D3DFORMAT CheckFormat
);

Parameters

Adapter
[in] Ordinal number denoting the display adapter to query. D3DADAPTER_DEFAULT is always the primary display adapter. This method returns D3DERR_INVALIDCALL when this value equals or exceeds the number of display adapters in the system.
DeviceType
[in] Member of the D3DDEVTYPE enumerated type, identifying the device type.
AdapterFormat
[in] Member of the D3DFORMAT enumerated type, identifying the format of the display mode into which the adapter will be placed.
Usage
[in] Requested usage options for the surface. Usage options are any combination of D3DUSAGE and D3DUSAGE_QUERY constants (only a subset of the D3DUSAGE constants are valid for IDirect3D9::CheckDeviceFormat; see the table on the D3DUSAGE page).
RType
[in] Resource type requested for use with the queried format. Member of D3DRESOURCETYPE.
CheckFormat
[in] Format of the surfaces which may be used, as defined by Usage. Member of D3DFORMAT.

Return Value

If the format is compatible with the specified device for the requested usage, this method returns D3D_OK.

D3DERR_INVALIDCALL is returned if Adapter equals or exceeds the number of display adapters in the system, or if DeviceType is unsupported.

D3DERR_NOTAVAILABLE is returned if the format is not acceptable to the device for this usage.

Remarks

An application can discover support for autogeneration on a particular format by calling IDirect3D9::CheckDeviceFormat with Usage set to D3DUSAGE_AUTOGENMIPMAP. The request to automatically generate mipmaps is considered a hint. Therefore, this method can return D3DOK_NOAUTOGEN, which is a valid success code, if the only thing that fails is the mipmap generation. If the mipmap automatic generation fails, the application will get a non-mipmapped texture. For more information, see Automatic Generation of Mipmaps.

To check for an off-screen plain surface format, specify Usage = 0 and RType = D3DRTYPE_SURFACE.

A typical use of CheckDeviceFormat is to verify the existence of a particular depth-stencil surface format. See Selecting a Device for more detail on the enumeration process. The following code fragment shows how you could use CheckDeviceFormat to verify the existence of a depth-stencil format.

BOOL IsDepthFormatExisting( D3DFORMAT DepthFormat, D3DFORMAT AdapterFormat )
{
    HRESULT hr = pD3D->CheckDeviceFormat( D3DADAPTER_DEFAULT,
                                          D3DDEVTYPE_HAL,
                                          AdapterFormat,
                                          D3DUSAGE_DEPTHSTENCIL,
                                          D3DRTYPE_SURFACE,
                                          CheckFormat);

    return SUCCEEDED( hr );
}

The preceding call will return FALSE if CheckFormat does not exist on the system.

Another typical use of CheckDeviceFormat would be to verify if textures existing in particular surface formats can be rendered, given the current display mode. The following code fragment shows how you could use CheckDeviceFormat to verify that texture formats are compatible with specific back buffer formats.

BOOL IsTextureFormatOk( D3DFORMAT TextureFormat, D3DFORMAT AdapterFormat )
{
    HRESULT hr = pD3D->CheckDeviceFormat( D3DADAPTER_DEFAULT,
                                          D3DDEVTYPE_HAL,
                                          AdapterFormat,
                                          0,
                                          D3DRTYPE_TEXTURE,
                                          CheckFormat);

    return SUCCEEDED( hr );
}

The preceding call will return FALSE if CheckFormat cannot be used to render textures while the adapter surface format is AdapterFormat.


IDirect3D9::CheckDeviceFormatConversion Method

Tests the device to see if it supports conversion from one display format to another.

Syntax

HRESULT CheckDeviceFormatConversion(

    UINT Adapter,
    D3DDEVTYPE DeviceType,
    D3DFORMAT SourceFormat,
    D3DFORMAT TargetFormat
);

Parameters

Adapter
[in] Display adapter ordinal number. D3DADAPTER_DEFAULT is always the primary display adapter. This method returns D3DERR_INVALIDCALL when this value equals or exceeds the number of display adapters in the system.
DeviceType
[in] Device type. Member of the D3DDEVTYPE enumerated type.
SourceFormat
[in] Source adapter format. Member of the D3DFORMAT enumerated type.
TargetFormat
[in] Target adapter format. Member of the D3DFORMAT enumerated type.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is D3DERR_INVALIDCALL.

The method will return D3DERR_NOTAVAILABLE when the hardware does not support conversion between the two formats.

Remarks

Using IDirect3D9::CheckDeviceType to test for compatibility between a back buffer that differs from the display format will return appropriate values. This means that the call will reflect device capabilities. If the device cannot render to the requested back buffer format, the call will still return D3DERR_NOTAVAILABLE. If the device can render to the format, but cannot perform the color-converting presentation, the return value will also be D3DERR_NOTAVAILABLE. Applications can discover hardware support for the presentation itself by calling IDirect3D9::CheckDeviceFormatConversion. No software emulation for the color-converting presentation itself will be offered.

IDirect3D9::CheckDeviceFormatConversion can also be used to determine which combinations of source surface formats and destination surface formats are permissible in calls to IDirect3DDevice9::StretchRect.

Color conversion is restricted to the following source and target formats.

  • The source format must be a four-character code (FOURCC) format or a valid back buffer format. For a list of these, see FourCC Formats and BackBuffer or Display Formats.
  • The target format must be one of these unsigned formats:
    D3DFMT_X1R5G5B5 | D3DFMT_A1R5G5B5 | D3DFMT_R5G6B5
    D3DFMT_R8G8B8 | D3DFMT_X8R8G8B8 | D3DFMT_A8R8G8B8
    D3DFMT_A2R10G10B10 | D3DFMT_A16B16G16R16 | D3DFMT_A2B10G10R10
    D3DFMT_A8B8G8R8 | D3DFMT_X8B8G8R8 | D3DFMT_A16B16G16R16F
    D3DFMT_A32B32G32R32F

See Also

IDirect3DDevice9::ColorFill, IDirect3DDevice9::StretchRect


IDirect3D9::CheckDeviceMultiSampleType Method

Determines if a multisampling technique is available on this device.

Syntax

HRESULT CheckDeviceMultiSampleType(

    UINT Adapter,
    D3DDEVTYPE DeviceType,
    D3DFORMAT SurfaceFormat,
    BOOL Windowed,
    D3DMULTISAMPLE_TYPE MultiSampleType,
    DWORD* pQualityLevels
);

Parameters

Adapter
[in] Ordinal number denoting the display adapter to query. D3DADAPTER_DEFAULT is always the primary display adapter. This method returns FALSE when this value equals or exceeds the number of display adapters in the system. See Remarks.
DeviceType
[in] Member of the D3DDEVTYPE enumerated type, identifying the device type.
SurfaceFormat
[in] Member of the D3DFORMAT enumerated type that specifies the format of the surface to be multisampled. For more information, see Remarks.
Windowed
[in] BOOL value. Specify TRUE to inquire about windowed multisampling, and specify FALSE to inquire about full-screen multisampling.
MultiSampleType
[in] Member of the D3DMULTISAMPLE_TYPE enumerated type, identifying the multisampling technique to test.
pQualityLevels
[out] The number of quality stops available for a given multisample type. This can be NULL if it is not necessary to return the values.

Return Value

If the device can perform the specified multisampling method, this method returns D3D_OK.

D3DERR_INVALIDCALL is returned if the Adapter or MultiSampleType parameters are invalid. This method returns D3DERR_NOTAVAILABLE if the queried multisampling technique is not supported by this device. D3DERR_INVALIDDEVICE is returned if DeviceType does not apply to this adapter.

Remarks

This method is intended for use with both render-target and depth-stencil surfaces because you must create both surfaces multisampled if you want to use them together.

The following code fragment shows how you could use IDirect3D9::CheckDeviceMultiSampleType to test for devices that support a specific multisampling method.

if( SUCCEEDED(pD3D->CheckDeviceMultiSampleType( pCaps->AdapterOrdinal,
                                pCaps->DeviceType, BackBufferFormat,
                                FALSE, D3DMULTISAMPLE_3_SAMPLES, NULL ) ) &&
         SUCCEEDED(pD3D->CheckDeviceMultiSampleType( pCaps->AdapterOrdinal,
                                pCaps->DeviceType, DepthBufferFormat,
                                FALSE, D3DMULTISAMPLE_3_SAMPLES, NULL ) ) )
    return S_OK;

The preceding code will return S_OK if the device supports the full-screen D3DMULTISAMPLE_3_SAMPLES multisampling method with the surface format.


IDirect3D9::CheckDeviceType Method

Verifies whether a hardware accelerated device type can be used on this adapter.

Syntax

HRESULT CheckDeviceType(

    UINT Adapter,
    D3DDEVTYPE DeviceType,
    D3DFORMAT DisplayFormat,
    D3DFORMAT BackBufferFormat,
    BOOL Windowed
);

Parameters

Adapter
[in] Ordinal number denoting the display adapter to enumerate. D3DADAPTER_DEFAULT is always the primary display adapter. This method returns D3DERR_INVALIDCALL when this value equals or exceeds the number of display adapters in the system.
DeviceType
[in] Member of the D3DDEVTYPE enumerated type, indicating the device type to check.
DisplayFormat
[in] Member of the D3DFORMAT enumerated type, indicating the format of the adapter display mode for which the device type is to be checked. For example, some devices will operate only in 16-bits-per-pixel modes.
BackBufferFormat
[in] Back buffer format. For more information about formats, see D3DFORMAT. This value must be one of the render-target formats. You can use IDirect3DDevice9::GetDisplayMode to obtain the current format.

For windowed applications, the back buffer format does not need to match the display mode format if the hardware supports color conversion. The set of possible back buffer formats is constrained, but the runtime will allow any valid back buffer format to be presented to any desktop format. There is the additional requirement that the device be operable in the desktop mode because devices typically do not operate in 8 bits per pixel modes.

Full-screen applications cannot do color conversion.

D3DFMT_UNKNOWN is allowed for windowed mode.
Windowed
[in] Value indicating whether the device type will be used in full-screen or windowed mode. If set to TRUE, the query is performed for windowed applications; otherwise, this value should be set FALSE.

Return Value

If the device can be used on this adapter, D3D_OK is returned.

D3DERR_INVALIDCALL is returned if Adapter equals or exceeds the number of display adapters in the system. D3DERR_INVALIDCALL is also returned if IDirect3D9::CheckDeviceType specified a device that does not exist.

D3DERR_NOTAVAILABLE is returned if the requested back buffer format is not supported, or if hardware acceleration is not available for the specified formats.

Remarks

A hardware abstraction layer (HAL) device type requires hardware acceleration. Applications can use CheckDeviceType to determine if the needed hardware and drivers are present to support a HAL device.

Full-screen applications should not specify a DisplayFormat that contains an alpha channel. This will result in a failed call. Note that an alpha channel can be present in the back buffer but the two display formats must be identical in all other respects. For example, if DisplayFormat = D3DFMT_X1R5G5B5, valid values for BackBufferFormat include D3DFMT_X1R5G5B5 and D3DFMT_A1R5G5B5 but exclude D3DFMT_R5G6B5.

The following code fragment shows how you could use CheckDeviceType to test whether a certain device type can be used on this adapter.
if(SUCCEEDED(pD3Device->CheckDeviceType(D3DADAPTER_DEFAULT,
                                        D3DDEVTYPE_HAL,
                                        DisplayFormat,
                                        BackBufferFormat,
                                        bIsWindowed)))

     return S_OK;
// There is no HAL on this adapter using this render-target format.
// Try again, using another format.

This code returns S_OK if the device can be used on the default adapter with the specified surface format.

Using IDirect3D9::CheckDeviceType to test for compatibility between a back buffer that differs from the display format will return appropriate values. This means that the call will reflect device capabilities. If the device cannot render to the requested back-buffer format, the call will still return D3DERR_NOTAVAILABLE. If the device can render to the format, but cannot perform the color-converting presentation, the return value will also be D3DERR_NOTAVAILABLE. Applications can discover hardware support for the presentation itself by calling IDirect3D9::CheckDeviceFormatConversion. No software emulation for the color-converting presentation itself will be offered.


IDirect3D9::CreateDevice Method

Creates a device to represent the display adapter.

Syntax

HRESULT CreateDevice(

    UINT Adapter,
    D3DDEVTYPE DeviceType,
    HWND hFocusWindow,
    DWORD BehaviorFlags,
    D3DPRESENT_PARAMETERS *pPresentationParameters,
    IDirect3DDevice9 **ppReturnedDeviceInterface
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter.
DeviceType
[in] Member of the D3DDEVTYPE enumerated type that denotes the desired device type. If the desired device type is not available, the method will fail.
hFocusWindow
[in] The focus window alerts Microsoft Direct3D when an application switches from foreground mode to background mode. See Remarks.
  • For full-screen mode, the window specified must be a top-level window.
  • For windowed mode, this parameter may be NULL. If you specify NULL, you also will need to specify a non-NULL handle when calling IDirect3DDevice9::Present. This can be done with either hDeviceWindow in D3DPRESENT_PARAMETERS, or hDestWndOverride in IDirect3DDevice9::Present.
BehaviorFlags
[in] Combination of one or more options that control device creation. For more information, see D3DCREATE.
pPresentationParameters
[in, out] Pointer to a D3DPRESENT_PARAMETERS structure, describing the presentation parameters for the device to be created. If BehaviorFlags specifies D3DCREATE_ADAPTERGROUP_DEVICE, pPresentationParameters is an array. Regardless of the number of heads that exist, only one depth/stencil surface is automatically created.

For Microsoft Windows 2000 and Windows XP, the full-screen device display refresh rate is set in the following order:

  1. User-specified nonzero ForcedRefreshRate registry key, if supported by the device.
  2. Application-specified nonzero refresh rate value in the presentation parameter.
  3. Refresh rate of the latest desktop mode, if supported by the device.
  4. 75 hertz if supported by the device.
  5. 60 hertz if supported by the device.
  6. Device default.

An unsupported refresh rate will default to the closest supported refresh rate below it. For example, if the application specifies 63 hertz, 60 hertz will be used. There are no supported refresh rates below 57 hertz.

pPresentationParameters is both an input and an output parameter. Calling this method may change several members including:

  • If BackBufferCount, BackBufferWidth, and BackBufferHeight are 0 before the method is called, they will be changed when the method returns.
  • If BackBufferFormat equals D3DFMT_UNKNOWN before the method is called, it will be changed when the method returns.
ppReturnedDeviceInterface
[out, retval] Address of a pointer to the returned IDirect3DDevice9 interface, which represents the created device.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_DEVICELOST | The device has been lost but cannot be reset at this time. Therefore, rendering is not possible.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Direct3D does not have enough display memory to perform the operation.

Remarks

This method returns a fully working device interface, set to the required display mode (or windowed), and allocated with the appropriate back buffers. To begin rendering, the application needs only to create and set a depth buffer (assuming EnableAutoDepthStencil is FALSE in D3DPRESENT_PARAMETERS).

When you create a Direct3D device, you supply two different window parameters: a focus window (hFocusWindow) and a device window (the hDeviceWindow in D3DPRESENT_PARAMETERS). The purpose of each window is:

  • The focus window alerts Direct3D when an application switches from foreground mode to background mode (via Alt-Tab, a mouse click, or some other method). A single focus window is shared by each device created by an application.
  • The device window determines the location and size of the back buffer on screen. This is used by Direct3D when the back buffer contents are copied to the front buffer during IDirect3DDevice9::Present.

This method should not be run during the handling of WM_CREATE. An application should never pass a window handle to Direct3D while handling WM_CREATE. Any call to create, release, or reset the device must be done using the same thread as the window procedure of the focus window.

Note that D3DCREATE_HARDWARE_VERTEXPROCESSING, D3DCREATE_MIXED_VERTEXPROCESSING, and D3DCREATE_SOFTWARE_VERTEXPROCESSING are mutually exclusive flags, and at least one of these vertex processing flags must be specified when calling this method.

Back buffers created as part of the device are only lockable if D3DPRESENTFLAG_LOCKABLE_BACKBUFFER is specified in the presentation parameters. (Multisampled back buffers and depth surfaces are never lockable.)

The methods IDirect3DDevice9::Reset, IUnknown::Release, and IDirect3DDevice9::TestCooperativeLevel must be called from the same thread that used this method to create a device.

D3DFMT_UNKNOWN can be specified for the windowed mode back buffer format when calling IDirect3D9::CreateDevice, IDirect3DDevice9::Reset, and IDirect3DDevice9::CreateAdditionalSwapChain. This means the application does not have to query the current desktop format before calling IDirect3D9::CreateDevice for windowed mode. For full-screen mode, the back buffer format must be specified.

If you attempt to create a device on a 0x0 sized window, IDirect3D9::CreateDevice will fail.

See Also

Direct3DCreate9, D3DDEVICE_CREATION_PARAMETERS, IDirect3DDevice9::Reset, Multihead, Using Devices with the Sample Framework


IDirect3D9::EnumAdapterModes Method

Queries the device to determine whether the specified adapter supports the requested format and display mode. This method could be used in a loop to enumerate all the available adapter modes.

Syntax

HRESULT EnumAdapterModes(

    UINT Adapter,
    D3DFORMAT Format,
    UINT Mode,
    D3DDISPLAYMODE* pMode
);

Parameters

Adapter
[in] Ordinal number denoting the display adapter to enumerate. D3DADAPTER_DEFAULT is always the primary display adapter. This method returns D3DERR_INVALIDCALL when this value equals or exceeds the number of display adapters in the system.
Format
[in] Allowable pixel formats. See Remarks.
Mode
[in] Represents the display-mode index which is an unsigned integer between zero and the value returned by IDirect3D9::GetAdapterModeCount minus one.
pMode
[out] A pointer to the available display mode of type D3DDISPLAYMODE. See Remarks.

Return Value

  • If the device can be used on this adapter, D3D_OK is returned.
  • If the Adapter equals or exceeds the number of display adapters in the system, D3DERR_INVALIDCALL is returned.
  • If either surface format is not supported or if hardware acceleration is not available for the specified formats, D3DERR_NOTAVAILABLE is returned.

Remarks

An application supplies a display mode and a format to IDirect3D9::EnumAdapterModes which returns a display mode. This method could be used in a loop to enumerate all available display modes.

The application specifies a format and the enumeration is restricted to those display modes that exactly match the format (alpha is ignored). Allowed formats (which are members of D3DFORMAT) are as follows:

  • D3DFMT_A1R5G5B5
  • D3DFMT_A2R10G10B10
  • D3DFMT_A8R8G8B8
  • D3DFMT_R5G6B5
  • D3DFMT_X1R5G5B5
  • D3DFMT_X8R8G8B8

In addition, IDirect3D9::EnumAdapterModes treats pixel formats 565 and 555 as equivalent, and returns the correct version. The difference comes into play only when the application locks the back buffer and there is an explicit flag that the application must set in order to accomplish this.


IDirect3D9::GetAdapterCount Method

Returns the number of adapters on the system.

Syntax

UINT GetAdapterCount(VOID);

Return Value

A UINT value that denotes the number of adapters on the system at the time this IDirect3D9 interface was instantiated.

See Also

IDirect3D9::GetAdapterIdentifier


IDirect3D9::GetAdapterDisplayMode Method

Retrieves the current display mode of the adapter.

Syntax

HRESULT GetAdapterDisplayMode(

    UINT Adapter,
    D3DDISPLAYMODE *pMode
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter to query. D3DADAPTER_DEFAULT is always the primary display adapter.
pMode
[in, out] Pointer to a D3DDISPLAYMODE structure, to be filled with information describing the current adapter's mode.

Return Value

If the method succeeds, the return value is D3D_OK.

If Adapter is out of range or pMode is invalid, this method returns D3DERR_INVALIDCALL.

Remarks

IDirect3D9::GetAdapterDisplayMode will not return the correct format when the display is in an extended format, such as 2:10:10:10. Instead, it returns the format X8R8G8B8.


IDirect3D9::GetAdapterIdentifier Method

Describes the physical display adapters present in the system when the IDirect3D9 interface was instantiated.

Syntax

HRESULT GetAdapterIdentifier(

    UINT Adapter,
    DWORD Flags,
    D3DADAPTER_IDENTIFIER9 *pIdentifier
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter. The minimum value for this parameter is 0, and the maximum value for this parameter is one less than the value returned by IDirect3D9::GetAdapterCount.
Flags
[in] Flags sets the WHQLLevel member of D3DADAPTER_IDENTIFIER9. Flags can be set to either 0 or D3DENUM_WHQL_LEVEL. If D3DENUM_WHQL_LEVEL is specified, this call can connect to the Internet to download new Microsoft Windows Hardware Quality Labs (WHQL) certificates.
pIdentifier
[out] Pointer to a D3DADAPTER_IDENTIFIER9 structure to be filled with information describing this adapter. If Adapter is greater than or equal to the number of adapters in the system, this structure will be zeroed.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if Adapter is out of range, if Flags contains unrecognized parameters, or if pIdentifier is NULL or points to unwriteable memory.

See Also

IDirect3D9::GetAdapterCount


IDirect3D9::GetAdapterModeCount Method

Returns the number of display modes available on this adapter.

Syntax

UINT GetAdapterModeCount(

    UINT Adapter,
    D3DFORMAT Format
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter.
Format
[in] Identifies the format of the surface type using D3DFORMAT. Use IDirect3D9::EnumAdapterModes to see the valid formats.

Return Value

This method returns the number of display modes on this adapter or zero if Adapter is greater than or equal to the number of adapters on the system.

See Also

IDirect3D9::EnumAdapterModes


IDirect3D9::GetAdapterMonitor Method

Returns the handle of the monitor associated with the Microsoft Direct3D object.

Syntax

HMONITOR GetAdapterMonitor(

    UINT Adapter
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter.

Return Value

Handle of the monitor associated with the Direct3D object.

Remarks

As shown in the following code fragment, which illustrates how to obtain a handle to the monitor associated with a given device, use IDirect3DDevice9::GetDirect3D to return the Direct3D enumerator from the device and use IDirect3DDevice9::GetCreationParameters to retrieve the value for Adapter.

    if( FAILED( pDevice->GetCreationParameters(  &Parameters ) ) )
        return D3DERR_INVALIDCALL;

    if( FAILED( pDevice->GetDirect3D(&pD3D) ) )
        return D3DERR_INVALIDCALL;

    hMonitor = pD3D->GetAdapterMonitor(Parameters.AdapterOrdinal);

    pD3D->Release();

See Also

IDirect3DDevice9::GetCreationParameters, IDirect3DDevice9::GetDirect3D


IDirect3D9::GetDeviceCaps Method

Retrieves device-specific information about a device.

Syntax

HRESULT GetDeviceCaps(

    UINT Adapter,
    D3DDEVTYPE DeviceType,
    D3DCAPS9 *pCaps
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter.
DeviceType
[in] Member of the D3DDEVTYPE enumerated type. Denotes the device type.
pCaps
[out] Pointer to a D3DCAPS9 structure to be filled with information describing the capabilities of the device.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_INVALIDDEVICE | The requested device type is not valid.
D3DERR_OUTOFVIDEOMEMORY | Direct3D does not have enough display memory to perform the operation.

Remarks

The application should not assume the persistence of vertex processing capabilities across Microsoft Direct3D device objects. The particular capabilities that a physical device exposes may depend on parameters supplied to IDirect3D9::CreateDevice. For example, the capabilities may yield different vertex processing capabilities before and after creating a Direct3D Device Object with hardware vertex processing enabled. For more information see the description of D3DCAPS9.


IDirect3D9::RegisterSoftwareDevice Method

Registers a pluggable software device. Software devices provide software rasterization enabling applications to access a variety of software rasterizers.

Syntax

HRESULT RegisterSoftwareDevice(

    void *pInitializeFunction
);

Parameters

pInitializeFunction
[in] Pointer to the initialization function for the software device to be registered.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Direct3D does not have enough display memory to perform the operation.

Remarks

If the user's computer provides no special hardware acceleration for 3-D operations, your application might emulate 3-D hardware in software. Software rasterization devices emulate the functions of color 3-D hardware in software. A software device runs more slowly than a hardware abstraction layer (HAL). However, software devices take advantage of any special instructions supported by the CPU to increase performance. Instruction sets include the AMD 3DNow! instruction set on some AMD processors and the MMX instruction set supported by many Intel processors. Microsoft Direct3D uses the 3D-Now! instruction set to accelerate transformation and lighting operations and the MMX instruction set to accelerate rasterization.

Software devices communicate with Direct3D through an interface similar to the hardware device driver interface (DDI).

Software devices are loaded by the application and registered with the IDirect3D9 object. Direct3D uses the software device for rendering.

The Direct3D Driver Development Kit (DDK) provides the documentation and headers for developing pluggable software devices.


IDirect3DBaseTexture9 Interface

Applications use the methods of the IDirect3DBaseTexture9 interface to manipulate texture resources including cube and volume textures.

IDirect3DBaseTexture9 Members

FreePrivateData | Frees the specified private data associated with this resource.
GenerateMipSubLevels | Generate mipmap sublevels.
GetAutoGenFilterType | Get the filter type that is used for automatically generated mipmap sublevels.
GetDevice | Retrieves the device associated with a resource.
GetLevelCount | Returns the number of texture levels in a multilevel texture.
GetLOD | Returns a value clamped to the maximum level of detail (LOD) set for a managed texture (this method is not supported for an unmanaged texture).
GetPriority | Retrieves the priority for this resource.
GetPrivateData | Copies the private data associated with the resource to a provided buffer.
GetType | Returns the type of the resource.
PreLoad | Preloads a managed resource.
SetAutoGenFilterType | Set the filter type that is used for automatically generated mipmap sublevels.
SetLOD | Sets the most detailed LOD for a managed texture.
SetPriority | Assigns the resource-management priority for this resource.
SetPrivateData | Associates data with the resource that is intended for use by the application, not by Microsoft Direct3D. Data is passed by value, and multiple sets of data can be associated with a single resource.

Remarks

The IDirect3DBaseTexture9 interface assigned to a particular stage for a device is obtained by calling the IDirect3DDevice9::GetTexture method.

The LPDIRECT3DBASETEXTURE9 and PDIRECT3DBASETEXTURE9 types are defined as pointers to the IDirect3DBaseTexture9 interface.

typedef struct IDirect3DBaseTexture9 *LPDIRECT3DBASETEXTURE9, *PDIRECT3DBASETEXTURE9;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IDirect3DResource9
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98


IDirect3DBaseTexture9::GenerateMipSubLevels Method

Generate mipmap sublevels.

Syntax

VOID GenerateMipSubLevels(VOID);

Return Value

No return value.

Remarks

An application can generate mipmap sublevels at any time by calling IDirect3DBaseTexture9::GenerateMipSubLevels. To have mipmap sublevels generated automatically at texture creation time (see Automatic Generation of Mipmaps), specify D3DUSAGE_AUTOGENMIPMAP during IDirect3DDevice9::CreateTexture, IDirect3DDevice9::CreateCubeTexture, and IDirect3DDevice9::CreateVolumeTexture. For more information about usage constants, see D3DUSAGE.

See Also

IDirect3DBaseTexture9::GetAutoGenFilterType, IDirect3DBaseTexture9::SetAutoGenFilterType


IDirect3DBaseTexture9::GetAutoGenFilterType Method

Get the filter type that is used for automatically generated mipmap sublevels.

Syntax

D3DTEXTUREFILTERTYPE GetAutoGenFilterType(VOID);

Return Value

Filter type. See D3DTEXTUREFILTERTYPE. A texture must be created with D3DUSAGE_AUTOGENMIPMAP to use this method. Any other usage value will cause this method to return D3DTEXF_NONE.

Remarks

Changing the filter type "dirties" the mipmap sublevels and causes them to be regenerated.

The (default) filter type set at texture creation time is D3DTEXF_LINEAR. If the driver doesn't support a linear filter, the filter type will be set to D3DTEXF_POINT. All filter types supported by the driver for regular texture filtering are supported for autogeneration except D3DTEXF_NONE. For each resource type, drivers should support all the filter types reported in the corresponding texture, cubetexture, and volumetexture filter caps. For more information about texture types, see D3DTEXTUREFILTERTYPE.

This method has no effect if the texture is not created with D3DUSAGE_AUTOGENMIPMAP.

See Also

IDirect3DBaseTexture9::GenerateMipSubLevels, IDirect3DBaseTexture9::SetAutoGenFilterType


IDirect3DBaseTexture9::GetLevelCount Method

Returns the number of texture levels in a multilevel texture.

Syntax

DWORD GetLevelCount(VOID);

Return Value

A DWORD value indicating the number of texture levels in a multilevel texture.

Remarks

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture9.

  • IDirect3DCubeTexture9
  • IDirect3DTexture9
  • IDirect3DVolumeTexture9


IDirect3DBaseTexture9::GetLOD Method

Returns a value clamped to the maximum level of detail (LOD) set for a managed texture (this method is not supported for an unmanaged texture).

Syntax

DWORD GetLOD(VOID);

Return Value

A DWORD value, clamped to the maximum LOD value (one less than the total number of levels).

Calling IDirect3DBaseTexture9::GetLOD on an unmanaged texture is not supported and will result in a D3DERR error code being returned.

See Also

IDirect3DBaseTexture9::SetLOD


IDirect3DBaseTexture9::SetAutoGenFilterType Method

Set the filter type that is used for automatically generated mipmap sublevels.

Syntax

HRESULT SetAutoGenFilterType(

    D3DTEXTUREFILTERTYPE FilterType
);

Parameters

FilterType
[in] Filter type. See D3DTEXTUREFILTERTYPE. This method will fail if the filter type is invalid or not supported.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Changing the filter type "dirties" the mipmap sublevels and causes them to be regenerated.

The (default) filter type set at texture creation time is D3DTEXF_LINEAR. If the driver does not support a linear filter, the filter type will be set to D3DTEXF_POINT. All filter types supported by the driver for regular texture filtering are supported for autogeneration except D3DTEXF_NONE. IDirect3DBaseTexture9::SetAutoGenFilterType will fail unless the driver sets the appropriate D3DPTFILTERCAPS_MINFxxx caps. These values are specified in the TextureFilterCaps and/or CubeTextureFilterCaps members of D3DCAPS9. For more information about texture filter types, see D3DTEXTUREFILTERTYPE.

This method has no effect if the texture is not created with D3DUSAGE_AUTOGENMIPMAP. In this case, no failure is returned. For more information about usage constants, see D3DUSAGE.

See Also

IDirect3DBaseTexture9::GenerateMipSubLevels, IDirect3DBaseTexture9::GetAutoGenFilterType


IDirect3DBaseTexture9::SetLOD Method

Sets the most detailed level of detail (LOD) for a managed texture.

Syntax

DWORD SetLOD(

    DWORD LODNew
);

Parameters

LODNew
[in] Most detailed LOD value to set for the mipmap chain.

Return Value

A DWORD value, clamped to the maximum LOD value (one less than the total number of levels). Subsequent calls to this method will return the clamped value, not the LOD value that was previously set.

Remarks

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture9.

  • IDirect3DCubeTexture9
  • IDirect3DTexture9
  • IDirect3DVolumeTexture9
  • IDirect3DResource9

IDirect3DBaseTexture9::SetLOD is used for LOD control of managed textures. This method returns 0 on nonmanaged textures.

IDirect3DBaseTexture9::SetLOD communicates to the Microsoft Direct3D texture manager the most detailed mipmap in the chain that should be loaded into local video memory. For example, in a five-level mipmap chain, setting LODNew to 2 indicates that the texture manager should load only mipmap levels 2 through 4 into local video memory at any given time.

More specifically, if the texture was created with the dimensions of 256x256, setting the most detailed level to 0 indicates that 256×256 is the largest mipmap available, setting the most detailed level to 1 indicates that 128×128 is the largest mipmap available, and so on, up to the most detailed mip level (the smallest texture size) for the chain.

See Also

IDirect3DBaseTexture9::GetLOD


IDirect3DCubeTexture9 Interface

Applications use the methods of the IDirect3DCubeTexture9 interface to manipulate a cube texture resource.

IDirect3DCubeTexture9 Members

AddDirtyRect

Adds a dirty region to a cube texture resource.

FreePrivateData | Frees the specified private data associated with this resource.
GenerateMipSubLevels | Generate mipmap sublevels.
GetAutoGenFilterType | Get the filter type that is used for automatically generated mipmap sublevels.
GetCubeMapSurface | Retrieves a cube texture map surface.
GetDevice | Retrieves the device associated with a resource.
GetLevelCount | Returns the number of texture levels in a multilevel texture.
GetLevelDesc

Retrieves a description of one face of the specified cube texture level.

GetLOD | Returns a value clamped to the maximum level of detail (LOD) set for a managed texture (this method is not supported for an unmanaged texture).
GetPriority | Retrieves the priority for this resource.
GetPrivateData | Copies the private data associated with the resource to a provided buffer.
GetType | Returns the type of the resource.
LockRect | Locks a rectangle on a cube texture resource.
PreLoad | Preloads a managed resource.
SetAutoGenFilterType | Set the filter type that is used for automatically generated mipmap sublevels.
SetLOD | Sets the most detailed LOD for a managed texture.
SetPriority | Assigns the resource-management priority for this resource.
SetPrivateData | Associates data with the resource that is intended for use by the application, not by Microsoft Direct3D. Data is passed by value, and multiple sets of data can be associated with a single resource.
UnlockRect

Unlocks a rectangle on a cube texture resource.

Remarks

The IDirect3DCubeTexture9 interface can be obtained by calling the IDirect3DDevice9::CreateCubeTexture method or one of the D3DXCreateCubeTexture xxx functions.

This interface inherits additional functionality from the IDirect3DBaseTexture9 interface.

This interface, like all Component Object Model (COM) interfaces, inherits additional functionality from the IUnknown interface.

The LPDIRECT3DCUBETEXTURE9 and PDIRECT3DCUBETEXTURE9 types are defined as pointers to the IDirect3DCubeTexture9 interface.

typedef struct IDirect3DCubeTexture9 *LPDIRECT3DCUBETEXTURE9, *PDIRECT3DCUBETEXTURE9;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IDirect3DBaseTexture9
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::CreateCubeTexture, D3DXCreateCubeTexture, D3DXCreateCubeTextureFromFile, D3DXCreateCubeTextureFromFileEx, D3DXCreateCubeTextureFromFileInMemory, D3DXCreateCubeTextureFromFileInMemoryEx, D3DXCreateCubeTextureFromResource, D3DXCreateCubeTextureFromResourceEx


IDirect3DCubeTexture9::AddDirtyRect Method

Adds a dirty region to a cube texture resource.

Syntax

HRESULT AddDirtyRect(

    D3DCUBEMAP_FACES FaceType,
    CONST RECT *pDirtyRect
);

Parameters

FaceType
[in] Member of the D3DCUBEMAP_FACES enumerated type, identifying the cube map face.
pDirtyRect
[in] Pointer to a RECT World Wide Web link structure, specifying the dirty region. Specifying NULL expands the dirty region to cover the entire cube texture.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For performance reasons, dirty regions are only recorded for level zero of a texture. For sublevels, it is assumed that the corresponding (scaled) rectangle or box is also dirty. Dirty regions are automatically recorded when IDirect3DCubeTexture9::LockRect or IDirect3DVolumeTexture9::LockBox is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. Also, the destination surface of a IDirect3DDevice9::UpdateSurface call is marked dirty.

See Also

IDirect3DCubeTexture9::GetLevelDesc, IDirect3DCubeTexture9::LockRect, IDirect3DCubeTexture9::UnlockRect


IDirect3DCubeTexture9::GetCubeMapSurface Method

Retrieves a cube texture map surface.

Syntax

HRESULT GetCubeMapSurface(

    D3DCUBEMAP_FACES FaceType,
    UINT Level,
    IDirect3DSurface9 **ppCubeMapSurface
);

Parameters

FaceType
[in] Member of the D3DCUBEMAP_FACES enumerated type, identifying a cube map face.
Level
[in] Specifies a level of a mipmapped cube texture.
ppCubeMapSurface
[out] Address of a pointer to an IDirect3DSurface9 interface, representing the returned cube texture map surface.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DSurface9 interface. Failure to call IUnknown::Release when finished using this IDirect3DSurface9 interface results in a memory leak.


IDirect3DCubeTexture9::GetLevelDesc Method

Retrieves a description of one face of the specified cube texture level.

Syntax

HRESULT GetLevelDesc(

    UINT Level,
    D3DSURFACE_DESC *pDesc
);

Parameters

Level
[in] Specifies a level of a mipmapped cube texture.
pDesc
[out] Pointer to a D3DSURFACE_DESC structure, describing one face of the specified cube texture level.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if one or more of the arguments are invalid.

Remarks

The D3DSURFACE_DESC structure contains Width and Height members, which describe the size of one face in the cube. To get the size of the entire cube, multiply six (the number of cube faces) by the product of Width and Height.

See Also

IDirect3DCubeTexture9::AddDirtyRect, IDirect3DCubeTexture9::LockRect, IDirect3DCubeTexture9::UnlockRect


IDirect3DCubeTexture9::LockRect Method

Locks a rectangle on a cube texture resource.

Syntax

HRESULT LockRect(

    D3DCUBEMAP_FACES FaceType,
    UINT Level,
    D3DLOCKED_RECT *pLockedRect,
    CONST RECT *pRect,
    DWORD Flags
);

Parameters

FaceType
[in] Member of the D3DCUBEMAP_FACES enumerated type, identifying a cube map face.
Level
[in] Specifies a level of a mipmapped cube texture.
pLockedRect
[out] Pointer to a D3DLOCKED_RECT structure, describing the region to lock.
pRect
[in] Pointer to a rectangle to lock. Specified by a pointer to a RECT World Wide Web link structure. Specifying NULL for this parameter expands the dirty region to cover the entire cube texture.
Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY

You may not specify a subrect when using D3DLOCK_DISCARD. For a description of the flags, see D3DLOCK.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if one or more of the arguments is invalid.

Remarks

For performance reasons, dirty regions are only recorded for level zero of a texture. Dirty regions are automatically recorded when IDirect3DCubeTexture9::LockRect is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. See IDirect3DDevice9::UpdateTexture for more information.

Cube textures created with D3DPOOL_DEFAULT are not lockable. Cube textures created in video memory are lockable when created with USAGE_DYNAMIC.

The only lockable format for a depth-stencil texture is D3DFMT_D16_LOCKABLE.

See Also

IDirect3DCubeTexture9::AddDirtyRect, IDirect3DCubeTexture9::GetLevelDesc, IDirect3DCubeTexture9::UnlockRect


IDirect3DCubeTexture9::UnlockRect Method

Unlocks a rectangle on a cube texture resource.

Syntax

HRESULT UnlockRect(

    D3DCUBEMAP_FACES FaceType,
    UINT Level
);

Parameters

FaceType
[in] Member of the D3DCUBEMAP_FACES enumerated type, identifying a cube map face.
Level
[in] Specifies a level of a mipmapped cube texture.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if one or more of the arguments is invalid.

See Also

IDirect3DCubeTexture9::AddDirtyRect, IDirect3DCubeTexture9::LockRect


IDirect3DDevice9 Interface

Applications use the methods of the IDirect3DDevice9 interface to perform DrawPrimitive-based rendering, create resources, work with system-level variables, adjust gamma ramp levels, work with palettes, and create shaders.

IDirect3DDevice9 Members

BeginScene | Begins a scene.
BeginStateBlock | Signals Microsoft Direct3D to begin recording a device-state block.
Clear | Clears one or more surfaces such as a render target, multiple render targets, a stencil buffer, and a depth buffer.
ColorFill | Allows an application to fill a rectangular area of a D3DPOOL_DEFAULT surface with a specified color.
CreateAdditionalSwapChain | Creates an additional swap chain for rendering multiple views.
CreateCubeTexture | Creates a cube texture resource.
CreateDepthStencilSurface | Creates a depth-stencil resource.
CreateIndexBuffer | Creates an index buffer.
CreateOffscreenPlainSurface | Create an off-screen surface.
CreatePixelShader | Creates a pixel shader.
CreateQuery | Creates a status query.
CreateRenderTarget | Creates a render-target surface.
CreateStateBlock | Creates a new state block that contains the values for all device states, vertex-related states, or pixel-related states.
CreateTexture | Creates a texture resource.
CreateVertexBuffer | Creates a vertex buffer.
CreateVertexDeclaration | Create a vertex shader declaration from the device and the vertex elements.
CreateVertexShader | Creates a vertex shader.
CreateVolumeTexture | Creates a volume texture resource.
DeletePatch | Frees a cached high-order patch.
DrawIndexedPrimitive | Based on indexing, renders the specified geometric primitive into an array of vertices.
DrawIndexedPrimitiveUP | Renders the specified geometric primitive with data specified by a user memory pointer.
DrawPrimitive | Renders a sequence of nonindexed, geometric primitives of the specified type from the current set of data input streams.
DrawPrimitiveUP | Renders data specified by a user memory pointer as a sequence of geometric primitives of the specified type.
DrawRectPatch | Draws a rectangular patch using the currently set streams.
DrawTriPatch | Draws a triangular patch using the currently set streams.
EndScene | Ends a scene that was begun by calling IDirect3DDevice9::BeginScene.
EndStateBlock | Signals Direct3D to stop recording a device-state block and retrieve a pointer to the state block interface.
EvictManagedResources | Evicts all managed resources, including both Direct3D and driver-managed resources.
GetAvailableTextureMem | Returns an estimate of the amount of available texture memory.
GetBackBuffer | Retrieves a back buffer from the device's swap chain.
GetClipPlane | Retrieves the coefficients of a user-defined clipping plane for the device.
GetClipStatus | Retrieves the clip status.
GetCreationParameters | Retrieves the creation parameters of the device.
GetCurrentTexturePalette | Retrieves the current texture palette.
GetDepthStencilSurface | Gets the depth-stencil surface owned by the Direct3DDevice object.
GetDeviceCaps | Retrieves the capabilities of the rendering device.
GetDirect3D | Returns an interface to the instance of the Direct3D object that created the device.
GetDisplayMode | Retrieves the display mode's spatial resolution, color resolution, and refresh frequency.
GetFrontBufferData | Generates a copy of the device's front buffer and places that copy in a system memory buffer provided by the application.
GetFVF | Gets the fixed vertex function declaration.
GetGammaRamp | Retrieves the gamma correction ramp for the swap chain.
GetIndices | Retrieves index data.
GetLight | Retrieves a set of lighting properties that this device uses.
GetLightEnable | Retrieves the activity status
GetMaterial | Retrieves the current material properties for the device.
GetNPatchMode | Gets the N-patch mode segments.
GetNumberOfSwapChains | Gets the number of implicit swap chains.
GetPaletteEntries | Retrieves palette entries.
GetPixelShader | Retrieves the currently set pixel shader.
GetPixelShaderConstantB | Gets a Boolean shader constant.
GetPixelShaderConstantF | Gets a floating-point shader constant.
GetPixelShaderConstantI | Gets an integer shader constant.
GetRasterStatus | Returns information describing the raster of the monitor on which the swap chain is presented.
GetRenderState | Retrieves a render-state value for a device.
GetRenderTarget | Retrieves a render-target surface.
GetRenderTargetData | Copies the render-target data from device memory to system memory.
GetSamplerState | Gets the sampler state value.
GetScissorRect | Gets the scissor rectangle.
GetSoftwareVertexProcessing | Gets the vertex processing (hardware or software) mode.
GetStreamSource | Retrieves a vertex buffer bound to the specified data stream.
GetStreamSourceFreq | Gets the stream source frequency divider value.
GetSwapChain | Gets a pointer to a swap chain.
GetTexture | Retrieves a texture assigned to a stage for a device.
GetTextureStageState | Retrieves a state value for an assigned texture.
GetTransform | Retrieves a matrix describing a transformation state.
GetVertexDeclaration | Gets a vertex shader declaration.
GetVertexShader | Retrieves the currently set vertex shader.
GetVertexShaderConstantB | Gets a Boolean vertex shader constant.
GetVertexShaderConstantF | Gets a floating-point vertex shader constant.
GetVertexShaderConstantI | Gets an integer vertex shader constant.
GetViewport | Retrieves the viewport parameters currently set for the device.
LightEnable | Enables or disables a set of lighting parameters within a device.
MultiplyTransform | Multiplies a device's world, view, or projection matrices by a specified matrix.
Present | Presents the contents of the next buffer in the sequence of back buffers owned by the device.
ProcessVertices | Applies the vertex processing defined by the vertex shader to the set of input data streams, generating a single stream of interleaved vertex data to the destination vertex buffer.
Reset | Resets the type, size, and format of the swap chain.
SetClipPlane | Sets the coefficients of a user-defined clipping plane for the device.
SetClipStatus | Sets the clip status.
SetCurrentTexturePalette | Sets the current texture palette.
SetCursorPosition | Sets the cursor position and update options.
SetCursorProperties | Sets properties for the cursor.
SetDepthStencilSurface | Sets the depth stencil surface.
SetDialogBoxMode | This method allows the use of Microsoft Windows Graphics Device Interface (GDI) dialog boxes in full-screen mode applications.
SetFVF | Sets the current vertex stream declaration.
SetGammaRamp | Sets the gamma correction ramp for the implicit swap chain. This method will affect the entire screen (not just the active window if you are running in windowed mode).
SetIndices | Sets index data.
SetLight | Assigns a set of lighting properties for this device.
SetMaterial | Sets the material properties for the device.
SetNPatchMode | Enable or disable N-patches.
SetPaletteEntries | Sets palette entries.
SetPixelShader | Sets the current pixel shader to a previously created pixel shader.
SetPixelShaderConstantB | Sets a Boolean shader constant.
SetPixelShaderConstantF | Sets a floating-point shader constant.
SetPixelShaderConstantI | Sets an integer shader constant.
SetRenderState | Sets a single device render-state parameter.
SetRenderTarget | Sets a new color buffer for the device.
SetSamplerState | Sets the sampler state value.
SetScissorRect | Sets the scissor rectangle.
SetSoftwareVertexProcessing | Use this method to switch between software and hardware vertex processing.
SetStreamSource | Binds a vertex buffer to a device data stream. For more information, see Setting the Stream Source.
SetStreamSourceFreq | Sets the stream source frequency divider value. This may be used to draw several instances of geometry.
SetTexture | Assigns a texture to a stage for a device.
SetTextureStageState | Sets the state value for the currently assigned texture.
SetTransform | Sets a single device transformation-related state.
SetVertexDeclaration | Sets a vertex shader declaration.
SetVertexShader | Sets the vertex shader.
SetVertexShaderConstantB | Sets a Boolean vertex shader constant.
SetVertexShaderConstantF | Sets a floating-point vertex shader constant.
SetVertexShaderConstantI | Sets an integer vertex shader constant.
SetViewport | Sets the viewport parameters for the device.
ShowCursor | Displays or hides the cursor.
StretchRect | Copy the contents of the source rectangle to the destination rectangle. The source rectangle can be stretched and filtered by the copy. This function is often used to change the aspect ratio of a video stream.
TestCooperativeLevel | Reports the current cooperative-level status of the Direct3D device for a windowed or full-screen application.
UpdateSurface | Copies rectangular subsets of pixels from one surface to another.
UpdateTexture | Updates the dirty portions of a texture.
ValidateDevice | Reports the device's ability to render the current texture-blending operations and arguments in a single pass.

Remarks

The IDirect3DDevice9 interface is obtained by calling the IDirect3D9::CreateDevice method.

This interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface methods.

The LPDIRECT3DDEVICE9 and PDIRECT3DDEVICE9 types are defined as pointers to the IDirect3DDevice9 interface.

typedef struct IDirect3DDevice9 *LPDIRECT3DDEVICE9, *PDIRECT3DDEVICE9;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

IDirect3D9::CreateDevice, Using Devices with the Sample Framework


IDirect3DDevice9::BeginScene Method

Begins a scene.

Syntax

HRESULT BeginScene(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

The method will fail with D3DERR_INVALIDCALL if IDirect3DDevice9::BeginScene is called while already in a IDirect3DDevice9::BeginScene/IDirect3DDevice9::EndScene pair. This happens only when IDirect3DDevice9::BeginScene is called twice without first calling IDirect3DDevice9::EndScene.

Remarks

Applications must call IDirect3DDevice9::BeginScene before performing any rendering and must call IDirect3DDevice9::EndScene when rendering is complete and before calling IDirect3DDevice9::BeginScene again.

If IDirect3DDevice9::BeginScene fails, the device was unable to begin the scene, and there is no need to call IDirect3DDevice9::EndScene. In fact, calls to IDirect3DDevice9::EndScene will fail if the previous IDirect3DDevice9::BeginScene failed. This applies to any application that creates multiple swap chains.

There should be at most one IDirect3DDevice9::BeginScene/IDirect3DDevice9::EndScene pair between any successive calls to present (either IDirect3DDevice9::Present or IDirect3DSwapChain9::Present). IDirect3DDevice9::BeginScene should be called once before any rendering is performed, and IDirect3DDevice9::EndScene should be called once after all rendering for a frame has been submitted to the runtime. To enable maximal parallelism between the CPU and the graphics accelerator, it is advantageous to call IDirect3DDevice9::EndScene as far ahead of calling present as possible.


IDirect3DDevice9::BeginStateBlock Method

Signals Microsoft Direct3D to begin recording a device-state block.

Syntax

HRESULT BeginStateBlock(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Applications can ensure that all recorded states are valid by calling the IDirect3DDevice9::ValidateDevice method prior to calling this method.

The following methods can be recorded in a state block, after calling IDirect3DDevice9::BeginStateBlock and before IDirect3DDevice9::EndStateBlock.

  • IDirect3DDevice9::LightEnable
  • IDirect3DDevice9::SetClipPlane
  • IDirect3DDevice9::SetCurrentTexturePalette
  • IDirect3DDevice9::SetFVF
  • IDirect3DDevice9::SetIndices
  • IDirect3DDevice9::SetLight
  • IDirect3DDevice9::SetMaterial
  • IDirect3DDevice9::SetNPatchMode
  • IDirect3DDevice9::SetPixelShader
  • IDirect3DDevice9::SetPixelShaderConstantB
  • IDirect3DDevice9::SetPixelShaderConstantF
  • IDirect3DDevice9::SetPixelShaderConstantI
  • IDirect3DDevice9::SetRenderState
  • IDirect3DDevice9::SetSamplerState
  • IDirect3DDevice9::SetScissorRect
  • IDirect3DDevice9::SetStreamSource
  • IDirect3DDevice9::SetStreamSourceFreq
  • IDirect3DDevice9::SetTexture
  • IDirect3DDevice9::SetTextureStageState
  • IDirect3DDevice9::SetTransform
  • IDirect3DDevice9::SetViewport
  • IDirect3DDevice9::SetVertexDeclaration
  • IDirect3DDevice9::SetVertexShader
  • IDirect3DDevice9::SetVertexShaderConstantB
  • IDirect3DDevice9::SetVertexShaderConstantF
  • IDirect3DDevice9::SetVertexShaderConstantI

The ordering of state changes in a state block is not guaranteed. If the same state is specified multiple times in a state block, only the last value is used.

See Also

IDirect3DDevice9::EndStateBlock, IDirect3DDevice9::CreateStateBlock


IDirect3DDevice9::Clear Method

Clears one or more surfaces such as a render target, multiple render targets, a stencil buffer, and a depth buffer.

Syntax

HRESULT Clear(

    DWORD Count,
    const D3DRECT *pRects,
    DWORD Flags,
    D3DCOLOR Color,
    float Z,
    DWORD Stencil
);

Parameters

Count
[in] Number of rectangles in the array at pRects. Must be set to 0 if pRects is NULL. May not be 0 if pRects is a valid pointer.
pRects
[in] Pointer to an array of D3DRECT structures that describe the rectangles to clear. Set a rectangle to the dimensions of the rendering target to clear the entire surface. Each rectangle uses screen coordinates that correspond to points on the render target. Coordinates are clipped to the bounds of the viewport rectangle. To indicate that the entire viewport rectangle is to be cleared, set this parameter to NULL and Count to 0.
Flags
[in] Combination of one or more D3DCLEAR flags that specify the surface(s) that will be cleared.
Color
[in] Clear a render target to this ARGB color.
Z
[in] Clear the depth buffer to this new z value which ranges from 0 to 1. See remarks.
Stencil
[in] Clear the stencil buffer to this new value which ranges from 0 to 2n–1 (n is the bit depth of the stencil buffer). See remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be:

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

Use this method to clear a surface including: a render target, all render targets in an MRT, a stencil buffer, or a depth buffer. Flags determines how many surfaces are cleared. Use pRects to clear a subset of a surface defined by an array of rectangles.

IDirect3DDevice9::Clear will fail if you:

  • Try to clear either the depth buffer or the stencil buffer of a render target that does not have an attached depth buffer.
  • Try to clear the stencil buffer when the depth buffer does not contain stencil data.


IDirect3DDevice9::ColorFill Method

Allows an application to fill a rectangular area of a D3DPOOL_DEFAULT surface with a specified color.

Syntax

HRESULT ColorFill(

    IDirect3DSurface9 *pSurface,
    CONST RECT *pRect,
    D3DCOLOR color
);

Parameters

pSurface
[in] Pointer to the surface to be filled.
pRect
[in] Pointer to the source rectangle. Using NULL means that the entire surface will be filled.
color
[in] Color used for filling.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This method can only be applied to a render target, a render-target texture surface, or an off-screen plain surface with a pool type of D3DPOOL_DEFAULT.

IDirect3DDevice9::ColorFill will work with all formats. However, when using a reference or software device, the only formats supported are D3DFMT_X1R5G5B5, D3DFMT_A1R5G5B5, D3DFMT_R5G6B5, D3DFMT_X8R8G8B8, D3DFMT_A8R8G8B8, D3DFMT_YUY2, D3DFMT_G8R8_G8B8, D3DFMT_UYVY, D3DFMT_R8G8_B8G8, D3DFMT_R16F, D3DFMT_G16R16F, D3DFMT_A16B16G16R16F, D3DFMT_R32F, D3DFMT_G32R32F, and D3DFMT_A32B32G32R32F.

When using a Microsoft DirectX 7.0 or DirectX 8.x driver, the only YUV formats supported are D3DFMT_UYVY and D3DFMT_YUY2.

See Also

D3DPOOL


IDirect3DDevice9::CreateAdditionalSwapChain Method

Creates an additional swap chain for rendering multiple views.

Syntax

HRESULT CreateAdditionalSwapChain(

    D3DPRESENT_PARAMETERS* pPresentationParameters,
    IDirect3DSwapChain9** ppSwapChain
);

Parameters

pPresentationParameters
[in, out] Pointer to a D3DPRESENT_PARAMETERS structure, containing the presentation parameters for the new swap chain. This value cannot be NULL.

Calling this method changes the value of members of the D3DPRESENT_PARAMETERS structure.

  • If BackBufferCount == 0, calling CreateAdditionalSwapChain will increase it to 1.
  • If the application is in windowed mode, and if either the BackBufferWidth or the BackBufferHeight == 0, they will be set to the client area width and height of the hwnd.
ppSwapChain
[out, retval] Address of a pointer to an IDirect3DSwapChain9 interface, representing the additional swap chain.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE This device does not support the queried multisample type.

D3DERR_DEVICELOST | The device has been lost but cannot be reset at this time. Therefore, rendering is not possible.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

There is always at least one swap chain (the implicit swap chain) for each device because Direct3D for Microsoft DirectX 9.0 has one swap chain as a property of the device.

Note that any given device can support only one full-screen swap chain.

D3DFMT_UNKNOWN can be specified for the windowed mode back buffer format when calling IDirect3D9::CreateDevice, IDirect3DDevice9::Reset and CreateAdditionalSwapChain. This means the application does not have to query the current desktop format before calling CreateDevice for windowed mode. For full-screen mode, the back buffer format must be specified.

See Also

Presenting Multiple Views in Windowed Mode


IDirect3DDevice9::CreateCubeTexture Method

Creates a cube texture resource.

Syntax

HRESULT CreateCubeTexture(

    UINT EdgeLength,
    UINT Levels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    IDirect3DCubeTexture9 **ppCubeTexture,
    HANDLE* pSharedHandle
);

Parameters

EdgeLength
[in] Size of the edges of all the top-level faces of the cube texture. The pixel dimensions of subsequent levels of each face will be the truncated value of half of the previous level's pixel dimension (independently). Each dimension clamps at a size of 1 pixel. Thus, if the division by 2 results in 0 (zero), 1 will be taken instead.
Levels
[in] Number of levels in each face of the cube texture. If this is zero, Microsoft Direct3D will generate all cube texture sublevels down to 1x1 pixels for each face for hardware that supports mipmapped cube textures. Call IDirect3DBaseTexture9::GetLevelCount to see the number of levels generated.
Usage
[in] Usage can be 0, which indicates no usage value. However, if usage is desired, use a combination of one or more D3DUSAGE constants. It is good practice to match the usage parameter in CreateCubeTexture with the behavior flags in IDirect3D9::CreateDevice. For more information, see Remarks.
Format
[in] Member of the D3DFORMAT enumerated type, describing the format of all levels in all faces of the cube texture.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the cube texture should be placed.
ppCubeTexture
[out, retval] Address of a pointer to an IDirect3DCubeTexture9 interface, representing the created cube texture resource.
pSharedHandle
[in] Reserved. Set this parameter to NULL.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Direct3D does not have enough display memory to perform the operation.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

A mipmap (texture) is a collection of successively downsampled (mipmapped) surfaces. On the other hand, a cube texture (created by IDirect3DDevice9::CreateCubeTexture) is a collection of six textures (mipmaps), one for each face. All faces must be present in the cube texture. Also, a cube map surface must be the same pixel size in all three dimensions (x, y, and z).

An application can discover support for Automatic Generation of Mipmaps in a particular format by calling IDirect3D9::CheckDeviceFormat with D3DUSAGE_AUTOGENMIPMAP. If IDirect3D9::CheckDeviceFormat returns D3DOK_NOAUTOGEN, IDirect3DDevice9::CreateCubeTexture will succeed but it will return a one-level texture.

See Also

D3DXCreateCubeTexture, D3DXCreateCubeTextureFromFile, D3DXCreateCubeTextureFromFileEx, D3DXCreateCubeTextureFromFileInMemory, D3DXCreateCubeTextureFromFileInMemoryEx, D3DXCreateCubeTextureFromResource, D3DXCreateCubeTextureFromResourceEx


IDirect3DDevice9::CreateDepthStencilSurface Method

Creates a depth-stencil resource.

Syntax

HRESULT CreateDepthStencilSurface(

    UINT Width,
    UINT Height,
    D3DFORMAT Format,
    D3DMULTISAMPLE_TYPE MultiSample,
    DWORD MultisampleQuality,
    BOOL Discard,
    IDirect3DSurface9** ppSurface,
    HANDLE* pSharedHandle
);

Parameters

Width
[in] Width of the depth-stencil surface, in pixels.
Height
[in] Height of the depth-stencil surface, in pixels.
Format
[in] Member of the D3DFORMAT enumerated type, describing the format of the depth-stencil surface. This value must be one of the enumerated depth-stencil formats for this device.
MultiSample
[in] Member of the D3DMULTISAMPLE_TYPE enumerated type, describing the multisampling buffer type. This value must be one of the allowed multisample types. When this surface is passed to IDirect3DDevice9::SetDepthStencilSurface, its multisample type must be the same as that of the render target set by IDirect3DDevice9::SetRenderTarget.
MultisampleQuality
[in] Quality level. The valid range is between zero and one less than the level returned by pQualityLevels used by IDirect3D9::CheckDeviceMultiSampleType. Passing a larger value returns the error D3DERR_INVALIDCALL. The MultisampleQuality values of paired render targets, depth stencil surfaces, and the MultiSample type must all match.
Discard
[in] Set this flag to TRUE to enable z-buffer discarding, and FALSE otherwise.

If this flag is set, the contents of the depth stencil buffer will be invalid after calling either IDirect3DDevice9::Present or IDirect3DDevice9::SetDepthStencilSurface with a different depth surface.

This flag has the same behavior as the constant, D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL, in D3DPRESENTFLAG.
ppSurface
[out, retval] Address of a pointer to an IDirect3DSurface9 interface, representing the created depth-stencil surface resource.
pSharedHandle
[in] Reserved. Set this parameter to NULL.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_NOTAVAILABLE This device does not support the queried multisample type.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The memory class of the depth-stencil buffer is always D3DPOOL_DEFAULT.

See Also

IDirect3DDevice9::UpdateSurface


IDirect3DDevice9::CreateIndexBuffer Method

Creates an index buffer.

Syntax

HRESULT CreateIndexBuffer(

    UINT Length,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    IDirect3DIndexBuffer9** ppIndexBuffer,
    HANDLE* pSharedHandle
);

Parameters

Length
[in] Size of the index buffer, in bytes.
Usage
[in] Usage can be 0, which indicates no usage value. However, if usage is desired, use a combination of one or more D3DUSAGE constants. It is good practice to match the usage parameter in CreateIndexBuffer with the behavior flags in IDirect3D9::CreateDevice. For more information, see Remarks.
Format
[in] Member of the D3DFORMAT enumerated type, describing the format of the index buffer. For more information, see Remarks. The valid settings are the following:
D3DFMT_INDEX16
Indices are 16 bits each.
D3DFMT_INDEX32
Indices are 32 bits each.
Pool
[in] Member of the D3DPOOL enumerated type, describing a valid memory class into which to place the resource.
ppIndexBuffer
[out, retval] Address of a pointer to an IDirect3DIndexBuffer9 interface, representing the created index buffer resource.
pSharedHandle
[in] Reserved. Set this parameter to NULL.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Index buffers are memory resources used to hold indices, they are similar to both surfaces and vertex buffers. The use of index buffers enables Direct3D to avoid unnecessary data copying and to place the buffer in the optimal memory type for the expected usage.

To use index buffers, create an index buffer, lock it, fill it with indices, unlock it, pass it to IDirect3DDevice9::SetIndices, set up the vertices, set up the vertex shader, and call IDirect3DDevice9::DrawIndexedPrimitive for rendering.

The MaxVertexIndex member of the D3DCAPS9 structure indicates the types of index buffers that are valid for rendering.

See Also

IDirect3DIndexBuffer9::GetDesc


IDirect3DDevice9::CreateOffscreenPlainSurface Method

Create an off-screen surface.

Syntax

HRESULT CreateOffscreenPlainSurface(

    UINT Width,
    UINT Height,
    D3DFORMAT Format,
    DWORD Pool,
    IDirect3DSurface9** ppSurface,
    HANDLE* pSharedHandle
);

Parameters

Width
[in] Width of the surface.
Height
[in] Height of the surface.
Format
[in] Format of the surface. See D3DFORMAT.
Pool
[in] Surface pool type. See D3DPOOL.
ppSurface
[out, retval] Pointer to the IDirect3DSurface9 interface created.
pSharedHandle
[in] Reserved. Set this parameter to NULL.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be the following:

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

D3DPOOL_SCRATCH will return a surface that has identical characteristics to a surface created by the Microsoft DirectX 8.x method CreateImageSurface.

D3DPOOL_DEFAULT is the appropriate pool for use with the IDirect3DDevice9::StretchRect and IDirect3DDevice9::ColorFill.

D3DPOOL_MANAGED is not allowed when creating an offscreen plain surface. For more information about memory pools, see D3DPOOL.

Off-screen plain surfaces are always lockable, regardless of their pool types.


IDirect3DDevice9::CreatePixelShader Method

Creates a pixel shader.

Syntax

HRESULT CreatePixelShader(

    CONST DWORD *pFunction,
    IDirect3DPixelShader9** ppShader
);

Parameters

pFunction
[in] Pointer to the pixel shader function token array, specifying the blending operations. This value cannot be NULL.
ppShader
[out, retval] Pointer to the returned pixel shader interface. See IDirect3DPixelShader9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

See Also

D3DXAssembleShader, D3DXAssembleShaderFromFile


IDirect3DDevice9::CreateQuery Method

Creates a status query.

Syntax

HRESULT CreateQuery(

    D3DQUERYTYPE Type,
    IDirect3DQuery9** ppQuery
);

Parameters

Type
[in] Identifies the query type. For more information, see D3DQUERYTYPE.
ppQuery
[out, retval] Returns a pointer to the query interface that manages the query object. See IDirect3DQuery9.

This parameter can be set to NULL to see if a query is supported. If the query is not supported, the method returns D3DERR_NOTAVAILABLE.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_NOTAVAILABLE or E_OUTOFMEMORY.

Remarks

This method is provided for both synchronous and asynchronous queries. It takes the place of GetInfo, which is no longer supported in Microsoft DirectX 9.0.

Synchronous and asynchronous queries are created with IDirect3DDevice9::CreateQuery with D3DQUERYTYPE. When a query has been created and the application programming interface (API) calls have been made that are being queried, use IDirect3DQuery9::Issue to issue a query and IDirect3DQuery9::GetData to get the results of the query.

See Also

Asynchronous Notification


IDirect3DDevice9::CreateRenderTarget Method

Creates a render-target surface.

Syntax

HRESULT CreateRenderTarget(

    UINT Width,
    UINT Height,
    D3DFORMAT Format,
    D3DMULTISAMPLE_TYPE MultiSample,
    DWORD MultisampleQuality,
    BOOL Lockable,
    IDirect3DSurface9** ppSurface,
    HANDLE* pSharedHandle
);

Parameters

Width
[in] Width of the render-target surface, in pixels.
Height
[in] Height of the render-target surface, in pixels.
Format
[in] Member of the D3DFORMAT enumerated type, describing the format of the render target.
MultiSample
[in] Member of the D3DMULTISAMPLE_TYPE enumerated type, which describes the multisampling buffer type. This parameter specifies the antialiasing type for this render target. When this surface is passed to IDirect3DDevice9::SetRenderTarget, its multisample type must be the same as that of the depth-stencil set by IDirect3DDevice9::SetDepthStencilSurface.
MultisampleQuality
[in] Quality level. The valid range is between zero and one less than the level returned by pQualityLevels used by IDirect3D9::CheckDeviceMultiSampleType. Passing a larger value returns the error, D3DERR_INVALIDCALL. The MultisampleQuality values of paired render targets, depth stencil surfaces, and the multisample type must all match.
Lockable
[in] Render targets are not lockable unless the application specifies TRUE for Lockable. Note that lockable render targets reduce performance on some graphics hardware.
ppSurface
[out, retval] Address of a pointer to an IDirect3DSurface9 interface.
pSharedHandle
[in] Reserved. Set this parameter to NULL.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_NOTAVAILABLE | This device does not support the queried multisample type.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Not enough display memory to perform the operation.
E_OUTOFMEMORY | Could not allocate sufficient memory to complete the call.

Remarks

Render-target surfaces are placed in the D3DPOOL_DEFAULT memory class.

The creation of lockable, multisampled render targets is not supported.


IDirect3DDevice9::CreateStateBlock Method

Creates a new state block that contains the values for all device states, vertex-related states, or pixel-related states.

Syntax

HRESULT CreateStateBlock(

    D3DSTATEBLOCKTYPE Type,
    IDirect3DStateBlock9** ppSB
);

Parameters

Type
[in] Type of state data that the method should capture. This parameter can be set to a value defined in the D3DSTATEBLOCKTYPE enumerated type.
ppSB
[out, retval] Pointer to a state block interface. See IDirect3DStateBlock9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Vertex-related device states typically refer to those states that affect how the system processes vertices. Pixel-related states generally refer to device states that affect how the system processes pixel or depth-buffer data during rasterization. Some states are contained in both groups.

See Also

IDirect3DDevice9::BeginStateBlock, IDirect3DDevice9::EndStateBlock


IDirect3DDevice9::CreateTexture Method

Creates a texture resource.

Syntax

HRESULT CreateTexture(

    UINT Width,
    UINT Height,
    UINT Levels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    IDirect3DTexture9** ppTexture,
    HANDLE* pSharedHandle
);

Parameters

Width
[in] Width of the top-level of the texture, in pixels. The pixel dimensions of subsequent levels will be the truncated value of half of the previous level's pixel dimension (independently). Each dimension clamps at a size of 1 pixel. Thus, if the division by 2 results in 0, 1 will be taken instead.
Height
[in] Height of the top-level of the texture, in pixels. The pixel dimensions of subsequent levels will be the truncated value of half of the previous level's pixel dimension (independently). Each dimension clamps at a size of 1 pixel. Thus, if the division by 2 results in 0, 1 will be taken instead.
Levels
[in] Number of levels in the texture. If this is zero, Microsoft Direct3D will generate all texture sublevels down to 1 by 1 pixels for hardware that supports mipmapped textures. Call IDirect3DBaseTexture9::GetLevelCount to see the number of levels generated.
Usage
[in] Usage can be 0, which indicates no usage value. However, if usage is desired, use a combination of one or more D3DUSAGE constants. It is good practice to match the usage parameter with the behavior flags in IDirect3D9::CreateDevice.
Format
[in] Member of the D3DFORMAT enumerated type, describing the format of all levels in the texture.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
ppTexture
[out, retval] Pointer to an IDirect3DTexture9 interface, representing the created texture resource.
pSharedHandle
[in] Reserved. Set this parameter to NULL.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Direct3D does not have enough display memory to perform the operation.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

An application can discover support for Automatic Generation of Mipmaps in a particular format by calling IDirect3D9::CheckDeviceFormat with D3DUSAGE_AUTOGENMIPMAP. If IDirect3D9::CheckDeviceFormat returns D3DOK_NOAUTOGEN, IDirect3DDevice9::CreateTexture will succeed but it will return a one-level texture.

See Also

D3DXCreateTexture, D3DXCreateTextureFromFile, D3DXCreateTextureFromFileEx, D3DXCreateTextureFromFileInMemory, D3DXCreateTextureFromFileInMemoryEx, D3DXCreateTextureFromResource, D3DXCreateTextureFromResourceEx


IDirect3DDevice9::CreateVertexBuffer Method

Creates a vertex buffer.

Syntax

HRESULT CreateVertexBuffer(

    UINT Length,
    DWORD Usage,
    DWORD FVF,
    D3DPOOL Pool,
    IDirect3DVertexBuffer9** ppVertexBuffer,
    HANDLE* pSharedHandle
);

Parameters

Length
[in] Size of the vertex buffer, in bytes. For flexible vertex format (FVF) vertex buffers, Length must be large enough to contain at least one vertex, but it need not be a multiple of the vertex size. Length is not validated for non-FVF buffers. See Remarks.
Usage
[in] Usage can be 0, which indicates no usage value. However, if usage is desired, use a combination of one or more D3DUSAGE constants. It is good practice to match the usage parameter in CreateVertexBuffer with the behavior flags in IDirect3D9::CreateDevice. For more information, see Remarks.
FVF
[in] Combination of D3DFVF, a usage specifier that describes the vertex format of the vertices in this buffer. If this parameter is set to a valid FVF code, the created vertex buffer is an FVF vertex buffer (see Remarks). Otherwise, if this parameter is set to zero, the vertex buffer is a non-FVF vertex buffer.
Pool
[in] Member of the D3DPOOL enumerated type, describing a valid memory class into which to place the resource.
ppVertexBuffer
[out, retval] Address of a pointer to an IDirect3DVertexBuffer9 interface, representing the created vertex buffer resource.
pSharedHandle
[in] Reserved. Set this parameter to NULL.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

A vertex buffer can be used with either hardware or software vertex processing. This is determined by how the device and the vertex buffer are created.

When a device is created, CreateDevice uses the behavior flag to determine whether to process vertices in hardware or software. There are three possibilities:

  • Process vertices in hardware by setting D3DCREATE_HARDWARE_VERTEXPROCESSING.
  • Process vertices in software by setting D3DCREATE_SOFTWARE_VERTEXPROCESSING.
  • Process vertices in either hardware or software by setting D3DCREATE_MIXED_VERTEXPROCESSING.

Mixed-mode devices might need to switch between software and hardware processing (using IDirect3DDevice9::SetSoftwareVertexProcessing) after the device is created.

When a vertex buffer is created, CreateVertexBuffer uses the usage parameter to decide whether to process vertices in hardware or software.

  • If CreateDevice uses D3DCREATE_HARDWARE_VERTEXPROCESSING, CreateVertexBuffer must use 0.
  • If CreateDevice uses D3DCREATE_SOFTWARE_VERTEXPROCESSING, CreateVertexBuffer must use either 0 or D3DUSAGE_SOFTWAREPROCESSING. For either value, vertices will be processed in software.
  • If CreateDevice uses D3DCREATE_MIXED_VERTEXPROCESSING, CreateVertexBuffer can use either 0 or D3DUSAGE_SOFTWAREPROCESSING.

To use a vertex buffer with a mixed mode device, create a single vertex buffer which can be used for both hardware or software processing. Use IDirect3DDevice9::SetStreamSource to set the current vertex buffer and use IDirect3DDevice9::SetRenderState, if necessary, to change the device behavior to match. It is recommended that the vertex buffer usage matches the device behavior. Note that a vertex buffer created for software processing cannot be located in video memory.

The IDirect3DDevice9 interface supports rendering of primitives using vertex data stored in vertex buffer objects. Vertex buffers are created from the IDirect3DDevice9, and are usable only with the IDirect3DDevice9 object from which they are created.

When set to a nonzero value, which must be a valid FVF code, the FVF parameter indicates that the buffer content is to be characterized by an FVF code. A vertex buffer that is created with an FVF code is referred to as an FVF vertex buffer. For more information, see FVF Vertex Buffers.

Non-FVF buffers can be used to interleave data during multipass rendering or multitexture rendering in a single pass. To do this, one buffer contains geometry data and the others contain texture coordinates for each texture to be rendered. When rendering, the buffer containing the geometry data is interleaved with each of the buffers containing the texture coordinates. If FVF buffers were used instead, each of them would need to contain identical geometry data in addition to the texture coordinate data specific to each texture rendered. This would result in either a speed or memory penalty, depending on the strategy used. For more information about texture coordinates, see Texture Coordinates.

See Also

IDirect3DVertexBuffer9::GetDesc, IDirect3DDevice9::ProcessVertices


IDirect3DDevice9::CreateVertexDeclaration Method

Create a vertex shader declaration from the device and the vertex elements.

Syntax

HRESULT CreateVertexDeclaration(

    CONST D3DVERTEXELEMENT9* pVertexElements,
    IDirect3DVertexDeclaration9** ppDecl
);

Parameters

pVertexElements
[in] An array of vertex elements.
ppDecl
[out, retval] Pointer to an IDirect3DVertexDeclaration9 pointer that returns the created vertex shader declaration.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

See the Vertex Declaration page for a detailed description of how to map vertex declarations between different versions of Microsoft DirectX.


IDirect3DDevice9::CreateVertexShader Method

Creates a vertex shader.

Syntax

HRESULT CreateVertexShader(

    const DWORD *pFunction,
    IDirect3DVertexShader9** ppShader
);

Parameters

pFunction
[in] Pointer to the vertex shader function token array. This parameter defines the operations to apply to each vertex.
ppShader
[out, retval] Pointer to the returned vertex shader interface. See IDirect3DVertexShader9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

When a device is created, IDirect3D9::CreateDevice uses the behavior flag to determine whether to process vertices in hardware or software. There are three possibilities.

  • Process vertices in hardware by setting D3DCREATE_HARDWARE_VERTEXPROCESSING.
  • Process vertices in software by setting D3DCREATE_SOFTWARE_VERTEXPROCESSING.

  • Process vertices in either hardware or software by setting D3DCREATE_MIXED_VERTEXPROCESSING.

    Mixed-mode devices might need to switch between software and hardware processing after the device is created. In this case, use IDirect3DDevice9::SetSoftwareVertexProcessing.

See Also

IDirect3D9::CreateDevice, D3DXAssembleShader


IDirect3DDevice9::CreateVolumeTexture Method

Creates a volume texture resource.

Syntax

HRESULT CreateVolumeTexture(

    UINT Width,
    UINT Height,
    UINT Depth,
    UINT Levels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    IDirect3DVolumeTexture9** ppVolumeTexture,
    HANDLE* pSharedHandle
);

Parameters

Width
[in] Width of the top-level of the volume texture, in pixels. This value must be a power of two if the D3DPTEXTURECAPS_VOLUMEMAP_POW2 member of D3DCAPS9 is set. The pixel dimensions of subsequent levels will be the truncated value of half of the previous level's pixel dimension (independently). Each dimension clamps at a size of 1 pixel. Thus, if the division by two results in 0 (zero), 1 will be taken instead. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
Height
[in] Height of the top-level of the volume texture, in pixels. This value must be a power of two if the D3DPTEXTURECAPS_VOLUMEMAP_POW2 member of D3DCAPS9 is set. The pixel dimensions of subsequent levels will be the truncated value of half of the previous level's pixel dimension (independently). Each dimension clamps at a size of 1 pixel. Thus, if the division by 2 results in 0 (zero), 1 will be taken instead. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
Depth
[in] Depth of the top-level of the volume texture, in pixels. This value must be a power of two if the D3DPTEXTURECAPS_VOLUMEMAP_POW2 member of D3DCAPS9 is set. The pixel dimensions of subsequent levels will be the truncated value of half of the previous level's pixel dimension (independently). Each dimension clamps at a size of 1 pixel. Thus, if the division by 2 results in 0 (zero), 1 will be taken instead. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
Levels
[in] Number of levels in the texture. If this is zero, Microsoft Direct3D will generate all texture sublevels down to 1x1 pixels for hardware that supports mipmapped volume textures. Call IDirect3DBaseTexture9::GetLevelCount to see the number of levels generated.
Usage
[in] Usage can be 0, which indicates no usage value. If usage is desired, use D3DUSAGE_DYNAMIC or D3DUSAGE_SOFTWAREPROCESSING. For more information, see D3DUSAGE.
Format
[in] Member of the D3DFORMAT enumerated type, describing the format of all levels in the volume texture.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the volume texture should be placed.
ppVolumeTexture
[out, retval] Address of a pointer to an IDirect3DVolumeTexture9 interface, representing the created volume texture resource.
pSharedHandle
[in] Reserved. Set this parameter to NULL.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Direct3D does not have enough display memory to perform the operation.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

See Also

D3DXCreateVolumeTexture, D3DXCreateVolumeTextureFromFile, D3DXCreateVolumeTextureFromFileEx, D3DXCreateVolumeTextureFromFileInMemory, D3DXCreateVolumeTextureFromFileInMemoryEx, D3DXCreateVolumeTextureFromResource, D3DXCreateVolumeTextureFromResourceEx


IDirect3DDevice9::DeletePatch Method

Frees a cached high-order patch.

Syntax

HRESULT DeletePatch(

    UINT Handle
);

Parameters

Handle
[in] Handle of the cached high-order patch to delete.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

See Also

IDirect3DDevice9::DrawRectPatch, IDirect3DDevice9::DrawTriPatch, Drawing Patches


IDirect3DDevice9::DrawIndexedPrimitive Method

Based on indexing, renders the specified geometric primitive into an array of vertices.

Syntax

HRESULT DrawIndexedPrimitive(

    D3DPRIMITIVETYPE Type,
    INT BaseVertexIndex,
    UINT MinIndex,
    UINT NumVertices,
    UINT StartIndex,
    UINT PrimitiveCount
);

Parameters

Type
[in] Member of the D3DPRIMITIVETYPE enumerated type, describing the type of primitive to render. D3DPT_POINTLIST is not supported with this method. See Remarks.
BaseVertexIndex
[in] Offset from the start of the vertex buffer to the first vertex index. An index of 0 in the index buffer refers to this location in the vertex buffer.
MinIndex
[in] Minimum vertex index for vertices used during this call. This is a zero based index relative to BaseVertexIndex.
NumVertices
[in] Number of vertices used during this call. The first vertex is located at index: BaseVertexIndex + MinIndex.
StartIndex
[in] Index of the first index to use when accesssing the vertex buffer. Beginning at StartIndex to index vertices from the vertex buffer.
PrimitiveCount
[in] Number of primitives to render. The number of vertices used is a function of the primitive count and the primitive type. The maximum number of primitives allowed is determined by checking the MaxPrimitiveCount member of the D3DCAPS9 structure.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be the following:

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This method draws indexed primitives from the current set of data input streams. MinIndex and all the indices in the index stream are relative to the BaseVertexIndex.

The MinIndex and NumVertices parameters specify the range of vertex indices used for each IDirect3DDevice9::DrawIndexedPrimitive call. These are used to optimize vertex processing of indexed primitives by processing a sequential range of vertices prior to indexing into these vertices. It is invalid for any indices used during this call to reference any vertices outside of this range.

IDirect3DDevice9::DrawIndexedPrimitive fails if no index array is set.

The D3DPT_POINTLIST member of the D3DPRIMITIVETYPE enumerated type is not supported and is not a valid type for this method.

When converting a fixed function legacy application to Microsoft DirectX 9.0, you must add a call to IDirect3DDevice9::SetFVF before you make any Draw calls.

See Also

Rendering from Vertex and Index Buffers, IDirect3DDevice9::DrawPrimitive


IDirect3DDevice9::DrawIndexedPrimitiveUP Method

Renders the specified geometric primitive with data specified by a user memory pointer.

Syntax

HRESULT DrawIndexedPrimitiveUP(

    D3DPRIMITIVETYPE PrimitiveType,
    UINT MinVertexIndex,
    UINT NumVertices,
    UINT PrimitiveCount,
    const void *pIndexData,
    D3DFORMAT IndexDataFormat,
    CONST void* pVertexStreamZeroData,
    UINT VertexStreamZeroStride
);

Parameters

PrimitiveType
[in] Member of the D3DPRIMITIVETYPE enumerated type, describing the type of primitive to render.
MinVertexIndex
[in] Minimum vertex index. This is a zero based index.
NumVertices
[in] Number of vertices used during this call. The first vertex is located at index: MinVertexIndex.
PrimitiveCount
[in] Number of primitives to render. The maximum number of primitives allowed is determined by checking the MaxPrimitiveCount member of the D3DCAPS9 structure (the number of indices is a function of the primitive count and the primitive type),
pIndexData
[in] User memory pointer to the index data.
IndexDataFormat
[in] Member of the D3DFORMAT enumerated type, describing the format of the index data. The valid settings are either:
  • D3DFMT_INDEX16
  • D3DFMT_INDEX32
pVertexStreamZeroData
[in] User memory pointer to the vertex data. The vertex data must be in stream 0.
VertexStreamZeroStride
[in] The number of bytes of data for each vertex.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be the following:

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This method is intended for use in applications that are unable to store their vertex data in vertex buffers. This method supports only a single vertex stream, which must be declared as stream 0.

Following any IDirect3DDevice9::DrawIndexedPrimitiveUP call, the stream 0 settings, referenced by IDirect3DDevice9::GetStreamSource, are set to NULL. Also, the index buffer setting for IDirect3DDevice9::SetIndices is set to NULL.

The vertex data passed to IDirect3DDevice9::DrawIndexedPrimitiveUP does not need to persist after the call. Microsoft Direct3D completes its access to that data prior to returning from the call.

When converting a fixed-function legacy application to Microsoft DirectX 9.0, you must add a call to IDirect3DDevice9::SetFVF before making any Draw calls.

See Also

Rendering from Vertex and Index Buffers, IDirect3DDevice9::DrawPrimitive


IDirect3DDevice9::DrawPrimitive Method

Renders a sequence of nonindexed, geometric primitives of the specified type from the current set of data input streams.

Syntax

HRESULT DrawPrimitive(

    D3DPRIMITIVETYPE PrimitiveType,
    UINT StartVertex,
    UINT PrimitiveCount
);

Parameters

PrimitiveType
[in] Member of the D3DPRIMITIVETYPE enumerated type, describing the type of primitive to render.
StartVertex
[in] Index of the first vertex to load. Beginning at StartVertex the correct number of vertices will be read out of the vertex buffer.
PrimitiveCount
[in] Number of primitives to render. The maximum number of primitives allowed is determined by checking the MaxPrimitiveCount member of the D3DCAPS9 structure. PrimitiveCount is the number of primitives as determined by the primitive type. If it is a line list, each primitive has two vertices. If it is a triangle list, each primitive has three vertices.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

When converting a fixed function legacy application to Microsoft DirectX 9.0, you must add a call to IDirect3DDevice9::SetFVF before you make any Draw calls.

See Also

Rendering from Vertex and Index Buffers, IDirect3DDevice9::DrawIndexedPrimitive


IDirect3DDevice9::DrawPrimitiveUP Method

Renders data specified by a user memory pointer as a sequence of geometric primitives of the specified type.

Syntax

HRESULT DrawPrimitiveUP(

    D3DPRIMITIVETYPE PrimitiveType,
    UINT PrimitiveCount,
    CONST void* pVertexStreamZeroData,
    UINT VertexStreamZeroStride
);

Parameters

PrimitiveType
[in] Member of the D3DPRIMITIVETYPE enumerated type, describing the type of primitive to render.
PrimitiveCount
[in] Number of primitives to render. The maximum number of primitives allowed is determined by checking the MaxPrimitiveCount member of the D3DCAPS9 structure.
pVertexStreamZeroData
[in] User memory pointer to the vertex data. The vertex data must be in stream 0.
VertexStreamZeroStride
[in] The number of bytes of data for each vertex.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This method is intended for use in applications that are unable to store their vertex data in vertex buffers. This method supports only a single vertex stream. The effect of this call is to use the provided vertex data pointer and stride for vertex stream 0. It is invalid to have the declaration of the current vertex shader refer to vertex streams other than stream 0.

Following any IDirect3DDevice9::DrawPrimitiveUP call, the stream 0 settings, referenced by IDirect3DDevice9::GetStreamSource, are set to NULL.

The vertex data passed to IDirect3DDevice9::DrawPrimitiveUP does not need to persist after the call. Microsoft Direct3D completes its access to that data prior to returning from the call.

When converting a fixed function legacy application to Microsoft DirectX 9.0, you must add a call to IDirect3DDevice9::SetFVF before you make any Draw calls.

See Also

Rendering from Vertex and Index Buffers, IDirect3DDevice9::DrawIndexedPrimitiveUP


IDirect3DDevice9::DrawRectPatch Method

Draws a rectangular patch using the currently set streams.

Syntax

HRESULT DrawRectPatch(

    UINT Handle,
    const float* pNumSegs,
    const D3DRECTPATCH_INFO* pRectPatchInfo
);

Parameters

Handle
[in] Handle to the rectangular patch to draw.
pNumSegs
[in] Pointer to an array of four floating-point values that identify the number of segments each edge of the rectangle patch should be divided into when tessellated. See D3DRECTPATCH_INFO.
pRectPatchInfo
[in] Pointer to a D3DRECTPATCH_INFO structure, describing the rectangular patch to draw.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

For static patches: Set the vertex shader, set the appropriate streams, supply patch information in the pRectPatchInfo parameter, and specify a handle so that Microsoft Direct3D can capture and cache information. Call IDirect3DDevice9::DrawRectPatch subsequently with pRectPatchInfo set to NULL to efficiently draw the patch. When drawing a cached patch, the currently set streams are ignored. Override the cached pNumSegs by specifying a new value for pNumSegs. When rendering a cached patch, you must set the same vertex shader that was set when it was captured.

Calling IDirect3DDevice9::DrawRectPatch with a handle invalidates the same handle cached by a previous IDirect3DDevice9::DrawTriPatch call.

For dynamic patches, the patch data changes for every rendering of the patch, so it is not efficient to cache information. The application can convey this to Direct3D by setting Handle to 0. In this case, Direct3D draws the patch using the currently set streams and the pNumSegs values, and does not cache any information. It is not valid to simultaneously set Handle to 0 and pRectPatchInfo to NULL.

See Also

IDirect3DDevice9::DeletePatch, Drawing Patches


IDirect3DDevice9::DrawTriPatch Method

Draws a triangular patch using the currently set streams.

Syntax

HRESULT DrawTriPatch(

    UINT Handle,
    const float* pNumSegs,
    const D3DTRIPATCH_INFO* pTriPatchInfo
);

Parameters

Handle
[in] Handle to the triangular patch to draw.
pNumSegs
[in] Pointer to an array of three floating-point values that identify the number of segments each edge of the triangle patch should be divided into when tessellated. See D3DTRIPATCH_INFO.
pTriPatchInfo
[in] Pointer to a D3DTRIPATCH_INFO structure, describing the triangular high-order patch to draw.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

For static patches: Set the vertex shader, set the appropriate streams, supply patch information in the pTriPatchInfo parameter, and specify a handle so that Microsoft Direct3D can capture and cache information. To efficiently draw the patch, call IDirect3DDevice9::DrawTriPatch with pTriPatchInfo set to NULL. When drawing a cached patch, the currently set streams are ignored. Override the cached pNumSegs by specifying a new value for pNumSegs. When rendering a cached patch, you must set the same vertex shader that was set when it was captured.

Calling IDirect3DDevice9::DrawTriPatch with a handle invalidates the same handle cached by a previous IDirect3DDevice9::DrawRectPatch call.

For dynamic patches, the patch data changes for every rendering of the patch so it is not efficient to cache information. The application can convey this to Direct3D by setting Handle to 0. In this case, Direct3D draws the patch using the currently set streams and the pNumSegs values, and does not cache any information. It is not valid to simultaneously set Handle to 0 and pTriPatchInfo to NULL.

See Also

Using Higher-Order Primitives


IDirect3DDevice9::EndScene Method

Ends a scene that was begun by calling IDirect3DDevice9::BeginScene.

Syntax

HRESULT EndScene(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

The method will fail with D3DERR_INVALIDCALL if IDirect3DDevice9::BeginScene is called while already in a IDirect3DDevice9::BeginScene/IDirect3DDevice9::EndScene pair. This happens only when IDirect3DDevice9::BeginScene is called twice without first calling IDirect3DDevice9::EndScene.

Remarks

When this method succeeds, the scene has been queued up for rendering by the driver. This is not a synchronous method, so the scene is not guaranteed to have completed rendering when this method returns.

Applications must call IDirect3DDevice9::BeginScene before performing any rendering and must call IDirect3DDevice9::EndScene when rendering is complete and before calling IDirect3DDevice9::BeginScene again.

If IDirect3DDevice9::BeginScene fails, the device was unable to begin the scene, and there is no need to call IDirect3DDevice9::EndScene. In fact, calls to IDirect3DDevice9::EndScene will fail if the previous IDirect3DDevice9::BeginScene failed. This applies to any application that creates multiple swap chains.

There should be at most one IDirect3DDevice9::BeginScene/IDirect3DDevice9::EndScene pair between any successive calls to present (either IDirect3DDevice9::Present or IDirect3DSwapChain9::Present). IDirect3DDevice9::BeginScene should be called once before any rendering is performed, and IDirect3DDevice9::EndScene should be called once after all rendering for a frame has been submitted to the runtime. To enable maximal parallelism between the CPU and the graphics accelerator, it is advantageous to call IDirect3DDevice9::EndScene as far ahead of calling present as possible.


IDirect3DDevice9::EndStateBlock Method

Signals Microsoft Direct3D to stop recording a device-state block and retrieve a pointer to the state block interface.

Syntax

HRESULT EndStateBlock(

    IDirect3DStateBlock9 **ppSB
);

Parameters

ppSB
[in, retval] Pointer to a state block interface. See IDirect3DStateBlock9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

See Also

IDirect3DDevice9::BeginStateBlock, IDirect3DDevice9::CreateStateBlock


IDirect3DDevice9::EvictManagedResources Method

Evicts all managed resources, including both Microsoft Direct3D and driver-managed resources.

Syntax

HRESULT EvictManagedResources(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_OUTOFVIDEOMEMORY | Direct3D does not have enough display memory to perform the operation.
D3DERR_COMMAND_UNPARSED | The driver could not parse this batch of commands.

Remarks

This function causes only the D3DPOOL_DEFAULT copy of resources to be evicted. The resource copy in system memory is retained. See D3DPOOL.


IDirect3DDevice9::GetAvailableTextureMem Method

Returns an estimate of the amount of available texture memory.

Syntax

UINT GetAvailableTextureMem(VOID);

Return Value

The function returns an estimate of the available texture memory.

Remarks

The returned value is rounded to the nearest MB. This is done to reflect the fact that video memory estimates are never precise due to alignment and other issues that affect consumption by certain resources. Applications can use this value to make gross estimates of memory availability to make large-scale resource decisions such as how many levels of a mipmap to attempt to allocate, but applications cannot use this value to make small-scale decisions such as if there is enough memory left to allocate another resource.


IDirect3DDevice9::GetBackBuffer Method

Retrieves a back buffer from the device's swap chain.

Syntax

HRESULT GetBackBuffer(

    UINT iSwapChain,
    UINT BackBuffer,
    D3DBACKBUFFER_TYPE Type,
    IDirect3DSurface9 **ppBackBuffer
);

Parameters

iSwapChain
[in] An unsigned integer specifying the swap chain.
BackBuffer
[in] Index of the back buffer object to return. Back buffers are numbered from 0 to the total number of back buffers minus one. A value of 0 returns the first back buffer, not the front buffer. The front buffer is not accessible through this method. Use IDirect3DDevice9::GetFrontBufferData to retrieve a copy of the front buffer.
Type
[in] Stereo view is not supported in Microsoft DirectX 9.0, so the only valid value for this parameter is D3DBACKBUFFER_TYPE_MONO.
ppBackBuffer
[out, retval] Address of a pointer to an IDirect3DSurface9 interface, representing the returned back buffer surface.

Return Value

If the method succeeds, the return value is D3D_OK.

If BackBuffer equals or exceeds the total number of back buffers, then the function fails and returns D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DSurface9 interface. Failure to call IUnknown::Release when finished using this IDirect3DSurface9 interface results in a memory leak.

See Also

IDirect3DDevice9::GetFrontBufferData


IDirect3DDevice9::GetClipPlane Method

Retrieves the coefficients of a user-defined clipping plane for the device.

Syntax

HRESULT GetClipPlane(

    DWORD Index,
    float *pPlane
);

Parameters

Index
[in] Index of the clipping plane for which the plane equation coefficients are retrieved.
pPlane
[out] Pointer to a four-element array of values that represent the coefficients of the clipping plane in the form of the general plane equation. See Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is D3DERR_INVALIDCALL. This error indicates that the value in Index exceeds the maximum clipping plane index supported by the device, or that the array at pPlane is not large enough to contain four floating-point values.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other values in D3DCREATE."

The coefficients that this method reports take the form of the general plane equation. If the values in the array at pPlane were labeled A, B, C, and D in the order that they appear in the array, they would fit into the general plane equation so that Ax + By + Cz + Dw = 0. A point with homogeneous coordinates (x, y, z, w) is visible in the half space of the plane if Ax + By + Cz + Dw >= 0. Points that exist on or behind the clipping plane are clipped from the scene.

The plane equation used by this method exists in world space and is set by a previous call to the IDirect3DDevice9::SetClipPlane method.

See Also

IDirect3DDevice9::SetClipPlane


IDirect3DDevice9::GetClipStatus Method

Retrieves the clip status.

Syntax

HRESULT GetClipStatus(

    D3DCLIPSTATUS9 *pClipStatus
);

Parameters

pClipStatus
[out] Pointer to a D3DCLIPSTATUS9 structure that describes the clip status.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the argument is invalid.

Remarks

When clipping is enabled during vertex processing (by IDirect3DDevice9::ProcessVertices, IDirect3DDevice9::DrawPrimitive, or other drawing functions), Microsoft Direct3D computes a clip code for every vertex. The clip code is a combination of D3DCS_* bits. When a vertex is outside a particular clipping plane, the corresponding bit is set in the clipping code. Direct3D maintains the clip status using D3DCLIPSTATUS9, which has ClipUnion and ClipIntersection members. ClipUnion is a bitwise "OR" of all vertex clip codes and ClipIntersection is a bitwise "AND" of all vertex clip codes. Initial values are zero for ClipUnion and 0xFFFFFFFF for ClipIntersection. When D3DRS_CLIPPING is set to FALSE, ClipUnion and ClipIntersection are set to zero. Direct3D updates the clip status during drawing calls. To compute clip status for a particular object, set ClipUnion and ClipIntersection to their initial value and continue drawing.

Clip status is not updated by IDirect3DDevice9::DrawRectPatch and IDirect3DDevice9::DrawTriPatch because there is no software emulation for them.

Clip status is used during software vertex processing. Therefore, this method is not supported on pure or nonpure hardware processing devices. For more information about pure devices, see D3DCREATE.

See Also

IDirect3DDevice9::SetClipStatus


IDirect3DDevice9::GetCreationParameters Method

Retrieves the creation parameters of the device.

Syntax

HRESULT GetCreationParameters(

    D3DDEVICE_CREATION_PARAMETERS *pParameters
);

Parameters

pParameters
[out] Pointer to a D3DDEVICE_CREATION_PARAMETERS structure, describing the creation parameters of the device.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the argument is invalid.

Remarks

You can query the AdapterOrdinal member of the returned D3DDEVICE_CREATION_PARAMETERS structure to retrieve the ordinal of the adapter represented by this device.


IDirect3DDevice9::GetCurrentTexturePalette Method

Retrieves the current texture palette.

Syntax

HRESULT GetCurrentTexturePalette(

    UINT *pPaletteNumber
);

Parameters

pPaletteNumber
[out, retval] Pointer to a returned value that identifies the current texture palette.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DDevice9::SetCurrentTexturePalette, Texture Palettes


IDirect3DDevice9::GetDepthStencilSurface Method

Gets the depth-stencil surface owned by the Direct3DDevice object.

Syntax

HRESULT GetDepthStencilSurface(

    IDirect3DSurface9 **ppZStencilSurface
);

Parameters

ppZStencilSurface
[out, retval] Address of a pointer to an IDirect3DSurface9 interface, representing the returned depth-stencil surface.

Return Value

If the method succeeds, the return value is D3D_OK.

If the device doesn't have a depth stencil buffer associated with it, the return value will be D3DERR_NOTFOUND. Otherwise, if the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DSurface9 interface. Failure to call IUnknown::Release when finished using this IDirect3DSurface9 interface results in a memory leak.

See Also

IDirect3DDevice9::SetDepthStencilSurface


IDirect3DDevice9::GetDeviceCaps Method

Retrieves the capabilities of the rendering device.

Syntax

HRESULT GetDeviceCaps(

    D3DCAPS9 *pCaps
);

Parameters

pCaps
[out] Pointer to a D3DCAPS9 structure, describing the returned device.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

IDirect3DDevice9::GetDeviceCaps retrieves the software vertex pipeline capabilities when the device is being used in software vertex processing mode.


IDirect3DDevice9::GetDirect3D Method

Returns an interface to the instance of the Microsoft Direct3D object that created the device.

Syntax

HRESULT GetDirect3D(

    IDirect3D9 **ppD3D9
);

Parameters

ppD3D9
[out, retval] Address of a pointer to an IDirect3D9 interface, representing the interface of the Direct3D object that created the device.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Calling IDirect3DDevice9::GetDirect3D increases the reference count on the interface, so applications should call IUnknown::Release through this pointer when finished with the interface.

Note Calling this method will increase the internal reference count on the IDirect3D9 interface. Failure to call IUnknown::Release when finished using this IDirect3D9 interface results in a memory leak.


IDirect3DDevice9::GetDisplayMode Method

Retrieves the display mode's spatial resolution, color resolution, and refresh frequency.

Syntax

HRESULT GetDisplayMode(

    UINT iSwapChain,
    D3DDISPLAYMODE *pMode
);

Parameters

iSwapChain
[in] An unsigned integer specifying the swap chain.
pMode
[out] Pointer to a D3DDISPLAYMODE structure containing data about the display mode of the adapter. As opposed to the display mode of the device, which may not be active if the device does not own full-screen mode.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


IDirect3DDevice9::GetFrontBufferData Method

Generates a copy of the device's front buffer and places that copy in a system memory buffer provided by the application.

Syntax

HRESULT GetFrontBufferData(

    UINT iSwapChain,
    IDirect3DSurface9 *pDestSurface
);

Parameters

iSwapChain
[in] An unsigned integer specifying the swap chain.
pDestSurface
[in] Pointer to an IDirect3DSurface9 interface that will receive a copy of the contents of the front buffer. The data is returned in successive rows with no intervening space, starting from the vertically highest row on the device's output to the lowest.

For windowed mode, the size of the destination surface should be the size of the desktop. For full-screen mode, the size of the destination surface should be the screen size.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_DRIVERINTERNALERROR

Internal driver error. Applications should generally shut down when receiving this error. For more information, see Driver Internal Errors.

D3DERR_DEVICELOST | The device has been lost but cannot be reset at this time. Therefore, rendering is not possible.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The buffer pointed to by pDestSurface will be filled with a representation of the front buffer, converted to the standard 32 bits per pixel format D3DFMT_A8R8G8B8.

This method is the only way to capture an antialiased screen shot.

This function is very slow, by design, and should not be used in any performance-critical path.

For more information, see Lost Devices and Retrieved Data.


IDirect3DDevice9::GetFVF Method

Gets the fixed vertex function declaration.

Syntax

HRESULT GetFVF(

    DWORD *pFVF
);

Parameters

pFVF
[out] A DWORD pointer to the fixed function vertex type. For more information, see D3DFVF.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

See Also

IDirect3DDevice9::SetFVF


IDirect3DDevice9::GetGammaRamp Method

Retrieves the gamma correction ramp for the swap chain.

Syntax

void GetGammaRamp(

    UINT iSwapChain,
    D3DGAMMARAMP *pRamp
);

Parameters

iSwapChain
[in] An unsigned integer specifying the swap chain.
pRamp
[in, out] Pointer to an application-supplied D3DGAMMARAMP structure to fill with the gamma correction ramp.

Return Value

None.

See Also

IDirect3DSwapChain9, IDirect3DDevice9::SetGammaRamp


IDirect3DDevice9::GetIndices Method

Retrieves index data.

Syntax

HRESULT GetIndices(

    IDirect3DIndexBuffer9 **ppIndexData
);

Parameters

ppIndexData
[out] Address of a pointer to an IDirect3DIndexBuffer9 interface, representing the returned index data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Note Calling this method will increase the internal reference count on the IDirect3DIndexBuffer9 interface. Failure to call IUnknown::Release when finished using this IDirect3DIndexBuffer9 interface results in a memory leak.

See Also

IDirect3DDevice9::SetIndices


IDirect3DDevice9::GetLight Method

Retrieves a set of lighting properties that this device uses.

Syntax

HRESULT GetLight(

    DWORD Index,
    D3DLIGHT9 *pLight
);

Parameters

Index
[in] Zero-based index of the lighting property set to retrieve. This method will fail if a lighting property has not been set for this index by calling the IDirect3DDevice9::SetLight method.
pLight
[out] Pointer to a D3DLIGHT9 structure that is filled with the retrieved lighting-parameter set.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other values in D3DCREATE.

Retrieve all the properties for an existing light source by calling the IDirect3DDevice9::GetLight method for the device. When calling the IDirect3DDevice9::GetLight method, pass the zero-based index of the light source for which the properties will be retrieved as the first parameter, and supply the address of a D3DLIGHT9 structure as the second parameter. The device fills the D3DLIGHT9 structure to describe the lighting properties it uses for the light source at that index.

// Assume d3dDevice is a valid pointer to an IDirect3DDevice9 interface.
HRESULT hr;
D3DLIGHT9 light;

// Get the property information for the first light.
hr = pd3dDevice->GetLight(0, &light);
if (SUCCEEDED(hr))
    // Handle Success
else
    // Handle failure

If you supply an index outside the range of the light sources assigned in the device, the IDirect3DDevice9::GetLight method fails, returning D3DERR_INVALIDCALL.

When you assign a set of light properties for a light source in a scene, the light source can be activated by calling the IDirect3DDevice9::LightEnable method for the device. New light sources are disabled by default. The IDirect3DDevice9::LightEnable method accepts two parameters. Set the first parameter to the zero-based index of the light source to be affected by the method, and set the second parameter to TRUE to enable the light or FALSE to disable it. The following code example illustrates the use of this method by enabling the first light source in the device's list of light source properties.

// Assume d3dDevice is a valid pointer to an IDirect3DDevice9 interface.
HRESULT hr;

hr = pd3dDevice->LightEnable(0, TRUE);
if (SUCCEEDED(hr))
    // Handle Success
else
    // Handle failure

Check the MaxActiveLights member of the D3DCAPS9 structure when you retrieve device capabilities to determine the maximum number of active lights supported by that device.

If you enable or disable a light that has no properties that are set with IDirect3DDevice9::SetLight, the IDirect3DDevice9::LightEnable method creates a light source with the properties listed in following table and enables or disables it.

See Also

IDirect3DDevice9::SetLight, IDirect3DDevice9::GetLightEnable, IDirect3DDevice9::LightEnable


IDirect3DDevice9::GetLightEnable Method

Retrieves the activity status—enabled or disabled—for a set of lighting parameters within a device.

Syntax

HRESULT GetLightEnable(

    DWORD Index,
    BOOL *pEnable
);

Parameters

Index
[in] Zero-based index of the set of lighting parameters that are the target of this method.
pEnable
[out, retval] Pointer to a variable to fill with the status of the specified lighting parameters. After the call, a nonzero value at this address indicates that the specified lighting parameters are enabled; a value of 0 indicates that they are disabled.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other values in D3DCREATE.

See Also

IDirect3DDevice9::GetLight, IDirect3DDevice9::LightEnable, IDirect3DDevice9::SetLight


IDirect3DDevice9::GetMaterial Method

Retrieves the current material properties for the device.

Syntax

HRESULT GetMaterial(

    D3DMATERIAL9 *pMaterial
);

Parameters

pMaterial
[out] Pointer to a D3DMATERIAL9 structure to fill with the currently set material properties.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL if the pMaterial parameter is invalid.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other values in D3DCREATE.

See Also

IDirect3DDevice9::SetMaterial


IDirect3DDevice9::GetNPatchMode Method

Gets the N-patch mode segments.

Syntax

FLOAT GetNPatchMode(VOID);

Return Value

Specifies the number of subdivision segments. If the number of segments is less than 1.0, N-patches are disabled. The default value is 0.0.

See Also

IDirect3DDevice9::SetNPatchMode


IDirect3DDevice9::GetNumberOfSwapChains Method

Gets the number of implicit swap chains.

Syntax

UINT GetNumberOfSwapChains(VOID);

Return Value

Number of implicit swap chains. See Remarks.

Remarks

Implicit swap chains are created by the device during IDirect3D9::CreateDevice. This method returns the number of swap chains created by CreateDevice.

An application may create additional swap chains using IDirect3DDevice9::CreateAdditionalSwapChain.


IDirect3DDevice9::GetPaletteEntries Method

Retrieves palette entries.

Syntax

HRESULT GetPaletteEntries(

    UINT PaletteNumber,
    PALETTEENTRY *pEntries
);

Parameters

PaletteNumber
[in] An ordinal value identifying the particular palette to retrieve.
pEntries
[in, out] Pointer to a PALETTEENTRY structure, representing the returned palette entries.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For more information about PALETTEENTRY, see the Microsoft Platform Software Development Kit (SDK).

Note As of Microsoft DirectX 9.0, the peFlags member of the PALETTEENTRY structure does not work the way it is documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

See Also

IDirect3DDevice9::GetCurrentTexturePalette, IDirect3DDevice9::SetCurrentTexturePalette, IDirect3DDevice9::SetPaletteEntries, Texture Palettes


IDirect3DDevice9::GetPixelShader Method

Retrieves the currently set pixel shader.

Syntax

HRESULT GetPixelShader(

    IDirect3DPixelShader9** ppShader
);

Parameters

ppShader
[out, retval] Pointer to a pixel shader interface.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method will not work on a device that is created using D3DCREATE_PUREDEVICE.

See Also

IDirect3DDevice9::SetPixelShader


IDirect3DDevice9::GetPixelShaderConstantB Method

Gets a Boolean shader constant.

Syntax

HRESULT GetPixelShaderConstantB(

    UINT StartRegister,
    BOOL *pConstantData,
    UINT BoolCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in, out] Pointer to an array of constants.
BoolCount
[in] Number of Boolean values in the array of constants.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

See Also

IDirect3DDevice9::SetPixelShaderConstantB


IDirect3DDevice9::GetPixelShaderConstantF Method

Gets a floating-point shader constant.

Syntax

HRESULT GetPixelShaderConstantF(

    UINT StartRegister,
    float *pConstantData,
    UINT Vector4fCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in, out] Pointer to an array of constants.
Vector4fCount
[in] Number of four float vectors in the array of constants.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

See Also

IDirect3DDevice9::SetPixelShaderConstantF


IDirect3DDevice9::GetPixelShaderConstantI Method

Gets an integer shader constant.

Syntax

HRESULT GetPixelShaderConstantI(

    UINT StartRegister,
    int *pConstantData,
    UINT Vector4iCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in, out] Pointer to an array of constants.
Vector4iCount
[in] Number of four integer vectors in the array of constants.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

See Also

IDirect3DDevice9::SetPixelShaderConstantI


IDirect3DDevice9::GetRasterStatus Method

Returns information describing the raster of the monitor on which the swap chain is presented.

Syntax

HRESULT GetRasterStatus(

    UINT iSwapChain,
    D3DRASTER_STATUS *pRasterStatus
);

Parameters

iSwapChain
[in] An unsigned integer specifying the swap chain.
pRasterStatus
[out] Pointer to a D3DRASTER_STATUS structure filled with information about the position or other status of the raster on the monitor driven by this adapter.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if pRasterStatus is invalid or if the device does not support reading the current scan line. To determine if the device supports reading the scan line, check for the D3DCAPS_READ_SCANLINE flag in the Caps member of D3DCAPS9.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other values in D3DCREATE."

See Also

D3DRASTER_STATUS


IDirect3DDevice9::GetRenderState Method

Retrieves a render-state value for a device.

Syntax

HRESULT GetRenderState(

    D3DRENDERSTATETYPE State,
    DWORD *pValue
);

Parameters

State
[in] Device state variable that is being queried. This parameter can be any member of the D3DRENDERSTATETYPE enumerated type.
pValue
[out, retval] Pointer to a variable that receives the value of the queried render state variable when the method returns.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL if one of the arguments is invalid.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other values in D3DCREATE."

See Also

IDirect3DDevice9::SetRenderState


IDirect3DDevice9::GetRenderTarget Method

Retrieves a render-target surface.

Syntax

HRESULT GetRenderTarget(

    DWORD RenderTargetIndex,
    IDirect3DSurface9 **ppRenderTarget
);

Parameters

RenderTargetIndex
[in] Index of the render target. See Remarks.
ppRenderTarget
[out] Address of a pointer to an IDirect3DSurface9 interface, representing the returned render-target surface for this device.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL if one of the arguments is invalid, or D3DERR_NOTFOUND if there's no render target available for the given index.

Remarks

Typically, methods that return state will not work on a device that is created using D3DCREATE_PUREDEVICE. This method however, will work even on a pure device because it returns an interface.

The device can now support multiple render targets. The number of render targets supported by a device is contained in the NumSimultaneousRTs member of D3DCAPS9. See Multiple Render Targets.

Calling this method will increase the internal reference count on the IDirect3DSurface9 interface. Failure to call IUnknown::Release when finished using the IDirect3DSurface9 interface results in a memory leak.

See Also

IDirect3DDevice9::SetRenderTarget


IDirect3DDevice9::GetRenderTargetData Method

Copies the render-target data from device memory to system memory.

Syntax

HRESULT GetRenderTargetData(

    IDirect3DSurface9* pRenderTarget,
    IDirect3DSurface9* pDestSurface
);

Parameters

pRenderTarget
[in] Pointer to an IDirect3DSurface9 object, representing a render target.
pDestSurface
[in] Pointer to an IDirect3DSurface9 object, representing a destination surface.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_DRIVERINTERNALERROR

Internal driver error. Applications should generally shut down when receiving this error. For more information, see Driver Internal Errors.

D3DERR_DEVICELOST | The device has been lost but cannot be reset at this time. Therefore, rendering is not possible.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The destination surface must be either an off-screen plain surface or a level of a texture (mipmap or cube texture) created with D3DPOOL_SYSTEMMEM.

The source surface must be a regular render target or a level of a render-target texture (mipmap or cube texture) created with POOL_DEFAULT.

This method will fail if:

  • The render target is multisampled.
  • The source render target is a different size than the destination surface.
  • The source render target and destination surface formats do not match.


IDirect3DDevice9::GetSamplerState Method

Gets the sampler state value.

Syntax

HRESULT GetSamplerState(

    DWORD Sampler,
    D3DSAMPLERSTATETYPE Type,
    DWORD* pValue
);

Parameters

Sampler
[in] The sampler stage index.
Type
[in] This parameter can be any member of the D3DSAMPLERSTATETYPE enumerated type.
pValue
[out] State value to get. The meaning of this value is determined by the Type parameter.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other values in D3DCREATE."

See Also

IDirect3DDevice9::SetSamplerState


IDirect3DDevice9::GetScissorRect Method

Gets the scissor rectangle.

Syntax

HRESULT GetScissorRect(

    RECT *pRect
);

Parameters

pRect
[out] Returns a pointer to a RECT World Wide Web link structure that defines the rendering area within the render target if scissor test is enabled.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be the following:

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The scissor rectangle is used as a rectangular clipping region.

See Rectangles for further information on the use of rectangles in Microsoft DirectX.


IDirect3DDevice9::GetSoftwareVertexProcessing Method

Gets the vertex processing (hardware or software) mode.

Syntax

BOOL GetSoftwareVertexProcessing(VOID);

Return Value

Returns TRUE if software vertex processing is set. Otherwise, it returns FALSE.

Remarks

An application can create a mixed-mode device to use both the software vertex processing and the hardware vertex processing. To switch between the two vertex processing modes in Microsoft DirectX 8.x, use IDirect3DDevice9::SetRenderState with the render state D3DRS_SOFTWAREVERTEXPROCESSING and the appropriate BOOL argument. The drawback of the render state approach was the difficulty in defining the semantics for state blocks. Applications and the runtime had to do extra work and be careful while recording and playing back state blocks.

In DirectX 9.0, use IDirect3DDevice9::SetSoftwareVertexProcessing instead. This new application programming interface (API) is not recorded by StateBlocks.


IDirect3DDevice9::GetStreamSource Method

Retrieves a vertex buffer bound to the specified data stream.

Syntax

HRESULT GetStreamSource(

    UINT StreamNumber,
    IDirect3DVertexBuffer9 **ppStreamData,
    UINT *pOffsetInBytes,
    UINT *pStride
);

Parameters

StreamNumber
[in] Specifies the data stream, in the range from 0 to the maximum number of streams minus one.
ppStreamData
[in, out] Address of a pointer to an IDirect3DVertexBuffer9 interface, representing the returned vertex buffer bound to the specified data stream.
pOffsetInBytes
[out] Pointer containing the offset from the beginning of the stream to the beginning of the vertex data. The offset is measured in bytes. See Remarks.
pStride
[out] Pointer to a returned stride of the component, in bytes. See Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A stream is defined as a uniform array of component data, where each component consists of one or more elements representing a single entity such as position, normal, color, and so on.

When a flexible vertex format (FVF) vertex shader is used, the stride of the vertex stream must match the vertex size, computed from the FVF. When a declaration is used, the stride should be greater than or equal to the stream size computed from the declaration.

Note Calling this method will increase the internal reference count on the IDirect3DVertexBuffer9 interface. Failure to call IUnknown::Release when finished using this IDirect3DVertexBuffer9 interface results in a memory leak.

See Also

IDirect3DDevice9::SetStreamSource


IDirect3DDevice9::GetStreamSourceFreq Method

Gets the stream source frequency divider value.

Syntax

HRESULT GetStreamSourceFreq(

    UINT StreamNumber,
    UINT* pDivider
);

Parameters

StreamNumber
[in] Stream source number.
pDivider
[out] Returns the frequency divider value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Vertex shaders can now be invoked more than once per vertex. See Drawing Non-Indexed Geometry.

See Also

IDirect3DDevice9::SetStreamSourceFreq


IDirect3DDevice9::GetSwapChain Method

Gets a pointer to a swap chain.

Syntax

HRESULT GetSwapChain(

    UINT iSwapChain,
    IDirect3DSwapChain9 **ppSwapChain
);

Parameters

iSwapChain
[in] The swap chain ordinal value. For more information, see NumberOfAdaptersInGroup in D3DCAPS9.
ppSwapChain
[in] Pointer to an IDirect3DSwapChain9 interface that will receive a copy of swap chain.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


IDirect3DDevice9::GetTexture Method

Retrieves a texture assigned to a stage for a device.

Syntax

HRESULT GetTexture(

    DWORD Stage,
    IDirect3DBaseTexture9 **ppTexture
);

Parameters

Stage
[in] Stage identifier of the texture to retrieve. Stage identifiers are zero-based.
ppTexture
[out, retval] Address of a pointer to an IDirect3DBaseTexture9 interface, representing the returned texture.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Typically, methods that return state will not work on a device that is created using D3DCREATE_PUREDEVICE. This method however, will work even on a pure device because it returns an interface.

Calling this method will increase the internal reference count on the IDirect3DTexture9 interface. Failure to call IUnknown::Release when finished using this IDirect3DTexture9 interface results in a memory leak.

See Also

IDirect3DDevice9::SetTexture, IDirect3DDevice9::GetTextureStageState, IDirect3DDevice9::SetTextureStageState


IDirect3DDevice9::GetTextureStageState Method

Retrieves a state value for an assigned texture.

Syntax

HRESULT GetTextureStageState(

    DWORD Stage,
    D3DTEXTURESTAGESTATETYPE Type,
    DWORD *pValue
);

Parameters

Stage
[in] Stage identifier of the texture for which the state is retrieved. Stage identifiers are zero-based. Devices can have up to eight set textures, so the maximum value allowed for Stage is 7.
Type
[in] Texture state to retrieve. This parameter can be any member of the D3DTEXTURESTAGESTATETYPE enumerated type.
pValue
[out, retval] Pointer a variable to fill with the retrieved state value. The meaning of the retrieved value is determined by the Type parameter.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other flag values in D3DCREATE."

See Also

IDirect3DDevice9::SetTextureStageState, IDirect3DDevice9::GetTexture, IDirect3DDevice9::SetTexture


IDirect3DDevice9::GetTransform Method

Retrieves a matrix describing a transformation state.

Syntax

HRESULT GetTransform(

    D3DTRANSFORMSTATETYPE State,
    D3DMATRIX *pMatrix
);

Parameters

State
[in] Device state variable that is being modified. This parameter can be any member of the D3DTRANSFORMSTATETYPE enumerated type, or the D3DTS_WORLDMATRIX macro.
pMatrix
[out] Pointer to a D3DMATRIX structure, describing the returned transformation state.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL if one of the arguments is invalid.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other flag values in D3DCREATE.

See Also

IDirect3DDevice9::SetTransform


IDirect3DDevice9::GetVertexDeclaration Method

Gets a vertex shader declaration.

Syntax

HRESULT GetVertexDeclaration(

    IDirect3DVertexDeclaration9** ppDecl
);

Parameters

ppDecl
[out] Pointer to an IDirect3DVertexDeclaration9 object that is returned.

Return Value

If the method succeeds, the return value is D3D_OK.

The return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DDevice9::SetVertexDeclaration


IDirect3DDevice9::GetVertexShader Method

Retrieves the currently set vertex shader.

Syntax

HRESULT GetVertexShader(

    IDirect3DVertexShader9** ppShader
);

Parameters

ppShader
[out, retval] Pointer to a vertex shader interface.

Return Value

If the method succeeds, the return value is D3D_OK.

If ppShader is invalid, D3DERR_INVALIDCALL is returned.

Remarks

Typically, methods that return state will not work on a device that is created using D3DCREATE_PUREDEVICE. This method however, will work even on a pure device because it returns an interface.

See Also

IDirect3DDevice9::SetVertexShader


IDirect3DDevice9::GetVertexShaderConstantB Method

Gets a Boolean vertex shader constant.

Syntax

HRESULT GetVertexShaderConstantB(

    UINT StartRegister,
    BOOL *pConstantData,
    UINT BoolCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in, out] Pointer to an array of constants.
BoolCount
[in] Number of Boolean values in the array of constants.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


IDirect3DDevice9::GetVertexShaderConstantF Method

Gets a floating-point vertex shader constant.

Syntax

HRESULT GetVertexShaderConstantF(

    UINT StartRegister,
    float *pConstantData,
    UINT Vector4fCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in, out] Pointer to an array of constants.
Vector4fCount
[in] Number of four float vectors in the array of constants.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


IDirect3DDevice9::GetVertexShaderConstantI Method

Gets an integer vertex shader constant.

Syntax

HRESULT GetVertexShaderConstantI(

    UINT StartRegister,
    int *pConstantData,
    UINT Vector4iCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in, out] Pointer to an array of constants.
Vector4iCount
[in] Number of four integer vectors in the array of constants.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


IDirect3DDevice9::GetViewport Method

Retrieves the viewport parameters currently set for the device.

Syntax

HRESULT GetViewport(

    D3DVIEWPORT9 *pViewport
);

Parameters

pViewport
[out] Pointer to a D3DVIEWPORT9 structure, representing the returned viewport parameters.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the pViewport parameter is invalid.

Remarks

Typically, methods that return state will not work on a device that is created using D3DCREATE_PUREDEVICE. This method however, will work even on a pure device.

See Also

IDirect3DDevice9::SetViewport


IDirect3DDevice9::LightEnable Method

Enables or disables a set of lighting parameters within a device.

Syntax

HRESULT LightEnable(

    DWORD LightIndex,
    BOOL bEnable
);

Parameters

LightIndex
[in] Zero-based index of the set of lighting parameters that are the target of this method.
bEnable
[in] Value that indicates if the set of lighting parameters are being enabled or disabled. Set this parameter to TRUE to enable lighting with the parameters at the specified index, or FALSE to disable it.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If a value for LightIndex is outside the range of the light property sets assigned within the device, the IDirect3DDevice9::LightEnable method creates a light source represented by a D3DLIGHT9 structure with the following properties and sets its enabled state to the value specified in bEnable.

Member | Default
Type | D3DLIGHT_DIRECTIONAL
Diffuse | (R:1, G:1, B:1, A:0)
Specular | (R:0, G:0, B:0, A:0)
Ambient | (R:0, G:0, B:0, A:0)
Position | (0, 0, 0)
Direction | (0, 0, 1)
Range | 0
Falloff | 0
Attenuation0 | 0
Attenuation1 | 0
Attenuation2 | 0
Theta | 0
Phi | 0

See Also

IDirect3DDevice9::GetLight, IDirect3DDevice9::GetLightEnable, IDirect3DDevice9::SetLight


IDirect3DDevice9::MultiplyTransform Method

Multiplies a device's world, view, or projection matrices by a specified matrix.

Syntax

HRESULT MultiplyTransform(

    D3DTRANSFORMSTATETYPE State,
    CONST D3DMATRIX *pMatrix
);

Parameters

State
[in] Member of the D3DTRANSFORMSTATETYPE enumerated type, or the D3DTS_WORLDMATRIX macro that identifies which device matrix is to be modified. The most common setting, D3DTS_WORLDMATRIX(0), modifies the world matrix, but you can specify that the method modify the view or projection matrices, if needed.
pMatrix
[in] Pointer to a D3DMATRIX structure that modifies the current transformation.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL if one of the arguments is invalid.

Remarks

The multiplication order is pMatrix times State.

An application might use the IDirect3DDevice9::MultiplyTransform method to work with hierarchies of transformations. For example, the geometry and transformations describing an arm might be arranged in the following hierarchy.

shoulder_transformation
    upper_arm geometry
    elbow transformation
        lower_arm geometry
        wrist transformation
            hand geometry

An application might use the following series of calls to render this hierarchy. Not all the parameters are shown in this pseudocode.

IDirect3DDevice9::SetTransform(D3DTS_WORLDMATRIX(0),
    shoulder_transform)
IDirect3DDevice9::DrawPrimitive(upper_arm)
IDirect3DDevice9::MultiplyTransform(D3DTS_WORLDMATRIX(0),
    elbow_transform)
IDirect3DDevice9::DrawPrimitive(lower_arm)
IDirect3DDevice9::MultiplyTransform(D3DTS_WORLDMATRIX(0),
    wrist_transform)
IDirect3DDevice9::DrawPrimitive(hand)

See Also

IDirect3DDevice9::DrawPrimitive, IDirect3DDevice9::SetTransform, D3DTS_WORLD, D3DTS_WORLDn, D3DTS_WORLDMATRIX


IDirect3DDevice9::Present Method

Presents the contents of the next buffer in the sequence of back buffers owned by the device.

Syntax

HRESULT Present(

    CONST RECT *pSourceRect,
    CONST RECT *pDestRect,
    HWND hDestWindowOverride,
    CONST RGNDATA *pDirtyRegion
);

Parameters

pSourceRect
[in] Pointer to a value that must be NULL unless the swap chain was created with D3DSWAPEFFECT_COPY. pSourceRect is a pointer to a RECT World Wide Web link structure containing the source rectangle. If NULL, the entire source surface is presented. If the rectangle exceeds the source surface, the rectangle is clipped to the source surface.
pDestRect
[in] Pointer to a value that must be NULL unless the swap chain was created with D3DSWAPEFFECT_COPY. pDestRect is a pointer to a RECT structure containing the destination rectangle, in window client coordinates. If NULL, the entire client area is filled. If the rectangle exceeds the destination client area, the rectangle is clipped to the destination client area.
hDestWindowOverride
[in] Pointer to a destination window whose client area is taken as the target for this presentation. If this value is NULL, then the hWndDeviceWindow member of D3DPRESENT_PARAMETERS is taken.
pDirtyRegion
[in] Value must be NULL unless the swap chain was created with D3DSWAPEFFECT_COPY. For more information about swap chains, see Flipping Surfaces and D3DSWAPEFFECT.

If this value is non-NULL, the contained region is expressed in back buffer coordinates. The rectangles within the region are the minimal set of pixels that need to be updated. This method takes these rectangles into account when optimizing the presentation by copying only the pixels within the region, or some suitably expanded set of rectangles. This is an aid to optimization only, and the application should not rely on the region being copied exactly. The implementation can choose to copy the whole source rectangle.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_DEVICELOST | The device has been lost but cannot be reset at this time. Therefore, rendering is not possible.
D3DERR_DRIVERINTERNALERROR

Internal driver error. Applications should generally shut down when receiving this error. For more information, see Driver Internal Errors.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

If necessary, a stretch operation is applied to transfer the pixels within the source rectangle to the destination rectangle in the client area of the target window.

Present will fail, returning D3DERR_INVALIDCALL, if called between BeginScene and EndScene pairs unless the render target is not the current render target (such as the back buffer you get from creating an additional swap chain). This is a new behavior for Microsoft DirectX 9.0.

See Also

IDirect3DDevice9::Reset, Multihead


IDirect3DDevice9::ProcessVertices Method

Applies the vertex processing defined by the vertex shader to the set of input data streams, generating a single stream of interleaved vertex data to the destination vertex buffer.

Syntax

HRESULT ProcessVertices(

    UINT SrcStartIndex,
    UINT DestIndex,
    UINT VertexCount,
    IDirect3DVertexBuffer9 *pDestBuffer,
    IDirect3DVertexDeclaration9* pVertexDecl,
    DWORD Flags
);

Parameters

SrcStartIndex
[in] Index of first vertex to load.
DestIndex
[in] Index of first vertex in the destination vertex buffer into which the results are placed.
VertexCount
[in] Number of vertices to process.
pDestBuffer
[in] Pointer to an IDirect3DVertexBuffer9 interface, the destination vertex buffer representing the stream of interleaved vertex data.
pVertexDecl
[in] Pointer to an IDirect3DVertexDeclaration9 interface that represents the output vertex data declaration. When vertex shader 3.0 or above is set as the current vertex shader, the output vertex declaration must be present.
Flags
[in] Processing options. Set this parameter to 0 for default processing. Set to D3DPV_DONOTCOPYDATA to prevent the system from copying vertex data not affected by the vertex operation into the destination buffer. The D3DPV_DONOTCOPYDATA value may be combined with one or more D3DLOCK values appropriate for the destination buffer.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The order of operations for this method is as follows:

  • Transform vertices to projection space using the world + view + projection matrix.
  • Compute screen coordinates using viewport settings.
  • If clipping is enabled, compute clipping codes and store them in an internal buffer, associated with the destination vertex buffer. If a vertex is inside the viewing frustum, its screen coordinates are computed. If the vertex is outside the viewing frustum, the vertex is stored in the destination vertex buffer in projection space coordinates.
  • Other notes: The user does not have access to the internal clip code buffer. No clipping is done on triangles or any other primitives.

The destination vertex buffer, pDestBuffer, must be created with a nonzero FVF parameter in IDirect3DDevice9::CreateVertexBuffer. The flexible vertex format (FVF) code specified during the call to the IDirect3DDevice9::CreateVertexBuffer method specifies the vertex elements present in the destination vertex buffer.

When Microsoft Direct3D generates texture coordinates, or copies or transforms input texture coordinates, and the output texture coordinate format defines more texture coordinate components than Direct3D generates, Direct3D does not change these extra components.

See Also

Device Types and Vertex Processing Requirements, Fixed Function Vertex Processing


IDirect3DDevice9::Reset Method

Resets the type, size, and format of the swap chain.

Syntax

HRESULT Reset(

    D3DPRESENT_PARAMETERS* pPresentationParameters
);

Parameters

pPresentationParameters
[in, out] Pointer to a D3DPRESENT_PARAMETERS structure, describing the new presentation parameters. This value cannot be NULL.

When switching to full-screen mode, Microsoft Direct3D will try to find a desktop format that matches the back buffer format, so that back buffer and front buffer formats will be identical (to eliminate the need for color conversion).

When this method returns:

  • BackBufferCount, BackBufferWidth, and BackBufferHeight are set to zero.
  • BackBufferFormat is set to D3DFMT_UNKNOWN for windowed mode only; a full-screen mode must specify a format.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_DEVICELOST | The device has been lost but cannot be reset at this time. Therefore, rendering is not possible.
D3DERR_DRIVERINTERNALERROR

Internal driver error. Applications should generally shut down when receiving this error. For more information, see Driver Internal Errors.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Direct3D does not have enough display memory to perform the operation.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

If a call to IDirect3DDevice9::Reset fails, the device will be placed in the "lost" state (as indicated by a return value of D3DERR_DEVICELOST from a call to IDirect3DDevice9::TestCooperativeLevel) unless it is already in the "not reset" state (as indicated by a return value of D3DERR_DEVICENOTRESET from a call to IDirect3DDevice9::TestCooperativeLevel). Refer to IDirect3DDevice9::TestCooperativeLevel and Lost Devices for further information concerning the use of IDirect3DDevice9::Reset in the context of lost devices.

Calling IDirect3DDevice9::Reset causes all texture memory surfaces to be lost, managed textures to be flushed from video memory, and all state information to be lost. Before calling the IDirect3DDevice9::Reset method for a device, an application should release any explicit render targets, depth stencil surfaces, additional swap chains, state blocks, and D3DPOOL_DEFAULT resources associated with the device.

There are two different types of swap chains: full-screen or windowed. If the new swap chain is full-screen, the adapter will be placed in the display mode that matches the new size.

Microsoft DirectX 9.0 applications can expect messages to be sent to them during this call (for example, before this call is returned); applications should take precautions not to call into Direct3D at this time. In addition, when IDirect3DDevice9::Reset fails, the only valid methods that can be called are IDirect3DDevice9::Reset, IDirect3DDevice9::TestCooperativeLevel, and the various Release member functions. Calling any other method can result in an exception.

A call to IDirect3DDevice9::Reset will fail if called on a different thread than that used to create the device being reset.

Pixel shaders and vertex shaders survive IDirect3DDevice9::Reset calls for DirectX 9.0. They do not need to be re-created explicitly by the application.

D3DFMT_UNKNOWN can be specified for the windowed mode back buffer format when calling IDirect3D9::CreateDevice, IDirect3DDevice9::Reset, and IDirect3DDevice9::CreateAdditionalSwapChain. This means the application does not have to query the current desktop format before calling IDirect3D9::CreateDevice for windowed mode. For full-screen mode, the back buffer format must be specified. Setting BackBufferCount equal to zero (BackBufferCount = 0) results in one back buffer.

When trying to reset more than one display adapter in a group, set pPresentationParameters to point to an array of D3DPRESENT_PARAMETERS structures, one for each display in the adapter group.

If a multihead device was created with D3DCREATE_ADAPTERGROUP_DEVICE, IDirect3DDevice9::Reset requires an array of D3DPRESENT_PARAMETERS structures wherein each structure must specify a full-screen display. To switch back to windowed mode, the application must destroy the device and re-create a non-multihead device in windowed mode.

See Also

D3DSWAPEFFECT, D3DPRESENT_PARAMETERS, IDirect3DDevice9::Present, Multihead


IDirect3DDevice9::SetClipPlane Method

Sets the coefficients of a user-defined clipping plane for the device.

Syntax

HRESULT SetClipPlane(

    DWORD Index,
    const float *pPlane
);

Parameters

Index
[in] Index of the clipping plane for which the plane equation coefficients are to be set.
pPlane
[in] Pointer to an address of a four-element array of values that represent the clipping plane coefficients to be set, in the form of the general plane equation. See Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is D3DERR_INVALIDCALL. This error indicates that the value in Index exceeds the maximum clipping plane index supported by the device or that the array at pPlane is not large enough to contain four floating-point values.

Remarks

The coefficients that this method sets take the form of the general plane equation. If the values in the array at pPlane were labeled A, B, C, and D in the order that they appear in the array, they would fit into the general plane equation so that Ax + By + Cz + Dw = 0. A point with homogeneous coordinates (x, y, z, w) is visible in the half space of the plane if Ax + By + Cz + Dw >= 0. Points that exist behind the clipping plane are clipped from the scene.

When the fixed function pipeline is used the plane equations are assumed to be in world space. When the programmable pipeline is used the plane equations are assumed to be in the clipping space (the same space as output vertices).

This method does not enable the clipping plane equation being set. To enable a clipping plane, set the corresponding bit in the DWORD value applied to the D3DRS_CLIPPLANEENABLE render state.

See Also

IDirect3DDevice9::GetClipPlane


IDirect3DDevice9::SetClipStatus Method

Sets the clip status.

Syntax

HRESULT SetClipStatus(

    const D3DCLIPSTATUS9 *pClipStatus
);

Parameters

pClipStatus
[in] Pointer to a D3DCLIPSTATUS9 structure, describing the clip status settings to be set.

Return Value

If the method succeeds, the return value is D3D_OK.

If one of the arguments is invalid, the return value is D3DERR_INVALIDCALL.

Remarks

Clip status is used during software vertex processing. Therefore, this method is not supported on pure or nonpure hardware processing devices. For more information about pure devices, see D3DCREATE.

When clipping is enabled during vertex processing (by IDirect3DDevice9::ProcessVertices, IDirect3DDevice9::DrawPrimitive, or other drawing functions), Microsoft Direct3D computes a clip code for every vertex. The clip code is a combination of D3DCS_* bits. When a vertex is outside a particular clipping plane, the corresponding bit is set in the clipping code. Direct3D maintains the clip status using D3DCLIPSTATUS9, which has ClipUnion and ClipIntersection members. ClipUnion is a bitwise "OR" of all vertex clip codes and ClipIntersection is a bitwise "AND" of all vertex clip codes. Initial values are zero for ClipUnion and 0xFFFFFFFF for ClipIntersection. When D3DRS_CLIPPING is set to FALSE, ClipUnion and ClipIntersection are set to zero. Direct3D updates the clip status during drawing calls. To compute clip status for a particular object, set ClipUnion and ClipIntersection to their initial value and continue drawing.

Clip status is not updated by IDirect3DDevice9::DrawRectPatch and IDirect3DDevice9::DrawTriPatch because there is no software emulation for them.

See Also

IDirect3DDevice9::GetClipStatus


IDirect3DDevice9::SetCurrentTexturePalette Method

Sets the current texture palette.

Syntax

HRESULT SetCurrentTexturePalette(

    UINT PaletteNumber
);

Parameters

PaletteNumber
[in] Value that specifies the texture palette to set as the current texture palette.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A single logical palette is associated with the device, and is shared by all texture stages.

See Also

IDirect3DDevice9::GetCurrentTexturePalette, Texture Palettes


IDirect3DDevice9::SetCursorPosition Method

Sets the cursor position and update options.

Syntax

void SetCursorPosition(

    INT X,
    INT Y,
    DWORD Flags
);

Parameters

X
[in] The new X-position of the cursor in virtual desktop coordinates. See Remarks.
Y
[in] The new Y-position of the cursor in virtual desktop coordinates. See Remarks.
Flags
[in] Specifies the update options for the cursor. Currently, only one flag is defined.
D3DCURSOR_IMMEDIATE_UPDATE
Update cursor at the refresh rate.

If this flag is specified, the system guarantees that the cursor will be updated at a minimum of half the display refresh rate, but never more frequently than the display refresh rate. Otherwise, the method delays cursor updates until the next IDirect3DDevice9::Present call. Not setting this flag usually results in better performance than if the flag is set. However, applications should set this flag if the rate of calls to Present is low enough that users would notice a significant delay in cursor motion. This flag has no effect in a windowed-mode application. Some video cards implement hardware color cursors. This flag does not have an effect on these cards.

Return Value

None.

Remarks

When running in full-screen mode, screen space coordinates are the back buffer coordinates appropriately scaled to the current display mode. When running in windowed mode, screen space coordinates are the desktop coordinates. The cursor image is drawn at the specified position minus the hotspot-offset specified by the IDirect3DDevice9::SetCursorProperties method.

If the cursor has been hidden by IDirect3DDevice9::ShowCursor, the cursor is not drawn.

See Also

IDirect3DDevice9::SetCursorProperties, IDirect3DDevice9::ShowCursor


IDirect3DDevice9::SetCursorProperties Method

Sets properties for the cursor.

Syntax

HRESULT SetCursorProperties(

    UINT XHotSpot,
    UINT YHotSpot,
    IDirect3DSurface9 *pCursorBitmap
);

Parameters

XHotSpot
[in] X-coordinate offset (in pixels) that marks the center of the cursor. The offset is relative to the upper-left corner of the cursor. When the cursor is given a new position, the image is drawn at an offset from this new position determined by subtracting the hot spot coordinates from the position.
YHotSpot
[in] Y-coordinate offset (in pixels) that marks the center of the cursor. The offset is relative to the upper-left corner of the cursor. When the cursor is given a new position, the image is drawn at an offset from this new position determined by subtracting the hot spot coordinates from the position.
pCursorBitmap
[in] Pointer to an IDirect3DSurface9 interface. This parameter must point to an 8888 ARGB surface (format D3DFMT_A8R8G8B8). The contents of this surface will be copied and potentially format-converted into an internal buffer from which the cursor is displayed. The dimensions of this surface must be less than the dimensions of the display mode, and must be a power of two in each direction, although not necessarily the same power of two. The alpha channel must be either 0.0 or 1.0.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

An operating system cursor is created and used under either of these conditions:

  • The hardware has set D3DCURSORCAPS_COLOR (see D3DCURSORCAPS), and the cursor size is 32x32 (which is the cursor size in the operating system).
  • The application is running in windowed mode.

Otherwise, Microsoft DirectX uses an emulated cursor. An application uses IDirect3DDevice9::SetCursorPosition to move an emulated cursor to follow mouse movement.

It is recommended for applications to always trap WM_MOUSEMOVE events and call DXSetCursorPosition.

Microsoft Direct3D cursor functions use either Microsoft Windows Graphics Device Interface (GDI) cursor or software emulation, depending on the hardware. Users typically want to respond to a WM_SETCURSOR message. For example, they might want to write the message handler as follows:

case WM_SETCURSOR:
// Turn off window cursor.
SetCursor( NULL );
m_pd3dDevice->ShowCursor( TRUE );
return TRUE; // Prevent Windows from setting cursor to window class cursor.
break;

Or, users might want to call the IDirect3DDevice9::SetCursorProperties method if they want to change the cursor.

The application can determine what hardware support is available for cursors by examining appropriate members of the D3DCAPS9 structure. Typically, hardware supports only 32x32 cursors and, when windowed, the system might support only 32x32 cursors. In this case, IDirect3DDevice9::SetCursorProperties still succeeds but the cursor might be reduced to that size. The hot spot is scaled appropriately.

The cursor does not survive when the device is lost. This method must be called after the device is reset.

See Also

IDirect3DDevice9::ShowCursor, D3DCAPS9


IDirect3DDevice9::SetDepthStencilSurface Method

Sets the depth stencil surface.

Syntax

HRESULT SetDepthStencilSurface(

    IDirect3DSurface9 *pNewZStencil
);

Parameters

pNewZStencil
[in] Address of a pointer to an IDirect3DSurface9 interface representing the depth stencil surface. Setting this to NULL disables the depth stencil operation.

Return Value

If the method succeeds, the return value is D3D_OK.

If pZStencilSurface is other than NULL, the return value is D3DERR_INVALIDCALL when the stencil surface is invalid.

Remarks

Restrictions for using this method include the following:

  • The multisample type must be the same for the render target and the depth stencil surface.
  • The formats must be compatible for the render target and the depth stencil surface. See IDirect3D9::CheckDepthStencilMatch.
  • The size of the depth stencil surface must be greater than or equal to the size of the render target.

These restrictions are validated only when using the debug runtime when any of the IDirect3DDevice9 Draw methods are called.

Cube textures differ from other surfaces in that they are collections of surfaces. To call IDirect3DDevice9::SetDepthStencilSurface with a cube texture, you must select an individual face using IDirect3DCubeTexture9::GetCubeMapSurface and pass the resulting surface to IDirect3DDevice9::SetDepthStencilSurface.

See Also

IDirect3DDevice9::GetDepthStencilSurface


IDirect3DDevice9::SetDialogBoxMode Method

This method allows the use of Microsoft Windows Graphics Device Interface (GDI) dialog boxes in full-screen mode applications.

Syntax

HRESULT SetDialogBoxMode(

    BOOL bEnableDialogs
);

Parameters

bEnableDialogs
[in] TRUE to enable GDI dialog boxes, and FALSE to disable them.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL unless all of the following are true.
  • The application specified a back buffer format compatible with GDI, in other words, one of D3DFMT_X1R5G5B5, D3DFMT_R5G6B5, or D3DFMT_X8R8G8B8.
  • The application specified no multisampling.
  • The application specified D3DSWAPEFFECT_DISCARD.
  • The application specified D3DPRESENTFLAG_LOCKABLE_BACKBUFFER.
  • The application did not specify D3DCREATE_ADAPTERGROUP_DEVICE.
  • The application is not between BeginScene and EndScene.

Remarks

The GDI dialog boxes must be created as child to the device window. They should also be created within the same thread that created the device because this enables the parent window to manage redrawing the child window.

The method has no effect for windowed mode applications, but this setting will be respected if the application resets the device into full-screen mode. If SetDialogBoxMode succeeds in a windowed mode application, any subsequent reset to full-screen mode will be checked against the restrictions listed above. Also, SetDialogBoxMode causes all back buffers on the swap chain to be discarded, so an application is expected to refresh its content for all back buffers after this call.


IDirect3DDevice9::SetFVF Method

Sets the current vertex stream declaration.

Syntax

HRESULT SetFVF(

    DWORD FVF
);

Parameters

FVF
[in] DWORD containing the fixed function vertex type. For more information, see D3DFVF.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be:

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

Here are the steps necessary to initialize and use vertices that have a position, diffuse and specular color, and texture coordinates:

  1. Define the custom vertex type and flexible vertex format (FVF) code.
    struct LVertex
{
    FLOAT    x, y, z;
    D3DCOLOR specular, diffuse;
    FLOAT    tu, tv;
};

const DWORD VertexFVF = (D3DFVF_XYZ | D3DFVF_DIFFUSE |
                         D3DFVF_SPECULAR | D3DFVF_TEX1 );
  2. Create a vertex buffer with enough room for four vertices using IDirect3DDevice9::CreateVertexBuffer.
    g_d3dDevice->CreateVertexBuffer( 4*sizeof(LVertex), VertexFVF,
  D3DUSAGE_WRITEONLY, D3DPOOL_DEFAULT, &pBigSquareVB, NULL );
  3. Set the values for each vertex.
    LVertex * v;
pBigSquareVB->Lock( 0, 0, (BYTE**)&v, 0 );

v[0].x  = 0.0f;  v[0].y  = 10.0;  v[0].z  = 10.0f;
v[0].diffuse  = 0xffff0000;
v[0].specular = 0xff00ff00;
v[0].tu = 0.0f;  v[0].tv = 0.0f;

v[1].x  = 0.0f;  v[1].y  = 0.0f;  v[1].z  = 10.0f;
v[1].diffuse  = 0xff00ff00;
v[1].specular = 0xff00ffff;
v[1].tu = 0.0f;  v[1].tv = 0.0f;

v[2].x  = 10.0f; v[2].y  = 10.0f; v[2].z  = 10.0f;
v[2].diffuse  = 0xffff00ff;
v[2].specular = 0xff000000;
v[2].tu = 0.0f;  v[2].tv = 0.0f;

v[3].x  = 0.0f; v[3].y  = 10.0f;  v[3].z = 10.0f;
v[3].diffuse  = 0xffffff00;
v[3].specular = 0xffff0000;
v[3].tu = 0.0f; v[3].tv = 0.0f;

pBigSquareVB->Unlock();
  4. The vertex buffer has been initialized and is ready to render. The following code example shows how to use the legacy FVF to draw a square.
    g_d3dDevice->SetFVF(VertexFVF);
g_d3dDevice->SetStreamSource(0, pBigSquareVB, 0, sizeof(LVertex));
g_d3dDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0 ,2);

Here are the steps necessary to initialize and use vertices that have a position, a normal, and texture coordinates:

  1. Define the custom vertex type and FVF code.
    struct Vertex
{
    FLOAT x, y, z;
    FLOAT nx, ny, nz;
    FLOAT tu, tv;
};

const DWORD VertexFVF = ( D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1 );
  2. Create a vertex buffer with enough room for four vertices using IDirect3DDevice9::CreateVertexBuffer (similar to the example above).
  3. Set the values for each vertex.
    Vertex * v;
pBigSquareVB->Lock(0, 0, (BYTE**)&v, 0);

v[0].x  = 0.0f;  v[0].y  = 10.0;  v[0].z  = 10.0f;
v[0].nx = 0.0f;  v[0].ny = 1.0f;  v[0].nz = 0.0f;
v[0].tu = 0.0f;  v[0].tv = 0.0f;

v[1].x  = 0.0f;  v[1].y  = 0.0f;  v[1].z  = 10.0f;
v[1].nx = 0.0f;  v[1].ny = 1.0f;  v[1].nz = 0.0f;
v[1].tu = 0.0f;  v[1].tv = 0.0f;

v[2].x  = 10.0f; v[2].y  = 10.0f; v[2].z  = 10.0f;
v[2].nx = 0.0f;  v[2].ny = 1.0f;  v[2].nz = 0.0f;
v[2].tu = 0.0f;  v[2].tv = 0.0f;

v[3].x  = 0.0f; v[3].y  = 10.0f;  v[3].z = 10.0f;
v[3].nx = 0.0f; v[3].ny = 1.0f;   v[3].nz = 0.0f;
v[3].tu = 0.0f; v[3].tv = 0.0f;

pBigSquareVB->Unlock();
  4. Draw the object (similar to the example above).

See Also

IDirect3DDevice9::GetFVF


IDirect3DDevice9::SetGammaRamp Method

Sets the gamma correction ramp for the implicit swap chain. This method will affect the entire screen (not just the active window if you are running in windowed mode).

Syntax

void SetGammaRamp(

    UINT iSwapChain,
    DWORD Flags,
    CONST D3DGAMMARAMP *pRamp
);

Parameters

iSwapChain
[in] Unsigned integer specifying the swap chain.
Flags
[in] Indicates whether correction should be applied. Gamma correction results in a more consistent display, but can incur processing overhead and should not be used frequently. Short-duration effects, such as flashing the whole screen red, should not be calibrated, but long-duration gamma changes should be calibrated. One of the following values can be set:
D3DSGR_CALIBRATE
If a gamma calibrator is installed, the ramp will be modified before being sent to the device to account for the system and monitor response curves. If a calibrator is not installed, the ramp will be passed directly to the device.
D3DSGR_NO_CALIBRATION
No gamma correction is applied. The supplied gamma table is transferred directly to the device.
pRamp
[in] Pointer to a D3DGAMMARAMP structure, representing the gamma correction ramp to be set for the implicit swap chain.

Return Value

No return value.

Remarks

There is always at least one swap chain (the implicit swap chain) for each device, because Microsoft DirectX 9.0 has one swap chain as a property of the device. The gamma ramp takes effect immediately; there is no wait for a vertical sync.

If the device does not support gamma ramps in the swap chain's current presentation mode (full-screen or windowed), no error return is given. Applications can check the D3DCAPS2_FULLSCREENGAMMA and D3DCAPS2_CANCALIBRATEGAMMA capability bits in the Caps2 member of the D3DCAPS9 structure to determine the capabilities of the device and whether a calibrator is installed.

For windowed gamma correction presentation, use IDirect3DSwapChain9::Present if the hardware supports the feature. In DirectX 8.0, SetGammaRamp will set the gamma ramp only on a full-screen mode application. For more information about gamma correction, see Gamma.

See Also

IDirect3DSwapChain9, IDirect3DDevice9::GetGammaRamp


IDirect3DDevice9::SetIndices Method

Sets index data.

Syntax

HRESULT SetIndices(

    IDirect3DIndexBuffer9 *pIndexData
);

Parameters

pIndexData
[in] Pointer to an IDirect3DIndexBuffer9 interface, representing the index data to be set.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When an application no longer holds a references to this interface, the interface will automatically be freed.

The IDirect3DDevice9::SetIndices method sets the current index array to an index buffer. The single set of indices is used to index all streams.

See Also

IDirect3DDevice9::GetIndices


IDirect3DDevice9::SetLight Method

Assigns a set of lighting properties for this device.

Syntax

HRESULT SetLight(

    DWORD Index,
    CONST D3DLIGHT9 *pLight
);

Parameters

Index
[in] Zero-based index of the set of lighting properties to set. If a set of lighting properties exists at this index, it is overwritten by the new properties specified in pLight.
pLight
[in] Pointer to a D3DLIGHT9 structure, containing the lighting parameters to set.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Set light properties by preparing a D3DLIGHT9 structure and then calling the IDirect3DDevice9::SetLight method. The IDirect3DDevice9::SetLight method accepts the index at which the device should place the set of light properties to its internal list of light properties, and the address of a prepared D3DLIGHT9 structure that defines those properties. You can call IDirect3DDevice9::SetLight with new information as needed to update the light's illumination properties.

The system allocates memory to accommodate a set of lighting properties each time you call the IDirect3DDevice9::SetLight method with an index that has never been assigned properties. Applications can set a number of lights, with only a subset of the assigned lights enabled at a time. Check the MaxActiveLights member of the D3DCAPS9 structure when you retrieve device capabilities to determine the maximum number of active lights supported by that device. If you no longer need a light, you can disable it or overwrite it with a new set of light properties.

The following example prepares and sets properties for a white point-light whose emitted light will not attenuate over distance.

// Assume d3dDevice is a valid pointer to an IDirect3DDevice9 interface.
D3DLIGHT9 d3dLight;
HRESULT   hr;

// Initialize the structure.
ZeroMemory(&d3dLight, sizeof(d3dLight));

// Set up a white point light.
d3dLight.Type = D3DLIGHT_POINT;
d3dLight.Diffuse.r  = 1.0f;
d3dLight.Diffuse.g  = 1.0f;
d3dLight.Diffuse.b  = 1.0f;
d3dLight.Ambient.r  = 1.0f;
d3dLight.Ambient.g  = 1.0f;
d3dLight.Ambient.b  = 1.0f;
d3dLight.Specular.r = 1.0f;
d3dLight.Specular.g = 1.0f;
d3dLight.Specular.b = 1.0f;

// Position it high in the scene and behind the user.
// Remember, these coordinates are in world space, so
// the user could be anywhere in world space, too.
// For the purposes of this example, assume the user
// is at the origin of world space.
d3dLight.Position.x = 0.0f;
d3dLight.Position.y = 1000.0f;
d3dLight.Position.z = -100.0f;

// Don't attenuate.
d3dLight.Attenuation0 = 1.0f;
d3dLight.Range        = 1000.0f;

// Set the property information for the first light.
hr = d3dDevice->SetLight(0, &d3dLight);
if (SUCCEEDED(hr))
    // Handle Success
else
    // Handle failure

Enable a light source by calling the IDirect3DDevice9::LightEnable method for the device.

See Also

IDirect3DDevice9::GetLight, IDirect3DDevice9::GetLightEnable, IDirect3DDevice9::LightEnable


IDirect3DDevice9::SetMaterial Method

Sets the material properties for the device.

Syntax

HRESULT SetMaterial(

    CONST D3DMATERIAL9 *pMaterial
);

Parameters

pMaterial
[in] Pointer to a D3DMATERIAL9 structure, describing the material properties to set.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL if the pMaterial parameter is invalid.

See Also

IDirect3DDevice9::GetMaterial


IDirect3DDevice9::SetNPatchMode Method

Enable or disable N-patches.

Syntax

HRESULT SetNPatchMode(

    float nSegments
);

Parameters

nSegments
[in] Specifies the number of subdivision segments. If the number of segments is less than 1.0, N-patches are disabled. The default value is 0.0.

Return Value

If the method succeeds, the return value is D3D_OK.

See Also

IDirect3DDevice9::GetNPatchMode


IDirect3DDevice9::SetPaletteEntries Method

Sets palette entries.

Syntax

HRESULT SetPaletteEntries(

    UINT PaletteNumber,
    const PALETTEENTRY *pEntries
);

Parameters

PaletteNumber
[in] An ordinal value identifying the particular palette upon which the operation is to be performed.
pEntries
[in] Pointer to a PALETTEENTRY structure, representing the palette entries to set. The number of PALETTEENTRY structures pointed to by pEntries is assumed to be 256. See Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For Microsoft DirectX 9.0 applications, any palette sent to this method must conform to the D3DPTEXTURECAPS_ALPHAPALETTE capability bit of the D3DCAPS9 structure. If D3DPTEXTURECAPS_ALPHAPALETTE is not set, every entry in the palette must have alpha set to 1.0 or this method will fail with D3DERR_INVALIDCALL. If D3DPTEXTURECAPS_ALPHAPALETTE is set, then any set of alpha values are allowed. Note that the debug runtime will print a warning message if all palette entries have alpha set to 0.

A single logical palette is associated with the device, and is shared by all texture stages.

See Also

IDirect3DDevice9::GetCurrentTexturePalette, IDirect3DDevice9::GetPaletteEntries, IDirect3DDevice9::SetCurrentTexturePalette, Texture Palettes


IDirect3DDevice9::SetPixelShader Method

Sets the current pixel shader to a previously created pixel shader.

Syntax

HRESULT SetPixelShader(

    IDirect3DPixelShader9* pShader
);

Parameters

pShader
[in] Pixel shader interface.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DDevice9::GetPixelShader


IDirect3DDevice9::SetPixelShaderConstantB Method

Sets a Boolean shader constant.

Syntax

HRESULT SetPixelShaderConstantB(

    UINT StartRegister,
    CONST BOOL *pConstantData,
    UINT BoolCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in] Pointer to an array of constants.
BoolCount
[in] Number of boolean values in the array of constants.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

See Also

IDirect3DDevice9::GetPixelShaderConstantB


IDirect3DDevice9::SetPixelShaderConstantF Method

Sets a floating-point shader constant.

Syntax

HRESULT SetPixelShaderConstantF(

    UINT StartRegister,
    CONST float *pConstantData,
    UINT Vector4fCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in] Pointer to an array of constants.
Vector4fCount
[in] Number of four float vectors in the array of constants.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

See Also

IDirect3DDevice9::GetPixelShaderConstantF


IDirect3DDevice9::SetPixelShaderConstantI Method

Sets an integer shader constant.

Syntax

HRESULT SetPixelShaderConstantI(

    UINT StartRegister,
    CONST int *pConstantData,
    UINT Vector4iCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in] Pointer to an array of constants.
Vector4iCount
[in] Number of four integer vectors in the array of constants.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

See Also

IDirect3DDevice9::GetPixelShaderConstantI


IDirect3DDevice9::SetRenderState Method

Sets a single device render-state parameter.

Syntax

HRESULT SetRenderState(

    D3DRENDERSTATETYPE State,
    DWORD Value
);

Parameters

State
[in] Device state variable that is being modified. This parameter can be any member of the D3DRENDERSTATETYPE enumerated type.
Value
[in] New value for the device render state to be set. The meaning of this parameter is dependent on the value specified for State. For example, if State were D3DRS_SHADEMODE, the second parameter would be one member of the D3DSHADEMODE enumerated type.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if one of the arguments is invalid.

See Also

IDirect3DDevice9::GetRenderState, IDirect3DDevice9::SetTransform


IDirect3DDevice9::SetRenderTarget Method

Sets a new color buffer for the device.

Syntax

HRESULT SetRenderTarget(

    DWORD RenderTargetIndex,
    IDirect3DSurface9 *pRenderTarget
);

Parameters

RenderTargetIndex
[in] Index of the render target. See Remarks.
pRenderTarget
[in] Pointer to a new color buffer. If NULL, the color buffer for the corresponding RenderTargetIndex is disabled. Devices always must be associated with a color buffer.

The new render-target surface must have at least D3DUSAGE_RENDERTARGET specified.

Return Value

If the method succeeds, the return value is D3D_OK.

This method will return D3DERR_INVALIDCALL if either:
  • pRenderTarget = NULL and RenderTargetIndex = 0
  • pRenderTarget is != NULL and the render target is invalid.

Remarks

The device can support multiple render targets. The number of render targets supported by a device is contained in the NumSimultaneousRTs member of D3DCAPS9. See Multiple Render Targets.

Some hardware tests the compatibility of the depth stencil buffer with the color buffer. If this is done, it is only done in a debug build.

Restrictions for using this method include the following:

  • The multisample type must be the same for the render target and the depth stencil surface.
  • The formats must be compatible for the render target and the depth stencil surface. See IDirect3D9::CheckDepthStencilMatch.
  • The size of the depth stencil surface must be greater than or equal to the size of the render target.

These restrictions are validated only when using the debug runtime when any of the IDirect3DDevice9 Draw methods are called.

Cube textures differ from other surfaces in that they are collections of surfaces. To call IDirect3DDevice9::SetRenderTarget with a cube texture, you must select an individual face using IDirect3DCubeTexture9::GetCubeMapSurface and pass the resulting surface to IDirect3DDevice9::SetRenderTarget.


IDirect3DDevice9::SetSamplerState Method

Sets the sampler state value.

Syntax

HRESULT SetSamplerState(

    DWORD Sampler,
    D3DSAMPLERSTATETYPE Type,
    DWORD Value
);

Parameters

Sampler
[in] The sampler stage index.
Type
[in] This parameter can be any member of the D3DSAMPLERSTATETYPE enumerated type.
Value
[in] State value to set. The meaning of this value is determined by the Type parameter.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DDevice9::GetSamplerState


IDirect3DDevice9::SetScissorRect Method

Sets the scissor rectangle.

Syntax

HRESULT SetScissorRect(

    CONST RECT *pRect
);

Parameters

pRect
[in] Pointer to a RECT World Wide Web link structure that defines the rendering area within the render target if scissor test is enabled. This parameter may not be NULL.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The scissor rectangle is used as a rectangular clipping region.

See Rectangles for further information on the use of rectangles in Microsoft DirectX.


IDirect3DDevice9::SetSoftwareVertexProcessing Method

Use this method to switch between software and hardware vertex processing.

Syntax

HRESULT SetSoftwareVertexProcessing(

    BOOL bSoftware
);

Parameters

bSoftware
[in] TRUE to specify software vertex processing; FALSE to specify hardware vertex processing.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The restrictions for changing modes are as follows:

  • If a device is created with D3DCREATE_SOFTWARE_VERTEXPROCESSING, the vertex processing will be done in software and cannot be changed.
  • If a device is created with D3DCREATE_HARDWARE_VERTEXPROCESSING, the vertex processing will be done in hardware and cannot be changed.
  • If a device is created with D3DCREATE_MIXED_VERTEXPROCESSING, the vertex processing will be done in hardware by default. The processing can be switched to software (or back to hardware) using IDirect3DDevice9::SetSoftwareVertexProcessing.

An application can create a mixed-mode device to use both the software vertex processing and the hardware vertex processing. To switch between the two vertex processing modes in Microsoft DirectX 8.x, use IDirect3DDevice8::SetRenderState with the render state D3DRS_SOFTWAREVERTEXPROCESSING and the appropriate DWORD argument. The drawback of the render state approach was the difficulty in defining the semantics for state blocks. Applications and the runtime had to do extra work and be careful while recording and playing back state blocks.

In DirectX 9.0, use SetSoftwareVertexProcessing instead. This new application programming interface (API) is not recorded by StateBlocks.

See Also

IDirect3DDevice9::GetSoftwareVertexProcessing


IDirect3DDevice9::SetStreamSource Method

Binds a vertex buffer to a device data stream. For more information, see Setting the Stream Source.

Syntax

HRESULT SetStreamSource(

    UINT StreamNumber,
    IDirect3DVertexBuffer9 *pStreamData,
    UINT OffsetInBytes,
    UINT Stride
);

Parameters

StreamNumber
[in] Specifies the data stream, in the range from 0 to the maximum number of streams -1.
pStreamData
[in] Pointer to an IDirect3DVertexBuffer9 interface, representing the vertex buffer to bind to the specified data stream.
OffsetInBytes
[in] Offset from the beginning of the stream to the beginning of the vertex data, in bytes. To find out if the device supports stream offsets, see the D3DDEVCAPS2_STREAMOFFSET constant in D3DDEVCAPS2.
Stride
[in] Stride of the component, in bytes. See Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When a flexible vertex format (FVF) vertex shader is used, the stride of the vertex stream must match the vertex size, computed from the FVF. When a declaration is used, the stride should be greater than or equal to the stream size computed from the declaration.

When an application no longer holds a references to this interface, the interface will automatically be freed.

See Also

IDirect3DDevice9::GetStreamSource, IDirect3DDevice9::DrawIndexedPrimitive, IDirect3DDevice9::DrawIndexedPrimitiveUP, IDirect3DDevice9::DrawPrimitive, IDirect3DDevice9::DrawPrimitiveUP


IDirect3DDevice9::SetStreamSourceFreq Method

Sets the stream source frequency divider value. This may be used to draw several instances of geometry.

Syntax

HRESULT SetStreamSourceFreq(

    UINT StreamNumber,
    UINT FrequencyParameter
);

Parameters

StreamNumber
[in] Stream source number.
FrequencyParameter
[in] This parameter may have two different values. See Drawing Multiple Instances of Geometry Efficiently.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DDevice9::GetStreamSourceFreq


IDirect3DDevice9::SetTexture Method

Assigns a texture to a stage for a device.

Syntax

HRESULT SetTexture(

    DWORD Sampler,
    IDirect3DBaseTexture9 *pTexture
);

Parameters

Sampler
[in] Zero based sampler number. Textures are bound to samplers; samplers define sampling state such as the filtering mode and the address wrapping mode. Textures are referenced differently by the programmable and the fixed function pipeline:
  • Programmable shaders reference textures using the sampler number. The number of samplers available to a programmable shader is dependent on the shader version. For vertex shaders, see see Sampler. For pixel shaders see Sampler.
  • The fixed function pipeline on the other hand, references textures by texture stage number. The maximum number of samplers is determined from two caps: MaxSimultaneousTextures and MaxTextureBlendStages of the D3DCAPS9 structure.

There are two other special cases for stage/sampler numbers.

  • A special number called D3DDDMAPSAMPLER is used for Displacement Mapping.
  • A programmable vertex shader uses a special number defined by a D3DVERTEXTEXTURESAMPLER when accessing Vertex Textures in vs_3_0.
pTexture
[in] Pointer to an IDirect3DBaseTexture9 interface, representing the texture being set.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

IDirect3DDevice9::SetTexture is not allowed if the texture is created with a pool type of D3DPOOL_SCRATCH. IDirect3DDevice9::SetTexture is not allowed with a pool type of D3DPOOL_SYSTEMMEM texture unless DevCaps is set with D3DDEVCAPS_TEXTURESYSTEMMEMORY.

See Also

IDirect3DDevice9::GetTexture, IDirect3DDevice9::GetTextureStageState, IDirect3DDevice9::SetTextureStageState


IDirect3DDevice9::SetTextureStageState Method

Sets the state value for the currently assigned texture.

Syntax

HRESULT SetTextureStageState(

    DWORD Stage,
    D3DTEXTURESTAGESTATETYPE Type,
    DWORD Value
);

Parameters

Stage
[in] Stage identifier of the texture for which the state value is set. Stage identifiers are zero-based. Devices can have up to eight set textures, so the maximum value allowed for Stage is 7.
Type
[in] Texture state to set. This parameter can be any member of the D3DTEXTURESTAGESTATETYPE enumerated type.
Value
[in] State value to set. The meaning of this value is determined by the Type parameter.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DDevice9::GetTextureStageState, IDirect3DDevice9::GetTexture, IDirect3DDevice9::SetTexture


IDirect3DDevice9::SetTransform Method

Sets a single device transformation-related state.

Syntax

HRESULT SetTransform(

    D3DTRANSFORMSTATETYPE State,
    CONST D3DMATRIX *pMatrix
);

Parameters

State
[in] Device-state variable that is being modified. This parameter can be any member of the D3DTRANSFORMSTATETYPE enumerated type, or the D3DTS_WORLDMATRIX macro.
pMatrix
[in] Pointer to a D3DMATRIX structure that modifies the current transformation.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if one of the arguments is invalid.

See Also

IDirect3DDevice9::GetTransform, IDirect3DDevice9::SetRenderState, D3DTS_WORLD, D3DTS_WORLDn, D3DTS_WORLDMATRIX


IDirect3DDevice9::SetVertexDeclaration Method

Sets a vertex shader declaration.

Syntax

HRESULT SetVertexDeclaration(

    IDirect3DVertexDeclaration9 *pDecl
);

Parameters

pDecl
[in] Pointer to an IDirect3DVertexDeclaration9 object, which contains the vertex declaration.

Return Value

If the method succeeds, the return value is D3D_OK.

The return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DDevice9::GetVertexDeclaration


IDirect3DDevice9::SetVertexShader Method

Sets the vertex shader.

Syntax

HRESULT SetVertexShader(

    IDirect3DVertexShader9* pShader
);

Parameters

pShader
[in] Vertex shader interface. For more information, see IDirect3DVertexShader9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

To set a fixed-function vertex shader (after having set a programmable vertex shader), call IDirect3DDevice9::SetVertexShader(NULL) to release the programmable shader, and then call IDirect3DDevice9::SetFVF with the fixed-function vertex format.

See Also

IDirect3DDevice9::GetVertexShader


IDirect3DDevice9::SetVertexShaderConstantB Method

Sets a Boolean vertex shader constant.

Syntax

HRESULT SetVertexShaderConstantB(

    UINT StartRegister,
    CONST BOOL *pConstantData,
    UINT BoolCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in] Pointer to an array of constants.
BoolCount
[in] Number of boolean values in the array of constants.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


IDirect3DDevice9::SetVertexShaderConstantF Method

Sets a floating-point vertex shader constant.

Syntax

HRESULT SetVertexShaderConstantF(

    UINT StartRegister,
    CONST float *pConstantData,
    UINT Vector4fCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in] Pointer to an array of constants.
Vector4fCount
[in] Number of four float vectors in the array of constants.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


IDirect3DDevice9::SetVertexShaderConstantI Method

Sets an integer vertex shader constant.

Syntax

HRESULT SetVertexShaderConstantI(

    UINT StartRegister,
    CONST int *pConstantData,
    UINT Vector4iCount
);

Parameters

StartRegister
[in] Register number that will contain the first constant value.
pConstantData
[in] Pointer to an array of constants.
Vector4iCount
[in] Number of four integer vectors in the array of constants.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


IDirect3DDevice9::SetViewport Method

Sets the viewport parameters for the device.

Syntax

HRESULT SetViewport(

    CONST D3DVIEWPORT9 *pViewport
);

Parameters

pViewport
[in] Pointer to a D3DVIEWPORT9 structure, specifying the viewport parameters to set.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, it will return D3DERR_INVALIDCALL. This will happen if pViewport is invalid, or if pViewport describes a region that cannot exist within the render target surface.

Remarks

Microsoft Direct3D sets the following default values for the viewport.

D3DVIEWPORT9 vp;
vp.X      = 0;
vp.Y      = 0;
vp.Width  = RenderTarget.Width;
vp.Height = RenderTarget.Height;
vp.MinZ   = 0.0f;
vp.MaxZ   = 1.0f;

IDirect3DDevice9::SetViewport can be used to draw on part of the screen. Make sure to call it before any geometry is drawn so the viewport settings will take effect.

To draw multiple views within a scene, repeat the IDirect3DDevice9::SetViewport and draw geometry sequence for each view.

See Also

IDirect3DDevice9::GetViewport


IDirect3DDevice9::ShowCursor Method

Displays or hides the cursor.

Syntax

BOOL ShowCursor(

    BOOL bShow
);

Parameters

bShow
[in] If bShow is TRUE, the cursor is shown. If bShow is FALSE, the cursor is hidden.

Return Value

Value indicating whether the cursor was previously visible. TRUE if the cursor was previously visible, or FALSE if the cursor was not previously visible.

Remarks

Microsoft Direct3D cursor functions use either Microsoft Windows Graphics Device Interface (GDI) cursor or software emulation, depending on the hardware. Users usually want to respond to a WM_SETCURSOR message. For example, the users might want to write the message handler like this:

case WM_SETCURSOR:
    // Turn off window cursor
    SetCursor( NULL );
    m_pd3dDevice->ShowCursor( TRUE );
    return TRUE; // prevent Windows from setting cursor to window class cursor
break;

Or users might want to call the IDirect3DDevice9::SetCursorProperties method if they want to change the cursor. See the code in the Microsoft DirectX Graphics C/C++ Samples for more detail.

See Also

IDirect3DDevice9::SetCursorPosition, IDirect3DDevice9::SetCursorProperties


IDirect3DDevice9::StretchRect Method

Copy the contents of the source rectangle to the destination rectangle. The source rectangle can be stretched and filtered by the copy. This function is often used to change the aspect ratio of a video stream.

Syntax

HRESULT StretchRect(

    IDirect3DSurface9 *pSourceSurface,
    CONST RECT *pSourceRect,
    IDirect3DSurface9 *pDestSurface,
    CONST RECT *pDestRect,
    D3DTEXTUREFILTERTYPE Filter
);

Parameters

pSourceSurface
[in] Pointer to the source surface. See IDirect3DSurface9.
pSourceRect
[in] Pointer to the source rectangle. A NULL for this parameter causes the entire source surface to be used.
pDestSurface
[in] Pointer to the destination surface. See IDirect3DSurface9.
pDestRect
[in] Pointer to the destination rectangle. A NULL for this parameter causes the entire destination surface to be used.
Filter
[in] Filter type. Allowable values are D3DTEXF_NONE, D3DTEXF_POINT, or D3DTEXF_LINEAR. For more information, see D3DTEXTUREFILTERTYPE.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be:

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

General Restrictions

There are many restrictions as to which surface combinations are valid for IDirect3DDevice9::StretchRect. Factors include whether the driver is a Microsoft DirectX 9.0 driver or older, and whether the operation will result in stretching/shrinking. Since applications are not expected to recognize if the driver is a DirectX 9.0 driver or not, Microsoft Direct3D will automatically set a new D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES cap in the D3DDEVCAPS2 structure for DirectX 9.0-level drivers and above.

DirectX 8.x Driver (no stretching)

Dest formats
Texture | RT texture | RT | Off-screen plain
Src formats | Texture | No | No | No | No
RT texture | No | Yes | Yes | No
RT | No | Yes | Yes | No
Off-screen plain | Yes | Yes | Yes | Yes

DirectX 8.x Driver (stretching)

Dest formats
Texture | RT texture | RT | Off-screen plain
Src formats | Texture | No | No | No | No
RT texture | No | No | No | No
RT | No | Yes | Yes | No
Off-screen plain | No | Yes | Yes | No

DirectX 9.0 Driver (no stretching)

Dest formats
Texture | RT texture | RT | Off-screen plain
Src formats | Texture | No | Yes | Yes | No
RT texture | No | Yes | Yes | No
RT | No | Yes | Yes | No
Off-screen plain | No | Yes | Yes | Yes

DirectX 9.0 Driver (stretching)

Dest formats
Texture | RT texture | RT | Off-screen plain
Src formats | Texture | No | Yes | Yes | No
RT texture | No | Yes | Yes | No
RT | No | Yes | Yes | No
Off-screen plain | No | Yes | Yes | No

IDirect3DDevice9::StretchRect requires that both the source and destination surfaces must be created in the default memory pool.

If filtering is specified, IDirect3DDevice9::StretchRect will fail unless the driver sets the appropriate StretchRectFilterCaps in D3DCAPS9. If D3DTEXF_NONE is specified, the driver will choose a filtering algorithm.

The stretch operation supports color-space conversion from YUV to high-precision RGBA only. Stretching between rectangles on the same surface is not supported. Use IDirect3D9::CheckDeviceFormatConversion to test the hardware for color conversion support because software emulation for the conversion is not supported.

Texture Restrictions

IDirect3DDevice9::StretchRect will work for a texture surface (or a cube texture surface) only for DirectX 9.0 drivers (drivers that set D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES).

Depth and Stencil Restrictions

Depth and stencil surfaces can be copied using IDirect3DDevice9::StretchRect with the following restrictions:

  • Both the source and destination surfaces must be created with IDirect3DDevice9::CreateDepthStencilSurface, because they must be plain depth stencil surfaces (not textures).
  • Both surfaces must be the same format (no format conversion).
  • No stretching or shrinking is allowed.
  • Subrectangle copies are not allowed. The entire surface must be copied. In other words, the source and destination rectangle must be NULL, or point to rectangles that cover the whole surface.
  • IDirect3DDevice9::StretchRect cannot be called inside of IDirect3DDevice9::BeginScene/IDirect3DDevice9::EndScene pairs.
  • The source or destination surface can't be a mip level of a texture (cube texture) created as a depth stencil surface.
  • Neither of the surfaces can be created as discardable.
  • Drivers must set D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES.

IDirect3DDevice9::StretchRect will fail for any of the following:

  • If the source and destination surface are the same.
  • If stretching or shrinking is involved, or if either surface is in a compressed format (see Using Compressed Textures).
  • If the destination surface is an off-screen plain surface but the source is not. If the destination surface is an off-screen plain surface and stretching is involved.

Downsampling a Multisample Rendertarget

You can use IDirect3DDevice9::StretchRect to copy from one rendertarget to another. If the source rendertarget is multisampled, this results in downsampling the source rendertarget. For instance you would:

  • Create a multisampled rendertarget.
  • Create a second rendertarget of the same size, that is not multisampled.
  • Copy (using IDirect3DDevice9::StretchRect) the multisample rendertarget to the second rendertarget.


IDirect3DDevice9::TestCooperativeLevel Method

Reports the current cooperative-level status of the Microsoft Direct3D device for a windowed or full-screen application.

Syntax

HRESULT TestCooperativeLevel(VOID);

Return Value

If the method succeeds, the return value is D3D_OK, indicating that the device is operational and the calling application can continue.

If the method fails, the return value can be one of the following values (see Remarks).

D3DERR_DEVICELOST | The device has been lost but cannot be reset at this time. Therefore, rendering is not possible.
D3DERR_DEVICENOTRESET | The device has been lost but can be reset at this time.
D3DERR_DRIVERINTERNALERROR

Internal driver error. Applications should generally shut down when receiving this error. For more information, see Driver Internal Errors.

Remarks

If the device is lost but cannot be restored at the current time, IDirect3DDevice9::TestCooperativeLevel returns the D3DERR_DEVICELOST return code. This would be the case, for example, when a full-screen device has lost focus. If an application detects a lost device, it should pause and periodically call IDirect3DDevice9::TestCooperativeLevel until it receives a return value of D3DERR_DEVICENOTRESET. The application may then attempt to reset the device by calling IDirect3DDevice9::Reset and, if this succeeds, restore the necessary resources and resume normal operation. Note that IDirect3DDevice9::Present will return D3DERR_DEVICELOST if the device is either "lost" or "not reset".

A call to IDirect3DDevice9::TestCooperativeLevel will fail if called on a different thread than that used to create the device being reset.


IDirect3DDevice9::UpdateSurface Method

Copies rectangular subsets of pixels from one surface to another.

Syntax

HRESULT UpdateSurface(

    IDirect3DSurface9* pSourceSurface,
    CONST RECT* pSourceRect,
    IDirect3DSurface9* pDestinationSurface,
    CONST POINT* pDestinationPoint
);

Parameters

pSourceSurface
[in] Pointer to an IDirect3DSurface9 interface, representing the source surface. This parameter must point to a different surface than pDestinationSurface.
pSourceRect
[in] Pointer to a rectangle on the source surface. Specifying NULL for this parameter causes the entire surface to be copied.
pDestinationSurface
[in] Pointer to an IDirect3DSurface9 interface, representing the destination surface.
pDestinationPoint
[in] Pointer to the upper left corner of the destination rectangle. Specifying NULL for this parameter causes the entire surface to be copied.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This method is similar to CopyRects in Microsoft DirectX 8.0.

This function has the following restrictions.

  • The source surface must have been created with D3DPOOL_SYSTEMMEM.
  • The destination surface must have been created with D3DPOOL_DEFAULT.
  • Neither surface can be locked or holding an outstanding device context.
  • Neither surface can be created with multisampling. The only valid flag for both surfaces is D3DMULTISAMPLE_NONE.
  • The surface format cannot be a depth stencil format.
  • The source and dest rects must fit within the surface.
  • No stretching or shrinking is allowed (the rects must be the same size).
  • The source format must match the dest format.

The following table shows the supported combinations.

Dest formats
Texture | RT texture | RT | Off-screen plain
Src formats | Texture | Yes | Yes | Yes* | Yes
RT texture | No | No | No | No
RT | No | No | No | No
Off-screen plain | Yes | Yes | Yes | Yes

* If the driver does not support the requested copy, it will be emulated using lock and copy.

If the application needs to copy data from a D3DPOOL_DEFAULT render target to a D3DPOOL_SYSTEMMEM surface, it can use IDirect3DDevice9::GetRenderTargetData.


IDirect3DDevice9::UpdateTexture Method

Updates the dirty portions of a texture.

Syntax

HRESULT UpdateTexture(

    IDirect3DBaseTexture9 *pSourceTexture,
    IDirect3DBaseTexture9 *pDestinationTexture
);

Parameters

pSourceTexture
[in] Pointer to an IDirect3DBaseTexture9 interface, representing the source texture. The source texture must be in system memory (D3DPOOL_SYSTEMMEM).
pDestinationTexture
[in] Pointer to an IDirect3DBaseTexture9 interface, representing the destination texture. The destination texture must be in the D3DPOOL_DEFAULT memory pool.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

You can dirty a portion of a texture by locking it, or by calling one of the following methods.

  • IDirect3DCubeTexture9::AddDirtyRect
  • IDirect3DTexture9::AddDirtyRect
  • IDirect3DVolumeTexture9::AddDirtyBox
  • IDirect3DDevice9::UpdateSurface

IDirect3DDevice9::UpdateTexture retrieves the dirty portions of the texture by calculating what has been accumulated since the last update operation.

For performance reasons, dirty regions are only recorded for level zero of a texture. For sublevels, it is assumed that the corresponding (scaled) rectangle or box is also dirty. Dirty regions are automatically recorded when LockRect or IDirect3DVolumeTexture9::LockBox is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. Also, the destination surface of IDirect3DDevice9::UpdateSurface is marked dirty.

This method fails if the textures are of different types, if their bottom-level buffers are of different sizes, or if their matching levels do not match. For example, consider a six-level source texture with the following dimensions.

32x16, 16x8, 8x4, 4x2, 2x1, 1x1

This six-level source texture could be the source for the following one-level destination.

1x1

For the following two-level destination.

2x1, 1x1

Or, for the following three-level destination.

4x2, 2x1, 1x1

In addition, this method will fail if the textures are of different formats. If the destination texture has fewer levels than the source, only the matching levels are copied. If the source texture has fewer levels than the destination, the method will fail.

If the source texture has dirty regions, the copy can be optimized by restricting the copy to only those regions. It is not guaranteed that only those bytes marked dirty will be copied.

Here are the possibilities for source and destination surface combinations:

  • If pSourceTexture is a non-autogenerated mipmap and pDestinationTexture is an autogenerated mipmap, only the topmost matching level is updated, and the destination sublevels are regenerated. All other source sublevels are ignored.
  • If both pSourceTexture and pDestinationTexture are autogenerated mipmaps, only the topmost matching level is updated. The sublevels from the source are ignored and the destination sublevels are regenerated.
  • If pSourceTexture is an autogenerated mipmap and pDestinationTexture a non-autogenerated mipmap, UpdateTexture will fail.

See Also

IDirect3D9::CreateDevice


IDirect3DDevice9::ValidateDevice Method

Reports the device's ability to render the current texture-blending operations and arguments in a single pass.

Syntax

HRESULT ValidateDevice(

    DWORD *pNumPasses
);

Parameters

pNumPasses
[out, retval] Pointer to a DWORD value to fill with the number of rendering passes needed to complete the desired effect through multipass rendering.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_CONFLICTINGRENDERSTATE | The currently set render states cannot be used together.
D3DERR_CONFLICTINGTEXTUREFILTER | The current texture filters cannot be used together.
D3DERR_DEVICELOST | The device has been lost but cannot be reset at this time. Therefore, rendering is not possible.
D3DERR_DRIVERINTERNALERROR

Internal driver error. Applications should generally shut down when receiving this error. For more information, see Driver Internal Errors.

D3DERR_TOOMANYOPERATIONS | The application is requesting more texture-filtering operations than the device supports.
D3DERR_UNSUPPORTEDALPHAARG | The device does not support a specified texture-blending argument for the alpha channel.
D3DERR_UNSUPPORTEDALPHAOPERATION | The device does not support a specified texture-blending operation for the alpha channel.
D3DERR_UNSUPPORTEDCOLORARG | The device does not support a specified texture-blending argument for color values.
D3DERR_UNSUPPORTEDCOLOROPERATION | The device does not support a specified texture-blending operation for color values.
D3DERR_UNSUPPORTEDFACTORVALUE | The device does not support the specified texture factor value.
D3DERR_UNSUPPORTEDTEXTUREFILTER | The device does not support the specified texture filter.
D3DERR_WRONGTEXTUREFORMAT | The pixel format of the texture surface is not valid.

Remarks

The IDirect3DDevice9::ValidateDevice method should be used to validate scenarios only when other capabilities are deficient. For example, in a multistage texturing scenario, you could query the MaxTextureBlendStages and MaxSimultaneousTextures members of a D3DCAPS9 structure to determine if multistage texturing is possible on the device.

Current hardware does not necessarily implement all possible combinations of operations and arguments. You can determine whether a particular blending operation can be performed with given arguments by setting the desired blending operation, and then calling the IDirect3DDevice9::ValidateDevice method.

The IDirect3DDevice9::ValidateDevice method uses the current render states, textures, and texture-stage states to perform validation at the time of the call. Changes to these factors after the call invalidate the previous result, and the method must be called again before rendering a scene.

For best performance, call IDirect3DDevice9::ValidateDevice at initialization time; do not use it within a render loop.

Using diffuse iterated values, either as an argument or as an operation (D3DTA_DIFFUSED3DTOP_BLENDDIFFUSEALPHA) is rarely supported on current hardware. Most hardware can introduce iterated color data only at the last texture operation stage.

Try to specify the texture (D3DTA_TEXTURE) for each stage as the first argument, rather than the second argument.

Many cards do not support use of diffuse or scalar values at arbitrary texture stages. Often, these are available only at the first or last texture-blending stage.

Many cards do not have a blending unit associated with the first texture that is capable of more than replicating alpha to color channels or inverting the input. Therefore, your application might need to use only the second texture stage, if possible. On such hardware, the first unit is presumed to be in its default state, which has the first color argument set to D3DTA_TEXTURE with the D3DTOP_SELECTARG1 operation.

Operations on the output alpha that are more intricate than or substantially different from the color operations are less likely to be supported.

Some hardware does not support simultaneous use of D3DTA_TFACTOR and D3DTA_DIFFUSE.

Many cards do not support simultaneous use of multiple textures and mipmapped trilinear filtering. If trilinear filtering has been requested for a texture involved in multitexture blending operations and validation fails, turn off trilinear filtering and revalidate. In this case, you might want to perform multipass rendering instead.

See Also

IDirect3DDevice9::GetTextureStageState, IDirect3DDevice9::SetTextureStageState


IDirect3DIndexBuffer9 Interface

Applications use the methods of the IDirect3DIndexBuffer9 interface to manipulate an index buffer resource.

IDirect3DIndexBuffer9 Members

FreePrivateData | Frees the specified private data associated with this resource.
GetDesc | Retrieves a description of the index buffer resource.
GetDevice | Retrieves the device associated with a resource.
GetPriority | Retrieves the priority for this resource.
GetPrivateData | Copies the private data associated with the resource to a provided buffer.
GetType | Returns the type of the resource.
Lock | Locks a range of index data and obtains a pointer to the index buffer memory.
PreLoad | Preloads a managed resource.
SetPriority | Assigns the resource-management priority for this resource.
SetPrivateData | Associates data with the resource that is intended for use by the application, not by Microsoft Direct3D. Data is passed by value, and multiple sets of data can be associated with a single resource.
Unlock | Unlocks index data.

Remarks

The IDirect3DIndexBuffer9 interface is obtained by calling the IDirect3DDevice9::CreateIndexBuffer method.

This interface inherits additional functionality from the IDirect3DResource9 interface.

This interface, like all Component Object Model (COM) interfaces, inherits from the IUnknown interface.

The LPDIRECT3DINDEXBUFFER9 and PDIRECT3DINDEXBUFFER9 types are defined as pointers to the IDirect3DIndexBuffer9 interface.

typedef struct IDirect3DIndexBuffer9 *LPDIRECT3DINDEXBUFFER9, *PDIRECT3DINDEXBUFFER9;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IDirect3DResource9
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::CreateIndexBuffer, Index Buffers


IDirect3DIndexBuffer9::GetDesc Method

Retrieves a description of the index buffer resource.

Syntax

HRESULT GetDesc(

    D3DINDEXBUFFER_DESC *pDesc
);

Parameters

pDesc
[out] Pointer to a D3DINDEXBUFFER_DESC structure, describing the returned index buffer.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the argument is invalid.


IDirect3DIndexBuffer9::Lock Method

Locks a range of index data and obtains a pointer to the index buffer memory.

Syntax

HRESULT Lock(

    UINT OffsetToLock,
    UINT SizeToLock,
    VOID **ppbData,
    DWORD Flags
);

Parameters

OffsetToLock
[in] Offset into the index data to lock, in bytes. Lock the entire index buffer by specifying 0 for both parameters, SizeToLock and OffsetToLock.
SizeToLock
[in] Size of the index data to lock, in bytes. Lock the entire index buffer by specifying 0 for both parameters, SizeToLock and OffsetToLock.
ppbData
[out] VOID* pointer to a memory buffer containing the returned index data.
Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY
  • D3DLOCK_NOOVERWRITE

For a description of the flags, see D3DLOCK.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When working with index buffers, you are allowed to make multiple lock calls. However, you must ensure that the number of lock calls match the number of unlock calls. IDirect3DDevice9::DrawIndexedPrimitive calls will not succeed with any outstanding lock count on any currently set index buffer.

The D3DLOCK_DISCARD and D3DLOCK_NOOVERWRITE flags are valid only on buffers created with D3DUSAGE_DYNAMIC.

See Programming Tips for information about using D3DLOCK_DISCARD or D3DLOCK_NOOVERWRITE.

See Also

IDirect3DIndexBuffer9::Unlock


IDirect3DIndexBuffer9::Unlock Method

Unlocks index data.

Syntax

HRESULT Unlock(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DIndexBuffer9::Lock


IDirect3DPixelShader9 Interface

Applications use the methods of the IDirect3DPixelShader9 interface to encapsulate the functionality of a pixel shader.

IDirect3DPixelShader9 Members

GetDevice | Gets the device.
GetFunction | Gets a pointer to the shader data.

Remarks

The LPDIRECT3DPIXELSHADER9 and PDIRECT3DPIXELSHADER9 types are defined as pointers to the IDirect3DPixelShader9 interface.

typedef struct IDirect3DPixelShader9 *LPDIRECT3DPIXELSHADER9, *PDIRECT3DPIXELSHADER9;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98


IDirect3DPixelShader9::GetDevice Method

Gets the device.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[out, retval] Pointer to the IDirect3DDevice9 interface that is returned.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


IDirect3DPixelShader9::GetFunction Method

Gets a pointer to the shader data.

Syntax

HRESULT GetFunction(

    void* pData,
    UINT* pSizeOfData
);

Parameters

pData
[in, out] Pointer to a buffer that contains the shader data. The application needs to allocate enough room for this.
pSizeOfData
[in, out] Size of the data, in bytes. To get the buffer size that is needed to retrieve the data, set pData = NULL when calling GetFunction. Then call GetFunction with the returned size, to get the buffer data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be:

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


IDirect3DQuery9 Interface

Applications use the methods of the IDirect3DQuery9 interface to perform asynchronous queries on a driver.

IDirect3DQuery9 Members

GetData | Polls a queried resource to get the query state or a query result. For more information about queries, see Queries.
GetDataSize | Gets the number of bytes in the query data.
GetDevice | Gets the device that is being queried.
GetType | Gets the query type.
Issue | Issue a query.

Remarks

The LPDIRECT3DQUERY9 and PDIRECT3DQUERY9 types are defined as pointers to the IDirect3DQuery9 interface.

typedef struct IDirect3DQuery9 *LPDIRECT3DQUERY9, *PDIRECT3DQUERY9;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98


IDirect3DQuery9::GetData Method

Polls a queried resource to get the query state or a query result. For more information about queries, see Queries.

Syntax

HRESULT GetData(

    void* pData,
    DWORD dwSize,
    DWORD dwGetDataFlags
);

Parameters

pData
[in, out] Pointer to a buffer containing the query data. The user is responsible for allocating this. pData may be NULL only if dwSize is 0.
dwSize
[in] Number of bytes of data in pData. If you set dwSize to zero, you can use this method to poll the resource for the query status. See remarks.
dwGetDataFlags
[in] Data flags specifying the query type. Valid values are either 0 or D3DGETDATA_FLUSH. Use D3DGETDATA_FLUSH to flush internally batched queries to the driver. For applications writing their own version of waiting, a query result is not realized until the driver receives a flush.

Return Value

The return type identifies the query state (see Queries). The method returns S_OK if the query data is available and S_FALSE if it is not. These are considered successful return values. If the method fails when D3DGETDATA_FLUSH is used, the return value can be D3DERR_DEVICELOST.

Remarks

It is possible to lose the device while polling for query status. When D3DGETDATA_FLUSH is specified, this method will return D3DERR_DEVICELOST in response to a lost device. This allows an application to prevent threads from endlessly polling due to a lost device (which cannot respond to the query).


IDirect3DQuery9::GetDataSize Method

Gets the number of bytes in the query data.

Syntax

DWORD GetDataSize(VOID);

Return Value

Returns the number of bytes of query data.


IDirect3DQuery9::GetDevice Method

Gets the device that is being queried.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **pDevice
);

Parameters

pDevice
[out] Pointer to the device being queried. See IDirect3DDevice9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


IDirect3DQuery9::GetType Method

Gets the query type.

Syntax

D3DQUERYTYPE GetType(VOID);

Return Value

Returns the query type. See D3DQUERYTYPE.


IDirect3DQuery9::Issue Method

Issue a query.

Syntax

HRESULT Issue(

    DWORD dwIssueFlags
);

Parameters

dwIssueFlags
[in] Query flags specify the type of state change for the query. See D3DISSUE_BEGIN and D3DISSUE_END.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A signaled query means the query has completed, the data is available, and IDirect3DQuery9::GetData will return S_OK.


IDirect3DResource9 Interface

Applications use the methods of the IDirect3DResource9 interface to query and prepare resources.

IDirect3DResource9 Members

FreePrivateData | Frees the specified private data associated with this resource.
GetDevice | Retrieves the device associated with a resource.
GetPriority | Retrieves the priority for this resource.
GetPrivateData | Copies the private data associated with the resource to a provided buffer.
GetType | Returns the type of the resource.
PreLoad | Preloads a managed resource.
SetPriority | Assigns the resource-management priority for this resource.
SetPrivateData | Associates data with the resource that is intended for use by the application, not by Microsoft Direct3D. Data is passed by value, and multiple sets of data can be associated with a single resource.

Remarks

To create a texture resource, you can call one of the following methods.

  • IDirect3DDevice9::CreateCubeTexture
  • IDirect3DDevice9::CreateTexture
  • IDirect3DDevice9::CreateVolumeTexture

To create a geometry-oriented resource, you can call one of the following methods.

  • IDirect3DDevice9::CreateIndexBuffer
  • IDirect3DDevice9::CreateVertexBuffer

This interface, like all Component Object Model (COM) interfaces, inherits from the IUnknown interface.

The LPDIRECT3DRESOURCE9 and PDIRECT3DRESOURCE9 types are defined as pointers to the IDirect3DResource9 interface.

typedef struct IDirect3DResource9 *LPDIRECT3DRESOURCE9, *PDIRECT3DRESOURCE9;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

Direct3D Resources


IDirect3DResource9::FreePrivateData Method

Frees the specified private data associated with this resource.

Syntax

HRESULT FreePrivateData(

    REFGUID refguid
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to free.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

Microsoft Direct3D calls this method automatically when a resource is released.

See Also

IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::GetPrivateData, IDirect3DIndexBuffer9::GetPrivateData, IDirect3DVertexBuffer9::GetPrivateData, IDirect3DResource9::SetPrivateData, IDirect3DBaseTexture9::SetPrivateData, IDirect3DCubeTexture9::SetPrivateData, IDirect3DTexture9::SetPrivateData, IDirect3DVolumeTexture9::SetPrivateData, IDirect3DIndexBuffer9::SetPrivateData, IDirect3DVertexBuffer9::SetPrivateData


IDirect3DResource9::GetDevice Method

Retrieves the device associated with a resource.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface to fill with the device pointer, if the query succeeds.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method allows navigation to the owning device object.

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Failure to call IUnknown::Release when finished using this IDirect3DDevice9 interface results in a memory leak.


IDirect3DResource9::GetPriority Method

Retrieves the priority for this resource.

Syntax

DWORD GetPriority(VOID);

Return Value

Returns a DWORD value, indicating the priority of the resource.

Remarks

IDirect3DResource9::GetPriority is used for priority control of managed resources. This method returns 0 on nonmanaged resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::SetPriority, IDirect3DBaseTexture9::SetPriority, IDirect3DCubeTexture9::SetPriority, IDirect3DTexture9::SetPriority, IDirect3DVolumeTexture9::SetPriority, IDirect3DIndexBuffer9::SetPriority, IDirect3DVertexBuffer9::SetPriority


IDirect3DResource9::GetPrivateData Method

Copies the private data associated with the resource to a provided buffer.

Syntax

HRESULT GetPrivateData(

    REFGUID refguid,
    void *pData,
    DWORD *pSizeOfData
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to retrieve.
pData
[in, out] Pointer to a previously allocated buffer to fill with the requested private data if the call succeeds. The application calling this method is responsible for allocating and releasing this buffer. If this parameter is NULL, this method will return the buffer size in pSizeOfData.
pSizeOfData
[in, out] Pointer to the size of the buffer at pData, in bytes. If this value is less than the actual size of the private data (such as 0), the method sets this parameter to the required buffer size and the method returns D3DERR_MOREDATA.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_MOREDATA | There is more data available than the specified buffer size can hold.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

This method is inherited by the following interfaces: IDirect3DResource9, IDirect3DBaseTexture9, IDirect3DCubeTexture9, IDirect3DTexture9, IDirect3DVolumeTexture9, IDirect3DIndexBuffer9, IDirect3DVertexBuffer9.


IDirect3DResource9::GetType Method

Returns the type of the resource.

Syntax

D3DRESOURCETYPE GetType(VOID);

Return Value

Returns a member of the D3DRESOURCETYPE enumerated type, identifying the type of the resource.


IDirect3DResource9::PreLoad Method

Preloads a managed resource.

Syntax

void PreLoad(VOID);

Return Value

No return value.

Remarks

Calling this method indicates that the application will need this managed resource shortly. This method has no effect on nonmanaged resources.

IDirect3DResource9::PreLoad detects "thrashing" conditions where more resources are being used in each frame than can fit in video memory simultaneously. Under such circumstances IDirect3DResource9::PreLoad silently does nothing.


IDirect3DResource9::SetPriority Method

Assigns the resource-management priority for this resource.

Syntax

DWORD SetPriority(

    DWORD PriorityNew
);

Parameters

PriorityNew
[in] DWORD value that specifies the new resource-management priority for the resource.

Return Value

Returns the previous priority value for the resource.

Remarks

IDirect3DResource9::SetPriority is used for priority control of managed resources. This method returns 0 on non-managed resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::GetPriority, IDirect3DBaseTexture9::GetPriority, IDirect3DCubeTexture9::GetPriority, IDirect3DTexture9::GetPriority, IDirect3DVolumeTexture9::GetPriority, IDirect3DIndexBuffer9::GetPriority, IDirect3DVertexBuffer9::GetPriority


IDirect3DResource9::SetPrivateData Method

Associates data with the resource that is intended for use by the application, not by Microsoft Direct3D. Data is passed by value, and multiple sets of data can be associated with a single resource.

Syntax

HRESULT SetPrivateData(

    REFGUID refguid,
    const void *pData,
    DWORD SizeOfData,
    DWORD Flags
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to set.
pData
[in] Pointer to a buffer that contains the data to be associated with the resource.
SizeOfData
[in] Size of the buffer at pData, in bytes.
Flags
[in] Value that describes the type of data being passed, or indicates to the application that the data should be invalidated when the resource changes.
(none)
If no flags are specified, Direct3D allocates memory to hold the data within the buffer and copies the data into the new buffer. The buffer allocated by Direct3D is automatically freed, as appropriate.
D3DSPD_IUNKNOWN
The data at pData is a pointer to an IUnknown interface. SizeOfData must be set to the size of a pointer to an IUnknown interface, sizeof(IUnknown*). Direct3D automatically calls IUnknown::AddRef through pData and IUnknown::Release when the private data is destroyed. Private data will be destroyed by a subsequent call to IDirect3DResource9::SetPrivateData with the same GUID, a subsequent call to IDirect3DResource9::FreePrivateData, or when the IDirect3D9 object is released. For more information, see Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Direct3D does not manage the memory at pData. If this buffer was dynamically allocated, it is the calling application's responsibility to free the memory.

See Also

IDirect3DResource9::FreePrivateData, IDirect3DBaseTexture9::FreePrivateData, IDirect3DCubeTexture9::FreePrivateData, IDirect3DTexture9::FreePrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData, IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData


IDirect3DStateBlock9 Interface

Applications use the methods of the IDirect3DStateBlock9 interface to encapsulate render states.

IDirect3DStateBlock9 Members

Apply | Apply the state block to the current device state.
Capture | Capture the device's current state.
GetDevice | Gets the device.

Remarks

This interface can be used to save and restore pipeline state. It can also be used to capture the current state.

The LPDIRECT3DSTATEBLOCK9 and PDIRECT3DSTATEBLOCK9 types are defined as pointers to the IDirect3DStateBlock9 interface.

typedef struct IDirect3DStateBlock9 *LPDIRECT3DSTATEBLOCK9, *PDIRECT3DSTATEBLOCK9;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98


IDirect3DStateBlock9::Apply Method

Apply the state block to the current device state.

Syntax

HRESULT Apply(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails while in record mode, the return value is D3DERR_INVALIDCALL.


IDirect3DStateBlock9::Capture Method

Capture the device's current state.

Syntax

HRESULT Capture(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails because capture cannot be done while in record mode, the return value is D3DERR_INVALIDCALL.


IDirect3DStateBlock9::GetDevice Method

Gets the device.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[in, out, retval] Pointer to the IDirect3DDevice9 interface that is returned.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


IDirect3DSurface9 Interface

Applications use the methods of the IDirect3DSurface9 interface to query and prepare surfaces.

IDirect3DSurface9 Members

FreePrivateData | Frees the specified private data associated with this resource.
GetContainer | Provides access to the parent cube texture or texture (mipmap) object, if this surface is a child level of a cube texture or a mipmap. This method can also provide access to the parent swap chain if the surface is a back-buffer child.
GetDC | Retrieves a device context.
GetDesc

Retrieves a description of the surface.

GetDevice | Retrieves the device associated with a resource.
GetPriority | Retrieves the priority for this resource.
GetPrivateData | Copies the private data associated with the resource to a provided buffer.
GetType | Returns the type of the resource.
LockRect

Locks a rectangle on a surface.

PreLoad | Preloads a managed resource.
ReleaseDC | Release a device context handle.
SetPriority | Assigns the resource-management priority for this resource.
SetPrivateData | Associates data with the resource that is intended for use by the application, not by Microsoft Direct3D. Data is passed by value, and multiple sets of data can be associated with a single resource.
UnlockRect | Unlocks a rectangle on a surface.

Remarks

This interface, like all Component Object Model (COM) interfaces, inherits from the IUnknown interface.

The LPDIRECT3DSURFACE9 and PDIRECT3DSURFACE9 types are defined as pointers to the IDirect3DSurface9 interface.

typedef struct IDirect3DSurface9 *LPDIRECT3DSURFACE9, *PDIRECT3DSURFACE9;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IDirect3DResource9
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

Direct3D Surfaces


IDirect3DSurface9::GetContainer Method

Provides access to the parent cube texture or texture (mipmap) object, if this surface is a child level of a cube texture or a mipmap. This method can also provide access to the parent swap chain if the surface is a back-buffer child.

Syntax

HRESULT GetContainer(

    REFIID riid,
    void **ppContainer
);

Parameters

riid
[in] Reference identifier of the container being requested.
ppContainer
[out] Address of a pointer to fill with the container pointer if the query succeeds. See Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the surface is created using IDirect3DDevice9::CreateRenderTarget or IDirect3DDevice9::CreateOffscreenPlainSurface or IDirect3DDevice9::CreateDepthStencilSurface, the surface is considered stand alone. In this case, IDirect3DSurface9::GetContainer will return the Microsoft Direct3D device used to create the surface.

If the call succeeds, the reference count of the container is increased by one.

Here's an example getting the parent texture of a mip surface.

// Assumes pSurface is a valid IDirect3DSurface9 pointer
void *pContainer = NULL;
IDirect3DTexture9 *pTexture = NULL;
HRESULT hr = pSurface->GetContainer(IID_IDirect3DTexture9, &pContainer);
if (SUCCEEDED(hr) && pContainer)
{
    pTexture = (IDirect3DTexture9 *)pContainer;
}


IDirect3DSurface9::GetDC Method

Retrieves a device context.

Syntax

HRESULT GetDC(

    HDC* phdc
);

Parameters

phdc
[out] Pointer to the device context for the surface.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the argument is invalid.

Remarks

The following restrictions apply.

  • IDirect3DSurface9::GetDC is valid on the following formats only: D3DFMT_R5G6B5, D3DFMT_X1R5G5B5, D3DFMT_R8G8B8, and D3DFMT_X8R8G8B8. Formats that contain Alpha are not supported because the Microsoft Windows Graphics Device Interface (GDI) implementations don't have a well-defined behavior on the alpha channel. For more information about formats, see D3DFORMAT.
  • Only one device context per surface can be returned at a time.
  • IDirect3DSurface9::GetDC will fail if the surface is already locked. If the surface is a member of a mipmap or cubemap, IDirect3DSurface9::GetDC fails if any other mipmap or cubemap member is locked.
  • IDirect3DSurface9::GetDC fails on render targets unless they were created lockable (or, in the case of back buffers, with the D3DPRESENTFLAG_LOCKABLE_BACKBUFFER flag).
  • For surfaces not created with IDirect3DDevice9::CreateOffscreenPlainSurface, IDirect3DSurface9::GetDC will fail on default pool (D3DPOOL_DEFAULT) surfaces unless they are dynamic (D3DUSAGE_DYNAMIC) or are lockable render targets.
  • IDirect3DSurface9::GetDC will fail on D3DPOOL_SCRATCH surfaces.

When a device context is outstanding on a surface, the application may not call these methods:

IDirect3DCubeTexture9 | IDirect3DCubeTexture9::LockRect
IDirect3DDevice9 | IDirect3DDevice9::ColorFill
IDirect3DDevice9::StretchRect
IDirect3DDevice9::UpdateSurface
IDirect3DDevice9::UpdateTexture
IDirect3DSurface9 | IDirect3DSurface9::LockRect
IDirect3DSwapChain9 | IDirect3DSwapChain9::Present *
IDirect3DTexture9 | IDirect3DTexture9::LockRect

* (on a swap chain that contains the surface)

IDirect3DSurface9::GetDC causes an implicit lock; do not retain the device context for later use. Call IDirect3DSurface9::ReleaseDC to release it.

It is valid to call IDirect3DSurface9::GetDC/IDirect3DSurface9::ReleaseDC on levels of a mipmap or cubemap, however, these calls will be slow to all miplevels except the topmost level, and GDI operations to these miplevels will not be accelerated.

The handle to a device context (HDC) provides access to Microsoft Win32 and GDI functionality.

See Also

IDirect3DSurface9::ReleaseDC, D3DUSAGE, D3DPOOL, D3DPRESENT_PARAMETERS


IDirect3DSurface9::GetDesc Method

Retrieves a description of the surface.

Syntax

HRESULT GetDesc(

    D3DSURFACE_DESC *pDesc
);

Parameters

pDesc
[out] Pointer to a D3DSURFACE_DESC structure, describing the surface.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the argument is invalid.


IDirect3DSurface9::LockRect Method

Locks a rectangle on a surface.

Syntax

HRESULT LockRect(

    D3DLOCKED_RECT *pLockedRect,
    const RECT *pRect,
    DWORD Flags
);

Parameters

pLockedRect
[out] Pointer to a D3DLOCKED_RECT structure that describes the locked region.
pRect
[in] Pointer to a rectangle to lock. Specified by a pointer to a RECT World Wide Web link structure. Specifying NULL for this parameter expands the dirty region to cover the entire surface.
Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_DONOTWAIT
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY

You may not specify a subrect when using D3DLOCK_DISCARD. For a description of the flags, see D3DLOCK.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL or D3DERR_WASSTILLDRAWING.

Remarks

If the D3DLOCK_DONOTWAIT flag is specified and the driver cannot lock the surface immediately, IDirect3DSurface9::LockRect will return D3DERR_WASSTILLDRAWING so that an application can use the CPU cycles while waiting for the driver to lock the surface.

The only lockable format for a depth-stencil surface is D3DFMT_D16_LOCKABLE. See D3DFORMAT.

For performance reasons, dirty regions are recorded only for level zero of a texture. Dirty regions are automatically recorded when IDirect3DSurface9::LockRect is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. See IDirect3DDevice9::UpdateTexture for more information.

A multisample back buffer cannot be locked.

This method cannot retrieve data from a surface that is is contained by a texture resource created with D3DUSAGE_RENDERTARGET because such a texture must be assigned to D3DPOOL_DEFAULT memory and is therefore not lockable. In this case, use instead IDirect3DDevice9::GetRenderTargetData to copy texture data from device memory to system memory.

See Also

IDirect3DSurface9::UnlockRect


IDirect3DSurface9::ReleaseDC Method

Release a device context handle.

Syntax

HRESULT ReleaseDC(

    HDC hdc
);

Parameters

hdc
[in] Handle to a device context.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the argument is invalid.

Remarks

An handle to a device context (HDC) is a Microsoft Windows resource. It must be released after use so Windows can return it to the pool of available resources.

This method will release only the device context returned by IDirect3DSurface9::GetDC. Otherwise, this method will fail.

See Also

IDirect3DSurface9::GetDC


IDirect3DSurface9::UnlockRect Method

Unlocks a rectangle on a surface.

Syntax

HRESULT UnlockRect(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DSurface9::LockRect


IDirect3DSwapChain9 Interface

Applications use the methods of the IDirect3DSwapChain9 interface to manipulate a swap chain.

IDirect3DSwapChain9 Members

GetBackBuffer | Retrieves a back buffer from the swap chain of the device.
GetDevice | Retrieves the device associated with the swap chain.
GetDisplayMode | Retrieves the display mode's spatial resolution, color resolution, and refresh frequency.
GetFrontBufferData | Generates a copy of the swapchain's front buffer and places that copy in a system memory buffer provided by the application.
GetPresentParameters | Retrieves the presentation parameters associated with a swap chain.
GetRasterStatus | Returns information describing the raster of the monitor on which the swap chain is presented.
Present | Presents the contents of the next buffer in the sequence of back buffers owned by the swap chain.

Remarks

There is always at least one swap chain for each device, known as the implicit swap chain. However, an additional swap chain for rendering multiple views from the same device can be created by calling the IDirect3DDevice9::CreateAdditionalSwapChain method.

This interface, like all Component Object Model (COM) interfaces, inherits from the IUnknown interface.

The LPDIRECT3DSWAPCHAIN9 and PDIRECT3DSWAPCHAIN9 types are defined as pointers to the IDirect3DSwapChain9 interface.

typedef struct IDirect3DSwapChain9 *LPDIRECT3DSWAPCHAIN9, *PDIRECT3DSWAPCHAIN9;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::CreateAdditionalSwapChain


IDirect3DSwapChain9::GetBackBuffer Method

Retrieves a back buffer from the swap chain of the device.

Syntax

HRESULT GetBackBuffer(

    UINT BackBuffer,
    D3DBACKBUFFER_TYPE Type,
    IDirect3DSurface9 **ppBackBuffer
);

Parameters

BackBuffer
[in] Index of the back buffer object to return. Back buffers are numbered from 0 to the total number of back buffers - 1. A value of 0 returns the first back buffer, not the front buffer. The front buffer is not accessible through this method. Use IDirect3DSwapChain9::GetFrontBufferData to retrieve a copy of the front buffer.
Type
[in] Stereo view is not supported in Microsoft DirectX 9.0, so the only valid value for this parameter is D3DBACKBUFFER_TYPE_MONO.
ppBackBuffer
[out, retval] Address of a pointer to an IDirect3DSurface9 interface, representing the returned back buffer surface.

Return Value

If the method succeeds, the return value is D3D_OK.

If BackBuffer exceeds or equals the total number of back buffers, then the function fails and returns D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DSurface9 interface. Failure to call IUnknown::Release when finished using this IDirect3DSurface9 interface results in a memory leak.

See Also

IDirect3DSwapChain9::GetFrontBufferData


IDirect3DSwapChain9::GetDevice Method

Retrieves the device associated with the swap chain.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface to fill with the device pointer, if the query succeeds.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method allows navigation to the owning device object.

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Failure to call IUnknown::Release when finished using this IDirect3DDevice9 interface results in a memory leak.


IDirect3DSwapChain9::GetDisplayMode Method

Retrieves the display mode's spatial resolution, color resolution, and refresh frequency.

Syntax

HRESULT GetDisplayMode(

    D3DDISPLAYMODE *pMode
);

Parameters

pMode
[out] Pointer to a D3DDISPLAYMODE structure containing data about the display mode of the adapter. As opposed to the display mode of the device, which may not be active if the device does not own full-screen mode.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


IDirect3DSwapChain9::GetFrontBufferData Method

Generates a copy of the swapchain's front buffer and places that copy in a system memory buffer provided by the application.

Syntax

HRESULT GetFrontBufferData(

    IDirect3DSurface9 *pDestSurface
);

Parameters

pDestSurface
[in, out] Pointer to an IDirect3DSurface9 interface that will receive a copy of the swapchain's front buffer. The data is returned in successive rows with no intervening space, starting from the vertically highest row to the lowest.

For windowed mode, the size of the destination surface should be the size of the desktop. For full screen mode, the size of the destination surface should be the screen size.

Return Value

If the method succeeds, the return value is D3D_OK.

If BackBuffer exceeds or equals the total number of back buffers, the function fails and returns D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DSurface9 interface. Failure to call IUnknown::Release when finished using this IDirect3DSurface9 interface results in a memory leak.


IDirect3DSwapChain9::GetPresentParameters Method

Retrieves the presentation parameters associated with a swap chain.

Syntax

HRESULT GetPresentParameters(

    D3DPRESENT_PARAMETERS* pPresentationParameters
);

Parameters

pPresentationParameters
[out, retval] Pointer to the presentation parameters. See D3DPRESENT_PARAMETERS.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method can be used to see the presentation parameters of the parent swap chain of a surface (a back buffer, for instance). The parent swap chain can be retrieved with IDirect3DSurface9::GetContainer.


IDirect3DSwapChain9::GetRasterStatus Method

Returns information describing the raster of the monitor on which the swap chain is presented.

Syntax

HRESULT GetRasterStatus(

    D3DRASTER_STATUS *pRasterStatus
);

Parameters

pRasterStatus
[out] Pointer to a D3DRASTER_STATUS structure filled with information about the position or other status of the raster on the monitor driven by this adapter.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if pRasterStatus is invalid or if the device does not support reading the current scan line. To determine if the device supports reading the scan line, check for the D3DCAPS_READ_SCANLINE flag in the Caps member of D3DCAPS9.

Remarks

This method will not return device state for a device that is created using D3DCREATE_PUREDEVICE. If you want to use this method, you must create your device with any of the other values in D3DCREATE."

See Also

D3DRASTER_STATUS


IDirect3DSwapChain9::Present Method

Presents the contents of the next buffer in the sequence of back buffers owned by the swap chain.

Syntax

HRESULT Present(

    const RECT *pSourceRect,
    CONST RECT *pDestRect,
    HWND hDestWindowOverride,
    CONST RGNDATA *pDirtyRegion,
    DWORD dwFlags
);

Parameters

pSourceRect
[in] Pointer to a RECT World Wide Web link structure that contains the source rectangle. This value must be NULL unless the swap chain was created with D3DSWAPEFFECT_COPY. If NULL, the entire source surface is presented. If the rectangle exceeds the source surface, the rectangle is clipped to the source surface.
pDestRect
[in] Pointer to a RECT structure containing the destination rectangle, in window client coordinates. This value must be NULL unless the swap chain was created with D3DSWAPEFFECT_COPY. If NULL, the entire client area is filled. If the rectangle exceeds the destination client area, the rectangle is clipped to the destination client area.
hDestWindowOverride
[in] Destination window whose client area is taken as the target for this presentation. If this value is NULL, the hWndDeviceWindow member of D3DPRESENT_PARAMETERS is taken.
pDirtyRegion
[in] This value must be NULL unless the swap chain was created with D3DSWAPEFFECT_COPY. For more information about swap chains, see Flipping Surfaces and D3DSWAPEFFECT.

If this value is non-NULL, the contained region is expressed in back buffer coordinates. The rectangles within the region are the minimal set of pixels that need to be updated. This method takes these rectangles into account when optimizing the presentation by copying only the pixels within the region, or some suitably expanded set of rectangles. This is an aid to optimization only, and the application should not rely on the region being copied exactly. The implementation may choose to copy the whole source rectangle.
dwFlags
[in] Allows the application to request that the method return immediately when the driver reports that it cannot schedule a presentation. Valid values are 0, or any combination of D3DPRESENT_DONOTWAIT and D3DPRESENT_LINEAR_CONTENT.

If dwFlags = 0, this method behaves as it did prior to Microsoft DirectX 9.0. IDirect3DSwapChain9::Present will spin until the hardware is free, without returning an error.

If dwFlags = D3DPRESENT_DONOTWAIT, and the hardware is busy processing or waiting for a vertical sync interval, the method will return D3DERR_WASSTILLDRAWING.

If dwFlags = D3DPRESENT_LINEAR_CONTENT, gamma correction is performed from linear space to sRGB for windowed swap chains. This flag will take effect only when the driver exposes D3DCAPS3_LINEAR_TO_SRGB_PRESENTATION. For more information about gamma correction, see Gamma.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_DEVICELOST | The device has been lost but cannot be reset at this time. Therefore, rendering is not possible.
D3DERR_DRIVERINTERNALERROR

Internal driver error. Applications should generally shut down when receiving this error. For more information, see Driver Internal Errors.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The IDirect3DDevice9::Present method is a shortcut to the IDirect3DSwapChain9::Present. The swap chain method has been updated to take a flag allowing the application to request that the method return immediately when the driver reports that it cannot schedule a presentation.

If necessary, a stretch operation is applied to transfer the pixels within the source rectangle to the destination rectangle in the client area of the target window.

IDirect3DSwapChain9::Present will fail if called between IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene pairs unless the render target is not the current render target (such as the back buffer you get from creating an additional swap chain). This is a new behavior for DirectX 9.0.

See Also

IDirect3DDevice9::Reset


IDirect3DTexture9 Interface

Applications use the methods of the IDirect3DTexture9 interface to manipulate a texture resource.

IDirect3DTexture9 Members

AddDirtyRect | Adds a dirty region to a texture resource.
FreePrivateData | Frees the specified private data associated with this resource.
GenerateMipSubLevels | Generate mipmap sublevels.
GetAutoGenFilterType | Get the filter type that is used for automatically generated mipmap sublevels.
GetDevice | Retrieves the device associated with a resource.
GetLevelCount | Returns the number of texture levels in a multilevel texture.
GetLevelDesc | Retrieves a level description of a texture resource.
GetLOD | Returns a value clamped to the maximum level of detail (LOD) set for a managed texture (this method is not supported for an unmanaged texture).
GetPriority | Retrieves the priority for this resource.
GetPrivateData | Copies the private data associated with the resource to a provided buffer.
GetSurfaceLevel | Retrieves the specified texture surface level.
GetType | Returns the type of the resource.
LockRect | Locks a rectangle on a texture resource.
PreLoad | Preloads a managed resource.
SetAutoGenFilterType | Set the filter type that is used for automatically generated mipmap sublevels.
SetLOD | Sets the most detailed LOD for a managed texture.
SetPriority | Assigns the resource-management priority for this resource.
SetPrivateData | Associates data with the resource that is intended for use by the application, not by Microsoft Direct3D. Data is passed by value, and multiple sets of data can be associated with a single resource.
UnlockRect | Unlocks a rectangle on a texture resource.

Remarks

The IDirect3DTexture9 interface can be obtained by calling the IDirect3DDevice9::CreateTexture method or one of the D3DXCreateTexture xxx functions.

This interface inherits additional functionality from the IDirect3DBaseTexture9 interface.

This interface, like all Component Object Model (COM) interfaces, inherits from the IUnknown interface.

The LPDIRECT3DTEXTURE9 and PDIRECT3DTEXTURE9 types are defined as pointers to the IDirect3DTexture9 interface.

typedef struct IDirect3DTexture9 *LPDIRECT3DTEXTURE9, *PDIRECT3DTEXTURE9;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IDirect3DBaseTexture9
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::CreateTexture, D3DXCreateTexture, D3DXCreateTextureFromFile, D3DXCreateTextureFromFileEx, D3DXCreateTextureFromFileInMemory, D3DXCreateTextureFromFileInMemoryEx, D3DXCreateTextureFromResource, D3DXCreateTextureFromResourceEx


IDirect3DTexture9::AddDirtyRect Method

Adds a dirty region to a texture resource.

Syntax

HRESULT AddDirtyRect(

    CONST RECT *pDirtyRect
);

Parameters

pDirtyRect
[in] Pointer to a RECT World Wide Web link structure, specifying the dirty region to add. Specifying NULL expands the dirty region to cover the entire texture.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For performance reasons, dirty regions are only recorded for level zero of a texture. For sublevels, it is assumed that the corresponding (scaled) rectangle or box is also dirty. Dirty regions are automatically recorded when LockRect or IDirect3DVolumeTexture9::LockBox is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. Also, the destination surface of IDirect3DDevice9::UpdateSurface is marked dirty.

Applications can optimize what subset of a resource is copied by specifying dirty regions on the resource.


IDirect3DTexture9::GetLevelDesc Method

Retrieves a level description of a texture resource.

Syntax

HRESULT GetLevelDesc(

    UINT Level,
    D3DSURFACE_DESC *pDesc
);

Parameters

Level
[in] Identifies a level of the texture resource. This method returns a surface description for the level specified by this parameter.
pDesc
[out] Pointer to a D3DSURFACE_DESC structure, describing the returned level.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if one of the arguments is invalid.


IDirect3DTexture9::GetSurfaceLevel Method

Retrieves the specified texture surface level.

Syntax

HRESULT GetSurfaceLevel(

    UINT Level,
    IDirect3DSurface9 **ppSurfaceLevel
);

Parameters

Level
[in] Identifies a level of the texture resource. This method returns a surface for the level specified by this parameter. The top-level surface is denoted by 0.
ppSurfaceLevel
[out, retval] Address of a pointer to an IDirect3DSurface9 interface, representing the returned surface.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DSurface9 interface. Failure to call IUnknown::Release when finished using this IDirect3DSurface9 interface results in a memory leak.


IDirect3DTexture9::LockRect Method

Locks a rectangle on a texture resource.

Syntax

HRESULT LockRect(

    UINT Level,
    D3DLOCKED_RECT *pLockedRect,
    CONST RECT *pRect,
    DWORD Flags
);

Parameters

Level
[in] Specifies the level of the texture resource to lock.
pLockedRect
[out] Pointer to a D3DLOCKED_RECT structure, describing the locked region.
pRect
[in] Pointer to a rectangle to lock. Specified by a pointer to a RECT structure. Specifying NULL for this parameter expands the dirty region to cover the entire texture.
Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY

You may not specify a subrect when using D3DLOCK_DISCARD. For a description of the flags, see D3DLOCK.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Textures created with D3DPOOL_DEFAULT are not lockable. Textures created in video memory are lockable when created with USAGE_DYNAMIC.

For performance reasons, dirty regions are recorded only for level zero of a texture. Dirty regions are automatically recorded when IDirect3DTexture9::LockRect is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. See IDirect3DDevice9::UpdateTexture for more information.

The only lockable format for a depth-stencil texture is D3DLOCK_D16_LOCKABLE.

Video memory textures cannot be locked, but must be modified by calling IDirect3DDevice9::UpdateSurface or IDirect3DDevice9::UpdateTexture. There are exceptions for some proprietary driver pixel formats that Microsoft DirectX 9.0 does not recognize. These can be locked.

This method cannot retrieve data from a texture resource created with D3DUSAGE_RENDERTARGET because such a texture must be assigned to D3DPOOL_DEFAULT memory and is therefore not lockable. In this case, use instead IDirect3DDevice9::GetRenderTargetData to copy texture data from device memory to system memory.

See Also

IDirect3DTexture9::UnlockRect, IDirect3DDevice9::UpdateTexture, IDirect3DDevice9::GetRenderTargetData


IDirect3DTexture9::UnlockRect Method

Unlocks a rectangle on a texture resource.

Syntax

HRESULT UnlockRect(

    UINT Level
);

Parameters

Level
[in] Specifies the level of the texture resource to unlock.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DTexture9::LockRect


IDirect3DVertexBuffer9 Interface

Applications use the methods of the IDirect3DVertexBuffer9 interface to manipulate vertex buffer resources.

IDirect3DVertexBuffer9 Members

FreePrivateData | Frees the specified private data associated with this resource.
GetDesc | Retrieves a description of the vertex buffer resource.
GetDevice | Retrieves the device associated with a resource.
GetPriority | Retrieves the priority for this resource.
GetPrivateData | Copies the private data associated with the resource to a provided buffer.
GetType | Returns the type of the resource.
Lock | Locks a range of vertex data and obtains a pointer to the vertex buffer memory.
PreLoad | Preloads a managed resource.
SetPriority | Assigns the resource-management priority for this resource.
SetPrivateData | Associates data with the resource that is intended for use by the application, not by Microsoft Direct3D. Data is passed by value, and multiple sets of data can be associated with a single resource.
Unlock | Unlocks vertex data.

Remarks

The IDirect3DVertexBuffer9 interface is obtained by calling the IDirect3DDevice9::CreateVertexBuffer method.

This interface inherits additional functionality from the IDirect3DResource9 interface.

This interface, like all Component Object Model (COM) interfaces, inherits from the IUnknown interface.

The LPDIRECT3DVERTEXBUFFER9 and PDIRECT3DVERTEXBUFFER9 types are defined as pointers to the IDirect3DVertexBuffer9 interface.

typedef struct IDirect3DVertexBuffer9 *LPDIRECT3DVERTEXBUFFER9, *PDIRECT3DVERTEXBUFFER9;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IDirect3DResource9
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::CreateVertexBuffer, Vertex Buffers


IDirect3DVertexBuffer9::GetDesc Method

Retrieves a description of the vertex buffer resource.

Syntax

HRESULT GetDesc(

    D3DVERTEXBUFFER_DESC *pDesc
);

Parameters

pDesc
[out] Pointer to a D3DVERTEXBUFFER_DESC structure, describing the returned vertex buffer.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the argument is invalid.


IDirect3DVertexBuffer9::Lock Method

Locks a range of vertex data and obtains a pointer to the vertex buffer memory.

Syntax

HRESULT Lock(

    UINT OffsetToLock,
    UINT SizeToLock,
    VOID **ppbData,
    DWORD Flags
);

Parameters

OffsetToLock
[in] Offset into the vertex data to lock, in bytes. To lock the entire vertex buffer, specify 0 for both parameters, SizeToLock and OffsetToLock.
SizeToLock
[in] Size of the vertex data to lock, in bytes. To lock the entire vertex buffer, specify 0 for both parameters, SizeToLock and OffsetToLock.
ppbData
[out] VOID* pointer to a memory buffer containing the returned vertex data.
Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY
  • D3DLOCK_NOOVERWRITE

For a description of the flags, see D3DLOCK.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When working with vertex buffers, you are allowed to make multiple lock calls; however, you must ensure that the number of lock calls match the number of unlock calls. DrawPrimitive calls will not succeed with any outstanding lock count on any currently set vertex buffer.

The D3DLOCK_DISCARD and D3DLOCK_NOOVERWRITE flags are valid only on buffers created with D3DUSAGE_DYNAMIC.

For information about using D3DLOCK_DISCARD or D3DLOCK_NOOVERWRITE with IDirect3DVertexBuffer9::Lock, see Using Dynamic Vertex and Index Buffers.

See Also

IDirect3DVertexBuffer9::Unlock


IDirect3DVertexBuffer9::Unlock Method

Unlocks vertex data.

Syntax

HRESULT Unlock(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DVertexBuffer9::Lock


IDirect3DVertexDeclaration9 Interface

Applications use the methods of the IDirect3DVertexDeclaration9 interface to encapsulate the vertex shader declaration.

IDirect3DVertexDeclaration9 Members

GetDeclaration | Gets the vertex shader declaration.
GetDevice | Gets the current device.

Remarks

A vertex shader declaration is made up of an array of vertex elements.

The LPDIRECT3DVERTEXDECLARATION9 and PDIRECT3DVERTEXDECLARATION9 types are defined as pointers to the IDirect3DVertexDeclaration9 interface.

typedef struct IDirect3DVertexDeclaration9 *LPDIRECT3DVERTEXDECLARATION9, *PDIRECT3DVERTEXDECLARATION9;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98


IDirect3DVertexDeclaration9::GetDeclaration Method

Gets the vertex shader declaration.

Syntax

HRESULT GetDeclaration(

    D3DVERTEXELEMENT9* pDecl,
    UINT* pNumElements
);

Parameters

pDecl
[in, out] Array of vertex elements that make up a vertex shader declaration. The application needs to allocate enough room for this. The vertex element array ends with the D3DDECL_END macro.
pNumElements
[in, out] Number of elements in the array. The application needs to allocate enough room for this.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be:

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The number of elements, pNumElements, includes the D3DDECL_END macro, which ends the declaration. So the element count is actually one higher than the number of valid vertex elements.

Here's an example that will return the vertex declaration array of up to 256 elements:

// assumes a valid pointer to a vertex declaration object
D3DVERTEXELEMENT9 decl[256];
UINT numElements;
HRESULT hr = m_pVertexDeclaration->GetDeclaration( decl, &numElements);


IDirect3DVertexDeclaration9::GetDevice Method

Gets the current device.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[out, retval] Pointer to the IDirect3DDevice9 interface that is returned.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be:

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


IDirect3DVertexShader9 Interface

Applications use the methods of the IDirect3DVertexShader9 interface to encapsulate the functionality of a vertex shader.

IDirect3DVertexShader9 Members

GetDevice | Gets the device.
GetFunction | Gets a pointer to the shader data.

Remarks

The LPDIRECT3DVERTEXSHADER9 and PDIRECT3DVERTEXSHADER9 types are defined as pointers to the IDirect3DVertexShader9 interface.

typedef struct IDirect3DVertexShader9 *LPDIRECT3DVERTEXSHADER9, *PDIRECT3DVERTEXSHADER9;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98


IDirect3DVertexShader9::GetDevice Method

Gets the device.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[out, retval] Pointer to the IDirect3DDevice9 interface that is returned.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


IDirect3DVertexShader9::GetFunction Method

Gets a pointer to the shader data.

Syntax

HRESULT GetFunction(

    void* pData,
    UINT* pSizeOfData
);

Parameters

pData
[in, out] Pointer to a buffer that contains the shader data. The application needs to allocate enough room for this.
pSizeOfData
[in, out] Size of the data, in bytes. To get the buffer size that is needed to retrieve the data, set pData = NULL when calling GetFunction. Then call GetFunction with the returned size, to get the buffer data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


IDirect3DVolume9 Interface

Applications use the methods of the IDirect3DVolume9 interface to manipulate volume resources.

IDirect3DVolume9 Members

FreePrivateData | Frees the specified private data associated with this volume.
GetContainer | Provides access to the parent volume texture object, if this surface is a child level of a volume texture.
GetDesc | Retrieves a description of the volume.
GetDevice | Retrieves the device associated with a volume.
GetPrivateData | Copies the private data associated with the volume to a provided buffer.
LockBox | Locks a box on a volume resource.
SetPrivateData | Associates data with the volume that is intended for use by the application, not by Microsoft Direct3D.
UnlockBox | Unlocks a box on a volume resource.

Remarks

The IDirect3DVolume9 interface is obtained by calling the IDirect3DVolumeTexture9::GetVolumeLevel method.

This interface, like all Component Object Model (COM) interfaces, inherits from the IUnknown interface.

The LPDIRECT3DVOLUME9 and PDIRECT3DVOLUME9 types are defined as pointers to the IDirect3DVolume9 interface.

typedef struct IDirect3DVolume9 *LPDIRECT3DVOLUME9, *PDIRECT3DVOLUME9;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98


IDirect3DVolume9::FreePrivateData Method

Frees the specified private data associated with this volume.

Syntax

HRESULT FreePrivateData(

    REFGUID refguid
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to free.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

Microsoft Direct3D calls this method automatically when a volume is released.

See Also

IDirect3DVolume9::GetPrivateData, IDirect3DVolume9::SetPrivateData


IDirect3DVolume9::GetContainer Method

Provides access to the parent volume texture object, if this surface is a child level of a volume texture.

Syntax

HRESULT GetContainer(

    REFIID riid,
    void **ppContainer
);

Parameters

riid
[in] Reference identifier of the volume being requested.
ppContainer
[out, retval] Address of a pointer to fill with the container pointer, if the query succeeds.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the call succeeds, the reference count of the container is increased by one.

Here's an example getting the parent volume texture of a volume texture.

// Assumes pSurface is a valid IDirect3DVolume9 pointer
void *pContainer = NULL;
IDirect3DVolumeTexture9 *pVolumeTexture = NULL;
HRESULT hr = pVolume->GetContainer(IID_IDirect3DVolumeTexture9, &pContainer);
if (SUCCEEDED(hr) && pContainer)
{
    pVolumeTexture = (IDirect3DVolumeTexture9 *)pContainer;


IDirect3DVolume9::GetDesc Method

Retrieves a description of the volume.

Syntax

HRESULT GetDesc(

    D3DVOLUME_DESC *pDesc
);

Parameters

pDesc
[out] Pointer to a D3DVOLUME_DESC structure, describing the volume.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the argument is invalid.


IDirect3DVolume9::GetDevice Method

Retrieves the device associated with a volume.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface to fill with the device pointer, if the query succeeds.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method allows navigation to the owning device object.

Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Failure to call IUnknown::Release when finished using this IDirect3DDevice9 interface results in a memory leak.


IDirect3DVolume9::GetPrivateData Method

Copies the private data associated with the volume to a provided buffer.

Syntax

HRESULT GetPrivateData(

    REFGUID refguid,
    void *pData,
    DWORD *pSizeOfData
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to retrieve.
pData
[in, out] Pointer to a previously allocated buffer to fill with the requested private data if the call succeeds. The application calling this method is responsible for allocating and releasing this buffer. If this parameter is NULL, this method will return the buffer size in pSizeOfData.
pSizeOfData
[in, out] Pointer to the size of the buffer at pData, in bytes. If this value is less than the actual size of the private data, such as 0, the method sets this parameter to the required buffer size, and the method returns D3DERR_MOREDATA.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_MOREDATA | There is more data available than the specified buffer size can hold.
D3DERR_NOTFOUND | The requested item was not found.

See Also

IDirect3DVolume9::FreePrivateData, IDirect3DVolume9::SetPrivateData


IDirect3DVolume9::LockBox Method

Locks a box on a volume resource.

Syntax

HRESULT LockBox(

    D3DLOCKED_BOX *pLockedVolume,
    const D3DBOX *pBox,
    DWORD Flags
);

Parameters

pLockedVolume
[out] Pointer to a D3DLOCKED_BOX structure, describing the locked region.
pBox
[in] Pointer to a box to lock. Specified by a pointer to a D3DBOX structure. Specifying NULL for this parameter locks the entire volume.
Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY

For a description of the flags, see D3DLOCK.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For performance reasons, dirty regions are only recorded for level zero of a texture. Dirty regions are automatically recorded when IDirect3DVolume9::LockBox is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. See IDirect3DDevice9::UpdateTexture for more information.

See Also

IDirect3DVolume9::UnlockBox


IDirect3DVolume9::SetPrivateData Method

Associates data with the volume that is intended for use by the application, not by Microsoft Direct3D.

Syntax

HRESULT SetPrivateData(

    REFGUID refguid,
    const void *pData,
    DWORD SizeOfData,
    DWORD Flags
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to set.
pData
[in] Pointer to a buffer that contains the data to associate with the volume.
SizeOfData
[in] Size of the buffer at pData in bytes.
Flags
[in] Value that describes the type of data being passed, or indicates to the application that the data should be invalidated when the resource changes.
(none)
If no flags are specified, Direct3D allocates memory to hold the data within the buffer and copies the data into the new buffer. The buffer allocated by Direct3D is automatically freed, as appropriate.
D3DSPD_IUNKNOWN
The data at pData is a pointer to an IUnknown interface. SizeOfData must be set to the size of a pointer to an IUnknown interface, sizeof(IUnknown*). Direct3D automatically calls IUnknown::AddRef through pData and IUnknown::Release when the private data is destroyed. Private data will be destroyed by a subsequent call to IDirect3DVolume9::SetPrivateData with the same globally unique identifier (GUID), a subsequent call to IDirect3DVolume9::FreePrivateData, or when the IDirect3D9 object is released. For more information, see Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Direct3D does not manage the memory at pData. If this buffer was dynamically allocated, it is the calling application's responsibility to free the memory.

Data is passed by value, and multiple sets of data can be associated with a single volume.

See Also

IDirect3DVolume9::FreePrivateData, IDirect3DVolume9::GetPrivateData


IDirect3DVolume9::UnlockBox Method

Unlocks a box on a volume resource.

Syntax

HRESULT UnlockBox(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DVolume9::LockBox


IDirect3DVolumeTexture9 Interface

Applications use the methods of the IDirect3DVolumeTexture9 interface to manipulate a volume texture resource.

IDirect3DVolumeTexture9 Members

AddDirtyBox | Adds a dirty region to a volume texture resource.
FreePrivateData | Frees the specified private data associated with this resource.
GenerateMipSubLevels | Generate mipmap sublevels.
GetAutoGenFilterType | Get the filter type that is used for automatically generated mipmap sublevels.
GetDevice | Retrieves the device associated with a resource.
GetLevelCount | Returns the number of texture levels in a multilevel texture.
GetLevelDesc | Retrieves a level description of a volume texture resource.
GetLOD | Returns a value clamped to the maximum level of detail (LOD) set for a managed texture (this method is not supported for an unmanaged texture).
GetPriority | Retrieves the priority for this resource.
GetPrivateData | Copies the private data associated with the resource to a provided buffer.
GetType | Returns the type of the resource.
GetVolumeLevel | Retrieves the specified volume texture level.
LockBox | Locks a box on a volume texture resource.
PreLoad | Preloads a managed resource.
SetAutoGenFilterType | Set the filter type that is used for automatically generated mipmap sublevels.
SetLOD | Sets the most detailed LOD for a managed texture.
SetPriority | Assigns the resource-management priority for this resource.
SetPrivateData | Associates data with the resource that is intended for use by the application, not by Microsoft Direct3D. Data is passed by value, and multiple sets of data can be associated with a single resource.
UnlockBox | Unlocks a box on a volume texture resource.

Remarks

The IDirect3DVolumeTexture9 interface can be obtained by calling the IDirect3DDevice9::CreateVolumeTexture method or one of the D3DXCreateVolumeTexture xxx functions.

This interface inherits additional functionality from the IDirect3DBaseTexture9 interface.

This interface, like all Component Object Model (COM) interfaces, inherits from the IUnknown interface.

The LPDIRECT3DVOLUMETEXTURE9 and PDIRECT3DVOLUMETEXTURE9 types are defined as pointers to the IDirect3DVolumeTexture9 interface.

typedef struct IDirect3DVolumeTexture9 *LPDIRECT3DVOLUMETEXTURE9, *PDIRECT3DVOLUMETEXTURE9;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IDirect3DBaseTexture9
Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::CreateVolumeTexture, D3DXCreateVolumeTexture, D3DXCreateVolumeTextureFromFile, D3DXCreateVolumeTextureFromFileEx, D3DXCreateVolumeTextureFromFileInMemory, D3DXCreateVolumeTextureFromFileInMemoryEx, D3DXCreateVolumeTextureFromResource, D3DXCreateVolumeTextureFromResourceEx


IDirect3DVolumeTexture9::AddDirtyBox Method

Adds a dirty region to a volume texture resource.

Syntax

HRESULT AddDirtyBox(

    CONST D3DBOX *pDirtyBox
);

Parameters

pDirtyBox
[in] Pointer to a D3DBOX structure, specifying the dirty region to add. Specifying NULL expands the dirty region to cover the entire volume texture.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For performance reasons, dirty regions are only recorded for level zero of a texture. For sublevels, it is assumed that the corresponding (scaled) rectangle or box is also dirty. Dirty regions are automatically recorded when LockRect or IDirect3DVolumeTexture9::LockBox is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. Also, the destination surface of IDirect3DDevice9::UpdateSurface is marked dirty.

Applications can optimize what subset of a resource is copied by specifying boxes on the resource. However, the dirty regions may be expanded to optimize alignment.


IDirect3DVolumeTexture9::GetLevelDesc Method

Retrieves a level description of a volume texture resource.

Syntax

HRESULT GetLevelDesc(

    UINT Level,
    D3DVOLUME_DESC *pDesc
);

Parameters

Level
[in] Identifies a level of the volume texture resource. This method returns a volume description for the level specified by this parameter.
pDesc
[out] Pointer to a D3DVOLUME_DESC structure, describing the returned volume texture level.

Return Value

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if one or more of the arguments are invalid.


IDirect3DVolumeTexture9::GetVolumeLevel Method

Retrieves the specified volume texture level.

Syntax

HRESULT GetVolumeLevel(

    UINT Level,
    IDirect3DVolume9 **ppVolumeLevel
);

Parameters

Level
[in] Identifies a level of the volume texture resource. This method returns a volume for the level specified by this parameter.
ppVolumeLevel
[out, retval] Address of a pointer to an IDirect3DVolume9 interface, representing the returned volume level.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DVolume9 interface. Failure to call IUnknown::Release when finished using this IDirect3DVolume9 interface results in a memory leak.


IDirect3DVolumeTexture9::LockBox Method

Locks a box on a volume texture resource.

Syntax

HRESULT LockBox(

    UINT Level,
    D3DLOCKED_BOX *pLockedVolume,
    const D3DBOX *pBox,
    DWORD Flags
);

Parameters

Level
[in] Specifies the level of the volume texture resource to lock.
pLockedVolume
[out] Pointer to a D3DLOCKED_BOX structure, describing the locked region.
pBox
[in] Pointer to the volume to lock. This parameter is specified by a pointer to a D3DBOX structure. Specifying NULL for this parameter locks the entire volume level.
Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY

For a description of the flags, see D3DLOCK.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For performance reasons, dirty regions are only recorded for level zero of a texture. Dirty regions are automatically recorded when IDirect3DVolumeTexture9::LockBox is called without D3DLOCK_NO_DIRTY_UPDATE or D3DLOCK_READONLY. For more information, see IDirect3DDevice9::UpdateTexture.

See Also

IDirect3DVolumeTexture9::UnlockBox


IDirect3DVolumeTexture9::UnlockBox Method

Unlocks a box on a volume texture resource.

Syntax

HRESULT UnlockBox(

    UINT Level
);

Parameters

Level
[in] Specifies the level of the volume texture resource to unlock.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

IDirect3DVolumeTexture9::LockBox


Functions
Microsoft DirectX 9.0 SDK Update (October 2004)

Functions

This section contains reference information for the functions that you need to use when you work with Microsoft Direct3D. The following functions are implemented:

  • Direct3DCreate9
  • D3DPERF_BeginEvent
  • D3DPERF_EndEvent
  • D3DPERF_SetMarker
  • D3DPERF_SetRegion
  • D3DPERF_QueryRepeatFrame
  • D3DPERF_SetOptions
  • D3DPERF_GetStatus


Direct3DCreate9 Function

Create a IDirect3D9 object and returns an interace to it.

Syntax

IDirect3D9 *WINAPI Direct3DCreate9(

    UINT SDKVersion
);

Parameters

SDKVersion
The value of this parameter should be D3D_SDK_VERSION. See Remarks.

Return Value

If successful, this function returns a pointer to an IDirect3D9 interface; otherwise, a NULL pointer is returned.

Remarks

The Microsoft Direct3D object is the first object that your application creates and the last object that your application releases. Functions for enumerating and retrieving capabilities of a Direct3D device are accessible through the Direct3D object. This enables applications to select devices without creating them.

Create a IDirect3D9 object as shown here:

LPDIRECT3D9 g_pD3D = NULL;

    if( NULL == (g_pD3D = Direct3DCreate9(D3D_SDK_VERSION)))
        return E_FAIL;

A IDirect3D9 interface supports enumeration of active display adapters and allows the creation of IDirect3DDevice9 objects. If the user dynamically adds adapters (either by adding devices to the desktop, or by hot-docking a laptop), those devices will not be included in the enumeration. Creating a new IDirect3D9 interface will expose the new devices.

D3D_SDK_VERSION is passed to this function to ensure that the header files against which an application is compiled match the version of the runtime dynamic-link library (DLL)'s that are installed on the machine. D3D_SDK_VERSION is only changed in the runtime when a header change (or other code change) would require an application to be rebuilt. If this function fails, it indicates that the header file version does not match the runtime DLL version. See DirectX Version Checking for help checking the version of the runtime that is installed on your machine.

Function Information

Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98


D3DPERF_BeginEvent Function

Specifies to a performance profiler (such as PIX) that a user-defined event is beginning.

Syntax

int WINAPI D3DPERF_BeginEvent(

    D3DCOLOR col,
    LPCWSTR wszName
);

Parameters

col
Color that may be used by the profiler to show a graphical representation of the event.
wszName
Name of the event.

Return Value

The level of the hierarchy that this event is starting in. If an error occurs, the return value will be negative.

Remarks

User-defined events group together other events in a way that is meaningful to the application so they can be better represented in performance profiling tools. For example, a "Draw Spaceship" event might bracket a number of Microsoft Direct3D calls that handle drawing a spaceship in a game. Events can be nested.

Each D3DPERF_BeginEvent call should have a matching D3DPERF_EndEvent call. Instantaneous events (which do not bracket other events) should be labeled using D3DPERF_SetMarker rather than using D3DPERF_BeginEvent and D3DPERF_EndEvent.

Function Information

Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

Gathering Data in the PIX Basic View


D3DPERF_EndEvent Function

Specifies to a performance profiler (such as PIX) that a user-defined event (that begins with D3DPERF_BeginEvent) is ending.

Syntax

int WINAPI D3DPERF_EndEvent(VOID);

Return Value

The level of the hierarchy in which the event is ending. If an error occurs, this value will be negative.

Function Information

Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

Gathering Data in the PIX Basic View


D3DPERF_SetMarker Function

Specifies to a performance profiler (such as PIX) that an instantaneous user-defined event is occurring.

Syntax

void WINAPI D3DPERF_SetMarker(

    D3DCOLOR col,
    LPCWSTR wszName
);

Parameters

col
A color that may be used by the profiler to show a graphical representation of the event.
wszName
The name of the event.

Return Value

None.

Remarks

Instantaneous user events do not bracket or group other events. For example, when the user fires a weapon in a game, a "Shot Fired" event could be created by a D3DPERF_SetMarker call. To group together a number of events under one user-defined name, use D3DPERF_BeginEvent and D3DPERF_EndEvent rather than D3DPERF_SetMarker.

Function Information

Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

Gathering Data in the PIX Basic View


D3DPERF_SetRegion Function

Specifies to a performance profiler (such as PIX) that subsequent frames should be marked with the specified color and name. This function is not currently supported by PIX.

Syntax

void WINAPI D3DPERF_SetRegion(

    D3DCOLOR col,
    LPCWSTR wszName
);

Parameters

col
A color that may be used by the profiler to show a graphical representation of the event.
wszName
The name of the region.

Return Value

None

Remarks

An application can use color to mark each level of a game as a different region in the graphical output.

Function Information

Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

Gathering Data in the PIX Basic View


D3DPERF_QueryRepeatFrame Function

Determine if a performance profiler (such as PIX) is requesting that the current frame be resubmitted to Microsoft Direct3D for performance analysis. The function should be called immediately after IDirect3DDevice9::Present is called. This function is not currently supported by PIX.

Syntax

bool WINAPI D3DPERF_QueryRepeatFrame(VOID);

Return Value

If the return value is TRUE, the caller should repeat the same sequence of calls. If FALSE, the caller should continue.

Function Information

Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

Gathering Data in the PIX Basic View


D3DPERF_SetOptions Function

Specifies how a performance profiler (such as PIX) should operate on the current program. This function is not currently supported by PIX.

Syntax

void WINAPI D3DPERF_SetOptions(

    DWORD dwOptions
);

Parameters

dwOptions
Specifies how a performance profiler should operate on the current program. If the value is 1, the current program does not give a profiler permission to perform instrumented profiling.

Return Value

None

Function Information

Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

Gathering Data in the PIX Basic View


D3DPERF_GetStatus Function

Determine the current state of a performance profiler (such as PIX). This function is not currently supported by PIX for PIX.

Syntax

DWORD WINAPI D3DPERF_GetStatus(VOID);

Return Value

None.

Function Information

Header | d3d9.h
Import library | d3d9.lib
Minimum operating systems | Windows 98

See Also

Gathering Data in the PIX Basic View


Macros
Microsoft DirectX 9.0 SDK Update (October 2004)

Macros

This section contains reference information for the macros provided by Microsoft Direct3D.

  • D3DCLIPPLANEn
  • D3DCOLOR_ARGB
  • D3DCOLOR_AYUV
  • D3DCOLOR_COLORVALUE
  • D3DCOLOR_RGBA
  • D3DCOLOR_XRGB
  • D3DFVF_TEXCOORDSIZEn
  • D3DTS_WORLD
  • D3DTS_WORLDMATRIX
  • D3DTS_WORLDn


D3DCLIPPLANEn Macro

Defines bit patterns that enable user-defined clipping planes. These macros are defined as a convenience when setting values for the D3DRS_CLIPPLANEENABLE render state.

Syntax

#define D3DCLIPPLANE0 (1 << 0)
#define D3DCLIPPLANE1 (1 << 1)
#define D3DCLIPPLANE2 (1 << 2)
#define D3DCLIPPLANE3 (1 << 3)
#define D3DCLIPPLANE4 (1 << 4)
#define D3DCLIPPLANE5 (1 << 5)

Remarks

User-defined clipping planes are enabled when the value set in the D3DRS_CLIPPLANEENABLE render state contains one or more set bits (that is, is not 0). The value of the render-state is not important; the system does not interpret the value as a number. Rather, the value enables the clipping plane whose corresponding bit is set. Bit 0 controls the state of the first clipping plane (at index 0), bit 1 the second plane, and so on.

The bit patterns that these macros create can be combined by using a logical OR operation to simultaneously enable multiple clipping planes. Omitting one of these macros from the combination effectively disables the clipping plane at that index.

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98


D3DCOLOR_ARGB Macro

Initializes a color with the supplied alpha, red, green, and blue values.

Syntax

#define D3DCOLOR_ARGB(a,r,g,b) \
    ((D3DCOLOR)((((a)&0xff)<<24)|(((r)&0xff)<<16)|(((g)&0xff)<<8)|((b)&0xff)))

Parameters

a
Alpha component of the color. This value must be in the range 0 through 255.
r
Red component of the color. This value must be in the range 0 through 255.
g
Green component of the color. This value must be in the range 0 through 255.
b
Blue component of the color. This value must be in the range 0 through 255.

Return Value

Returns the D3DCOLOR value that corresponds to the supplied ARGB values.

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DCOLOR_RGBA, D3DCOLOR_XRGB


D3DCOLOR_AYUV Macro

Initializes a color using the (a,y,u,v) values.

Syntax

#define D3DCOLOR_AYUV(a,y,u,v) D3DCOLOR_ARGB(a,y,u,v)

Parameters

a
Alpha component of the color. This value must be in the range 0 through 255.
y
Luminance component of the color. This value must be in the range 0 through 255.
u
Blue brightness of the color. This value must be in the range 0 through 255.
v
Red brightness of the color. This value must be in the range 0 through 255.

Return Value

Returns the D3DCOLOR value that corresponds to the supplied (y,u,v) values.

Remarks

An RGB color can be reduced to 16 bits per pixel by conversion to luminance and color differences with the following equations:

y (luminance) = 0.299*red + 0.587*green + 0.114*blue
u = blue - luminance
v = red - luminance

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DCOLOR_ARGB, D3DCOLOR_XYUV


D3DCOLOR_COLORVALUE Macro

Initializes a color with the supplied red, green, blue, and alpha floating-point values.

Syntax

#define D3DCOLOR_COLORVALUE(r,g,b,a) \
    D3DCOLOR_RGBA((DWORD)((r)*255.f),(DWORD)((g)*255.f),(DWORD)((b)*255.f),(DWORD)((a)*255.f))

Parameters

r
Red component of the color. This value must be a floating-point value in the range 0.0 through 1.0.
g
Green component of the color. This value must be a floating-point value in the range 0.0 through 1.0.
b
Blue component of the color. This value must be a floating-point value in the range 0.0 through 1.0.
a
Alpha component of the color. This value must be a floating-point value in the range 0.0 through 1.0.

Return Value

Returns the D3DCOLOR value that corresponds to the supplied RGBA values.

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98


D3DCOLOR_RGBA Macro

Initializes a color with the supplied red, green, blue, and alpha values.

Syntax

#define D3DCOLOR_RGBA(r,g,b,a) D3DCOLOR_ARGB(a,r,g,b)

Parameters

r
Red component of the color. This value must be in the range 0 through 255.
g
Green component of the color. This value must be in the range 0 through 255.
b
Blue component of the color. This value must be in the range 0 through 255.
a
Alpha component of the color. This value must be in the range 0 through 255.

Return Value

Returns the D3DCOLOR value that corresponds to the supplied RGBA values.

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DCOLOR_ARGB, D3DCOLOR_XRGB


D3DCOLOR_XRGB Macro

Initializes a color with the supplied red, green, and blue values.

Syntax

#define D3DCOLOR_XRGB(r,g,b) D3DCOLOR_ARGB(0xff,r,g,b)

Parameters

r
Red component of the color. This value must be in the range 0 through 255.
g
Green component of the color. This value must be in the range 0 through 255.
b
Blue component of the color. This value must be in the range 0 through 255.

Return Value

Returns the D3DCOLOR value that corresponds to the supplied RGB values.

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DCOLOR_ARGB, D3DCOLOR_RGBA


D3DCOLOR_XYUV Macro

Initializes a color with the (y, u, v) values.

Syntax

#define D3DCOLOR_XYUV(y,u,v) D3DCOLOR_ARGB(0xff,y,u,v)

Parameters

y
Luminance component of the color. This value must be in the range 0 through 255.
u
Blue brightness of the color. This value must be in the range 0 through 255.
v
Red brightness of the color. This value must be in the range 0 through 255.

Return Value

Returns the D3DCOLOR value that corresponds to the supplied (y, u, v) values.

Remarks

An RGB color can be reduced to 16 bits per pixel by conversion to luminance and color differences with the following equations:

y (luminance) = 0.299*red + 0.587*green + 0.114*blue
u = blue - luminance
v = red - luminance

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DCOLOR_ARGB, D3DCOLOR_AYUV


D3DFVF_TEXCOORDSIZEn Macro

Constructs bit patterns that are used to identify texture coordinate formats within a flexible vertex format (FVF) description. The results of these macros can be combined within a FVF description by using the OR operator.

Syntax

#define D3DFVF_TEXCOORDSIZE1(CoordIndex) (D3DFVF_TEXTUREFORMAT1 << (CoordIndex*2 + 16))
#define D3DFVF_TEXCOORDSIZE2(CoordIndex) (D3DFVF_TEXTUREFORMAT2)
#define D3DFVF_TEXCOORDSIZE3(CoordIndex) (D3DFVF_TEXTUREFORMAT3 << (CoordIndex*2 + 16))
#define D3DFVF_TEXCOORDSIZE4(CoordIndex) (D3DFVF_TEXTUREFORMAT4 << (CoordIndex*2 + 16))

Parameters

CoordIndex
Value that identifies the texture coordinate set at which the texture coordinate size (1-, 2-, 3-, or 4-dimensional) applies.

Remarks

The D3DFVF_TEXCOORDSIZEn macros use the following constants.

#define D3DFVF_TEXTUREFORMAT1 3 // one floating point value
#define D3DFVF_TEXTUREFORMAT2 0 // two floating point values
#define D3DFVF_TEXTUREFORMAT3 1 // three floating point values
#define D3DFVF_TEXTUREFORMAT4 2 // four floating point values

The following FVF description identifies a vertex format that has a position; a normal; diffuse and specular colors; and two sets of texture coordinates. The first set of texture coordinates includes a single element, and the second set includes two elements:

DWORD dwFVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE |
              D3DFVF_SPECULAR | D3DFVF_TEX2 |
              D3DFVF_TEXCOORDSIZE1(0) |  // Uses 1-D texture coordinates for
                                         // texture coordinate set 1 (index 0).
              D3DFVF_TEXCOORDSIZE2(1);   // And 2-D texture coordinates for
                                         // texture coordinate set 2 (index 1).

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DFVF


D3DPS_VERSION Macro

Create a pixel shader version token.

Syntax

#define D3DPS_VERSION(_Major,_Minor)

Remarks

Version Numbers

The version number is a combination of the major version and the minor vertex shader version numbers. Valid numbers are shown in the table.

Major | Minor | Example
1 | 1 | D3DPS_VERSION(1,1)
1 | 2 | D3DPS_VERSION(1,2)
1 | 3 | D3DPS_VERSION(1,3)
1 | 4 | D3DPS_VERSION(1,4)
2 | 0 | D3DPS_VERSION(2,0)
3 | 0 | D3DPS_VERSION(3,0)

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98


D3DTS_WORLD Macro

Identifies the transformation matrix being set as the world transformation matrix.

Syntax

#define D3DTS_WORLD  D3DTS_WORLDMATRIX(0)

Remarks

This macro is provided to facilitate porting existing applications to Microsoft DirectX 9.0

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::SetTransform, D3DTS_WORLDMATRIX


D3DTS_WORLDMATRIX Macro

Maps indices in the range 0 through 255 to the corresponding transform states.

Syntax

#define D3DTS_WORLDMATRIX(index) (D3DTRANSFORMSTATETYPE)(index + 256)

Parameters

index
An index value in the range 0 through 255.

Remarks

Transform states in the range 256 through 511 are reserved to store up to 256 matrices that can be indexed using 8-bit indices.

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::SetTransform


D3DTS_WORLDn Macro

Identifies subsequent transformation matrices that can be used to blend vertices by using the corresponding matrix and a blending (beta) weight value specified in the vertex format.

Syntax

#define D3DTS_WORLD1 D3DTS_WORLDMATRIX(1)
#define D3DTS_WORLD2 D3DTS_WORLDMATRIX(2)
#define D3DTS_WORLD3 D3DTS_WORLDMATRIX(3)

Remarks

These macros are provided to facilitate porting existing applications to Microsoft DirectX 9.0.

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::SetTransform, D3DTS_WORLDMATRIX


D3DVS_VERSION Macro

Create a vertex shader version number token.

Syntax

#define D3DVS_VERSION(Major, Minor)

Remarks

Version Numbers

The version number is a combination of the major version and the minor vertex shader version numbers. Valid numbers are shown in the table.

Major | Minor | Example
1 | 1 | D3DVS_VERSION(1,1)
2 | 0 | D3DVS_VERSION(2,0)
3 | 0 | D3DVS_VERSION(3,0)

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98


Structures
Microsoft DirectX 9.0 SDK Update (October 2004)

Structures

This section contains information about the structures used with Microsoft Direct3D.

Structures

  • D3DADAPTER_IDENTIFIER9
  • D3DBOX
  • D3DCAPS9
  • D3DCLIPSTATUS9
  • D3DCOLORVALUE
  • D3DDEVICE_CREATION_PARAMETERS
  • D3DDEVINFO_D3D9BANDWIDTHTIMINGS
  • D3DDEVINFO_D3D9CACHEUTILIZATION
  • D3DDEVINFO_D3D9INTERFACETIMINGS
  • D3DDEVINFO_D3D9PIPELINETIMINGS
  • D3DDEVINFO_D3D9STAGETIMINGS
  • D3DDEVINFO_D3DVERTEXSTATS
  • D3DDEVINFO_RESOURCEMANAGER
  • D3DDEVINFO_VCACHE
  • D3DDISPLAYMODE
  • D3DGAMMARAMP
  • D3DINDEXBUFFER_DESC
  • D3DLIGHT9
  • D3DLOCKED_BOX
  • D3DLOCKED_RECT
  • D3DMATERIAL9
  • D3DMATRIX
  • D3DPRESENT_PARAMETERS
  • D3DPSHADERCAPS2_0
  • D3DRANGE
  • D3DRASTER_STATUS
  • D3DRECT
  • D3DRECTPATCH_INFO
  • D3DRESOURCESTATS
  • D3DSURFACE_DESC
  • D3DTRIPATCH_INFO
  • D3DVECTOR
  • D3DVERTEXBUFFER_DESC
  • D3DVERTEXELEMENT9
  • D3DVIEWPORT9
  • D3DVOLUME_DESC
  • D3DVSHADERCAPS2_0
  • D3DXF_FILELOADMEMORY
  • D3DXFILELOADRESOURCE
  • PALETTEENTRY
  • XFILECOMPRESSEDANIMATIONSET


D3DADAPTER_IDENTIFIER9 Structure

Contains information identifying the adapter.

Syntax

typedef struct _D3DADAPTER_IDENTIFIER9 {
    char Driver[MAX_DEVICE_IDENTIFIER_STRING];
    char Description[MAX_DEVICE_IDENTIFIER_STRING];
    char DeviceName[32];
    LARGE_INTEGER DriverVersion;
    DWORD DriverVersionLowPart;
    DWORD DriverVersionHighPart;
    DWORD VendorId;
    DWORD DeviceId;
    DWORD SubSysId;
    DWORD Revision;
    GUID DeviceIdentifier;
    DWORD WHQLLevel;
} D3DADAPTER_IDENTIFIER9;

Members

Driver
Used for presentation to the user. This should not be used to identify particular drivers, because many different strings might be associated with the same device and driver from different vendors.
Description
Used for presentation to the user.
DeviceName
Device name for Microsoft Windows Graphics Device Interface (GDI).
DriverVersion
Identify the version of the Microsoft Direct3D driver. It is legal to do less than and greater than comparisons on the 64-bit signed integer value. However, exercise caution if you use this element to identify problematic drivers. Instead, you should use DeviceIdentifier. See Remarks.
DriverVersionLowPart
Identify the version of the Direct3D driver. It is legal to do < and > comparisons on the 64-bit signed integer value. However, exercise caution if you use this element to identify problematic drivers. Instead, you should use DeviceIdentifier. See Remarks.
DriverVersionHighPart
Identify the version of the Direct3D driver. It is legal to do < and > comparisons on the 64-bit signed integer value. However, exercise caution if you use this element to identify problematic drivers. Instead, you should use DeviceIdentifier. See Remarks.
VendorId
Can be used to help identify a particular chip set. Query this member to identify the manufacturer. The value can be zero if unknown.
DeviceId
Can be used to help identify a particular chip set. Query this member to identify the type of chip set. The value can be zero if unknown.
SubSysId
Can be used to help identify a particular chip set. Query this member to identify the subsystem, typically the particular board. The value can be zero if unknown.
Revision
Can be used to help identify a particular chip set. Query this member to identify the revision level of the chip set. The value can be zero if unknown.
DeviceIdentifier
Can be queried to check changes in the driver and chip set. This globally unique identifier (GUID) is a unique identifier for the driver and chip set pair. Query this member to track changes to the driver and chip set in order to generate a new profile for the graphics subsystem. DeviceIdentifier can also be used to identify particular problematic drivers.
WHQLLevel

Used to determine the Windows Hardware Quality Labs (WHQL) validation level for this driver and device pair. The DWORD is a packed date structure defining the date of the release of the most recent WHQL test passed by the driver. It is legal to perform < and > operations on this value. The following illustrates the date format.

Bits
31-16 | The year, a decimal number from 1999 upwards.
15-8 | The month, a decimal number from 1 to 12.
7-0 | The day, a decimal number from 1 to 31.

The following values are also used.

0 | Not certified.
1 | WHQL validated, but no date information is available.

Remarks

The following pseudocode example illustrates the version format encoded in the DriverVersion, DriverVersionLowPart, and DriverVersionHighPart members.

Product = HIWORD(DriverVersion.HighPart)
Version = LOWORD(DriverVersion.HighPart)
SubVersion = HIWORD(DriverVersion.LowPart)
Build = LOWORD(DriverVersion.LowPart)

See the Microsoft Platform Software Development Kit (SDK) for more information about the HIWORD macro, the LOWORD macro, and the LARGE_INTEGER structure.

MAX_DEVICE_IDENTIFIER_STRING is a constant with the following definition.

#define MAX_DEVICE_IDENTIFIER_STRING        512

The VendorId, DeviceId, SubSysId, and Revision members can be used in tandem to identify particular chip sets. However, use these members with caution.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98


D3DBOX Structure

Defines a volume.

Syntax

typedef struct _D3DBOX {
    UINT Left;
    UINT Top;
    UINT Right;
    UINT Bottom;
    UINT Front;
    UINT Back;
} D3DBOX;

Members

Left
Position of the left side of the box on the x-axis.
Top
Position of the top of the box on the y-axis.
Right
Position of the right side of the box on the x-axis.
Bottom
Position of the bottom of the box on the y-axis.
Front
Position of the front of the box on the z-axis.
Back
Position of the back of the box on the z-axis.

Remarks

D3DBOX includes the left, top, and front edges; however, the right, bottom, and back edges are not included. For example, a box that is 100 units wide and begins at 0 (thus, including the points up to and including 99) would be expressed with a value of 0 for the Left member and a value of 100 for the Right member. Note that a value of 99 is not used for the Right member.

The restrictions on side ordering observed for D3DBOX are left to right, top to bottom, and front to back.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98


D3DCAPS9 Structure

Represents the capabilities of the hardware exposed through the Microsoft Direct3D object.

Syntax

typedef struct _D3DCAPS9 {
    D3DDEVTYPE DeviceType;
    UINT AdapterOrdinal;
    DWORD Caps;
    DWORD Caps2;
    DWORD Caps3;
    DWORD PresentationIntervals;
    DWORD CursorCaps;
    DWORD DevCaps;
    DWORD PrimitiveMiscCaps;
    DWORD RasterCaps;
    DWORD ZCmpCaps;
    DWORD SrcBlendCaps;
    DWORD DestBlendCaps;
    DWORD AlphaCmpCaps;
    DWORD ShadeCaps;
    DWORD TextureCaps;
    DWORD TextureFilterCaps;
    DWORD CubeTextureFilterCaps;
    DWORD VolumeTextureFilterCaps;
    DWORD TextureAddressCaps;
    DWORD VolumeTextureAddressCaps;
    DWORD LineCaps;
    DWORD MaxTextureWidth;
    DWORD MaxTextureHeight;
    DWORD MaxVolumeExtent;
    DWORD MaxTextureRepeat;
    DWORD MaxTextureAspectRatio;
    DWORD MaxAnisotropy;
    float MaxVertexW;
    float GuardBandLeft;
    float GuardBandTop;
    float GuardBandRight;
    float GuardBandBottom;
    float ExtentsAdjust;
    DWORD StencilCaps;
    DWORD FVFCaps;
    DWORD TextureOpCaps;
    DWORD MaxTextureBlendStages;
    DWORD MaxSimultaneousTextures;
    DWORD VertexProcessingCaps;
    DWORD MaxActiveLights;
    DWORD MaxUserClipPlanes;
    DWORD MaxVertexBlendMatrices;
    DWORD MaxVertexBlendMatrixIndex;
    float MaxPointSize;
    DWORD MaxPrimitiveCount;
    DWORD MaxVertexIndex;
    DWORD MaxStreams;
    DWORD MaxStreamStride;
    DWORD VertexShaderVersion;
    DWORD MaxVertexShaderConst;
    DWORD PixelShaderVersion;
    float PixelShader1xMaxValue;
    DWORD DevCaps2;
    float MaxNpatchTessellationLevel;
    UINT MasterAdapterOrdinal;
    UINT AdapterOrdinalInGroup;
    UINT NumberOfAdaptersInGroup;
    DWORD DeclTypes;
    DWORD NumSimultaneousRTs;
    DWORD StretchRectFilterCaps;
    D3DVSHADERCAPS2_0 VS20Caps;
    D3DPSHADERCAPS2_0 PS20Caps;
    DWORD VertexTextureFilterCaps;
    DWORD MaxVShaderInstructionsExecuted;
    DWORD MaxPShaderInstructionsExecuted;
    DWORD MaxVertexShader30InstructionSlots;
    DWORD MaxPixelShader30InstructionSlots;
    DWORD Reserved2;
    DWORD Reserved3;
} D3DCAPS9;

Members

DeviceType
Member of the D3DDEVTYPE enumerated type, which identifies what type of resources are used for processing vertices.
AdapterOrdinal
Adapter on which this Direct3D device was created. This ordinal is valid only to pass to methods of the IDirect3D9 interface that created this Direct3D device. The IDirect3D9 interface can always be retrieved by calling IDirect3DDevice9::GetDirect3D.
Caps

The following driver-specific capability.

D3DCAPS_READ_SCANLINE
Display hardware is capable of returning the current scan line.
Caps2

Driver-specific capabilities identified in D3DCAPS2.

Caps3

Driver-specific capabilities identified in D3DCAPS3.

PresentationIntervals

Bit mask of values representing what presentation swap intervals are available.

D3DPRESENT_INTERVAL_IMMEDIATE
The driver supports an immediate presentation swap interval.
D3DPRESENT_INTERVAL_ONE
The driver supports a presentation swap interval of every screen refresh.
D3DPRESENT_INTERVAL_TWO
The driver supports a presentation swap interval of every second screen refresh.
D3DPRESENT_INTERVAL_THREE
The driver supports a presentation swap interval of every third screen refresh.
D3DPRESENT_INTERVAL_FOUR
The driver supports a presentation swap interval of every fourth screen refresh.
CursorCaps

Bit mask indicating what hardware support is available for cursors. Microsoft DirectX 9.0 does not define alpha-blending cursor capabilities.

D3DCURSORCAPS_COLOR
A full-color cursor is supported in hardware. Specifically, this flag indicates that the driver supports at least a hardware color cursor in high-resolution modes (with scan lines greater than or equal to 400).
D3DCURSORCAPS_LOWRES
A full-color cursor is supported in hardware. Specifically, this flag indicates that the driver supports a hardware color cursor in both high-resolution and low-resolution modes (with scan lines less than 400).
DevCaps

Flags identifying the capabilities of the device.

D3DDEVCAPS_CANBLTSYSTONONLOCAL
Device supports blits from system-memory textures to nonlocal video-memory textures.
D3DDEVCAPS_CANRENDERAFTERFLIP
Device can queue rendering commands after a page flip. Applications do not change their behavior if this flag is set; this capability means that the device is relatively fast.
D3DDEVCAPS_DRAWPRIMITIVES2
Device can support at least a DirectX 5.0-compliant driver.
D3DDEVCAPS_DRAWPRIMITIVES2EX
Device can support at least a DirectX 7.0-compliant driver.
D3DDEVCAPS_DRAWPRIMTLVERTEX
Device exports an IDirect3DDevice9::DrawPrimitive-aware hardware abstraction layer (HAL).
D3DDEVCAPS_EXECUTESYSTEMMEMORY
Device can use execute buffers from system memory.
D3DDEVCAPS_EXECUTEVIDEOMEMORY
Device can use execute buffers from video memory.
D3DDEVCAPS_HWRASTERIZATION
Device has hardware acceleration for scene rasterization.
D3DDEVCAPS_HWTRANSFORMANDLIGHT
Device can support transformation and lighting in hardware.
D3DDEVCAPS_NPATCHES
Device supports N patches.
D3DDEVCAPS_PUREDEVICE
Device can support rasterization, transform, lighting, and shading in hardware.
D3DDEVCAPS_QUINTICRTPATCHES
Device supports quintic Bézier curves and B-splines.
D3DDEVCAPS_RTPATCHES
Device supports rectangular and triangular patches.
D3DDEVCAPS_RTPATCHHANDLEZERO
When this device capability is set, the hardware architecture does not require caching of any information, and uncached patches (handle zero) will be drawn as efficiently as cached ones. Note that setting D3DDEVCAPS_RTPATCHHANDLEZERO does not mean that a patch with handle zero can be drawn. A handle-zero patch can always be drawn whether this cap is set or not.
D3DDEVCAPS_SEPARATETEXTUREMEMORIES
Device is texturing from separate memory pools.
D3DDEVCAPS_TEXTURENONLOCALVIDMEM
Device can retrieve textures from non-local video memory.
D3DDEVCAPS_TEXTURESYSTEMMEMORY
Device can retrieve textures from system memory.
D3DDEVCAPS_TEXTUREVIDEOMEMORY
Device can retrieve textures from device memory.
D3DDEVCAPS_TLVERTEXSYSTEMMEMORY
Device can use buffers from system memory for transformed and lit vertices.
D3DDEVCAPS_TLVERTEXVIDEOMEMORY
Device can use buffers from video memory for transformed and lit vertices.
PrimitiveMiscCaps

Miscellaneous driver primitive capabilities. See D3DPMISCCAPS.

RasterCaps

Information on raster-drawing capabilities. This member can be one or more of the following flags.

D3DPRASTERCAPS_ANISOTROPY
Device supports anisotropic filtering.
D3DPRASTERCAPS_COLORPERSPECTIVE
Device iterates colors perspective correctly.
D3DPRASTERCAPS_DITHER
Device can dither to improve color resolution.
D3DPRASTERCAPS_DEPTHBIAS
Device supports legacy depth bias. For true depth bias, see RasterCaps .
D3DPRASTERCAPS_FOGRANGE
Device supports range-based fog. In range-based fog, the distance of an object from the viewer is used to compute fog effects, not the depth of the object (that is, the z-coordinate) in the scene.
D3DPRASTERCAPS_FOGTABLE
Device calculates the fog value by referring to a lookup table containing fog values that are indexed to the depth of a given pixel.
D3DPRASTERCAPS_FOGVERTEX
Device calculates the fog value during the lighting operation and interpolates the fog value during rasterization.
D3DPRASTERCAPS_MIPMAPLODBIAS
Device supports level of detail (LOD) bias adjustments. These bias adjustments enable an application to make a mipmap appear crisper or less sharp than it normally would. For more information about LOD bias in mipmaps, see D3DSAMP_MIPMAPLODBIAS.
D3DPRASTERCAPS_MULTISAMPLE_TOGGLE
Device supports toggling multisampling on and off between IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene (using D3DRS_MULTISAMPLEANTIALIAS).
D3DPRASTERCAPS_SCISSORTEST
Device supports scissor test. See Scissor Test.
D3DPRASTERCAPS_SLOPESCALEDEPTHBIAS
Device performs true slope-scale based depth bias. This is in contrast to the legacy style depth bias.
D3DPRASTERCAPS_WBUFFER
Device supports depth buffering using w.
D3DPRASTERCAPS_WFOG
Device supports w-based fog. W-based fog is used when a perspective projection matrix is specified, but affine projections still use z-based fog. The system considers a projection matrix that contains a nonzero value in the [3][4] element to be a perspective projection matrix.
D3DPRASTERCAPS_ZBUFFERLESSHSR
Device can perform hidden-surface removal (HSR) without requiring the application to sort polygons and without requiring the allocation of a depth-buffer. This leaves more video memory for textures. The method used to perform HSR is hardware-dependent and is transparent to the application.

Z-bufferless HSR is performed if no depth-buffer surface is associated with the rendering-target surface and the depth-buffer comparison test is enabled (that is, when the state value associated with the D3DRS_ZENABLE enumeration constant is set to TRUE).

D3DPRASTERCAPS_ZFOG
Device supports z-based fog.
D3DPRASTERCAPS_ZTEST
Device can perform z-test operations. This effectively renders a primitive and indicates whether any z pixels have been rendered.
ZCmpCaps

Z-buffer comparison capabilities. This member can be one or more of the following flags.

D3DPCMPCAPS_ALWAYS
Always pass the z-test.
D3DPCMPCAPS_EQUAL
Pass the z-test if the new z equals the current z.
D3DPCMPCAPS_GREATER
Pass the z-test if the new z is greater than the current z.
D3DPCMPCAPS_GREATEREQUAL
Pass the z-test if the new z is greater than or equal to the current z.
D3DPCMPCAPS_LESS
Pass the z-test if the new z is less than the current z.
D3DPCMPCAPS_LESSEQUAL
Pass the z-test if the new z is less than or equal to the current z.
D3DPCMPCAPS_NEVER
Always fail the z-test.
D3DPCMPCAPS_NOTEQUAL
Pass the z-test if the new z does not equal the current z.
SrcBlendCaps

Source-blending capabilities. This member can be one or more of the following flags. (The RGBA values of the source and destination are indicated by the subscripts s and d.)

D3DPBLENDCAPS_BLENDFACTOR
The driver supports both D3DBLEND_BLENDFACTOR and D3DBLEND_INVBLENDFACTOR. See D3DBLEND.
D3DPBLENDCAPS_BOTHINVSRCALPHA
Source blend factor is (1-As, 1-As, 1-As, 1-As) and destination blend factor is (As, As, As, As); the destination blend selection is overridden.
D3DPBLENDCAPS_BOTHSRCALPHA
The driver supports the D3DBLEND_BOTHSRCALPHA blend mode. (This blend mode is obsolete. For more information, see D3DBLEND.)
D3DPBLENDCAPS_DESTALPHA
Blend factor is (Ad, Ad, Ad, Ad).
D3DPBLENDCAPS_DESTCOLOR
Blend factor is (Rd, Gd, Bd, Ad).
D3DPBLENDCAPS_INVDESTALPHA
Blend factor is (1-Ad, 1-Ad, 1-Ad, 1-Ad).
D3DPBLENDCAPS_INVDESTCOLOR
Blend factor is (1-Rd, 1-Gd, 1-Bd, 1-Ad).
D3DPBLENDCAPS_INVSRCALPHA
Blend factor is (1-As, 1-As, 1-As, 1-As).
D3DPBLENDCAPS_INVSRCCOLOR
Blend factor is (1-Rs, 1-Gs, 1-Bs, 1-As).
D3DPBLENDCAPS_ONE
Blend factor is (1, 1, 1, 1).
D3DPBLENDCAPS_SRCALPHA
Blend factor is (As, As, As, As).
D3DPBLENDCAPS_SRCALPHASAT
Blend factor is (f, f, f, 1); f = min(As, 1-Ad).
D3DPBLENDCAPS_SRCCOLOR
Blend factor is (Rs, Gs, Bs, As).
D3DPBLENDCAPS_ZERO
Blend factor is (0, 0, 0, 0).
DestBlendCaps
Destination-blending capabilities. This member can be the same capabilities that are defined for the SrcBlendCaps member.
AlphaCmpCaps
Alpha-test comparison capabilities. This member can include the same capability flags defined for the ZCmpCaps member. If this member contains only the D3DPCMPCAPS_ALWAYS capability or only the D3DPCMPCAPS_NEVER capability, the driver does not support alpha tests. Otherwise, the flags identify the individual comparisons that are supported for alpha testing.
ShadeCaps
Shading operations capabilities. It is assumed, in general, that if a device supports a given command at all, it supports the D3DSHADE_FLAT mode (as specified in the D3DSHADEMODE enumerated type). This flag specifies whether the driver can also support Gouraud shading and whether alpha color components are supported. When alpha components are not supported, the alpha value of colors generated is implicitly 255. This is the maximum possible alpha (that is, the alpha component is at full intensity).

The color, specular highlights, fog, and alpha interpolants of a triangle each have capability flags that an application can use to find out how they are implemented by the device driver.

This member can be one or more of the following flags.

D3DPSHADECAPS_ALPHAGOURAUDBLEND
Device can support an alpha component for Gouraud-blended transparency (the D3DSHADE_GOURAUD state for the D3DSHADEMODE enumerated type). In this mode, the alpha color component of a primitive is provided at vertices and interpolated across a face along with the other color components.
D3DPSHADECAPS_COLORGOURAUDRGB
Device can support colored Gouraud shading. In this mode, the per-vertex color components (red, green, and blue) are interpolated across a triangle face.
D3DPSHADECAPS_FOGGOURAUD
Device can support fog in the Gouraud shading mode.
D3DPSHADECAPS_SPECULARGOURAUDRGB
Device supports Gouraud shading of specular highlights.
TextureCaps

Miscellaneous texture-mapping capabilities. This member can be one or more of the following flags.

D3DPTEXTURECAPS_ALPHA
Alpha in texture pixels is supported.
D3DPTEXTURECAPS_ALPHAPALETTE
Device can draw alpha from texture palettes.
D3DPTEXTURECAPS_CUBEMAP
Supports cube textures.
D3DPTEXTURECAPS_CUBEMAP_POW2
Device requires that cube texture maps have dimensions specified as powers of two.
D3DPTEXTURECAPS_MIPCUBEMAP
Device supports mipmapped cube textures.
D3DPTEXTURECAPS_MIPMAP
Device supports mipmapped textures.
D3DPTEXTURECAPS_MIPVOLUMEMAP
Device supports mipmapped volume textures.
D3DPTEXTURECAPS_NONPOW2CONDITIONAL
TextureCaps is also set, conditionally supports the use of 2-D textures with dimensions that are not powers of two. A device that exposes this capability can use such a texture if all of the following requirements are met.
  • The texture addressing mode for the texture stage is set to D3DTADDRESS_CLAMP.
  • Texture wrapping for the texture stage is disabled (D3DRS_WRAP n set to 0).
  • Mipmapping is not in use (use magnification filter only).
  • Texture formats must not be D3DFMT_DXT1 through D3DFMT_DXT5.

If this flag is not set, and TextureCaps is also not set, then unconditional support is provided for 2-D textures with dimensions that are not powers of two.

A texture that is not a power of two cannot be set at a stage that will be read based on a shader computation (such as the bem and texm3x3 instructions in pixel shaders versions 1_0 to 1_3). For example, these textures can be used to store bumps that will be fed into texture reads, but not the environment maps that are used in texbem, texbeml, and texm3x3spec. This means that a texture with dimensions that are not powers of two cannot be addressed or sampled using texture coordinates computed within the shader. This type of operation is known as a dependent read and cannot be performed on these types of textures.

D3DPTEXTURECAPS_NOPROJECTEDBUMPENV
Device does not support a projected bump-environment loopkup operation in programmable and fixed function shaders.
D3DPTEXTURECAPS_PERSPECTIVE
Perspective correction texturing is supported.
D3DPTEXTURECAPS_POW2
If TextureCaps is not set, all textures must have widths and heights specified as powers of two. This requirement does not apply to either cube textures or volume textures.

If TextureCaps is also set, conditionally supports the use of 2-D textures with dimensions that are not powers of two. See TextureCaps description.

If this flag is not set, and TextureCaps is also not set, then unconditional support is provided for 2-D textures with dimensions that are not powers of two.

D3DPTEXTURECAPS_PROJECTED
Supports the D3DTTFF_PROJECTED texture transformation flag. When applied, the device divides transformed texture coordinates by the last texture coordinate. If this capability is present, then the projective divide occurs per pixel. If this capability is not present, but the projective divide needs to occur anyway, then it is performed on a per-vertex basis by the Direct3D runtime.
D3DPTEXTURECAPS_SQUAREONLY
All textures must be square.
D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE
Texture indices are not scaled by the texture size prior to interpolation.
D3DPTEXTURECAPS_VOLUMEMAP
Device supports volume textures.
D3DPTEXTURECAPS_VOLUMEMAP_POW2
Device requires that volume texture maps have dimensions specified as powers of two.
TextureFilterCaps
Texture-filtering capabilities for a texture. Per-stage filtering capabilities reflect which filtering modes are supported for texture stages when performing multiple-texture blending. This member can be any combination of the per-stage texture-filtering flags defined in D3DPTFILTERCAPS.
CubeTextureFilterCaps
Texture-filtering capabilities for a cube texture. Per-stage filtering capabilities reflect which filtering modes are supported for texture stages when performing multiple-texture blending. This member can be any combination of the per-stage texture-filtering flags defined in D3DPTFILTERCAPS.
VolumeTextureFilterCaps
Texture-filtering capabilities for a volume texture. Per-stage filtering capabilities reflect which filtering modes are supported for texture stages when performing multiple-texture blending. This member can be any combination of the per-stage texture-filtering flags defined in D3DPTFILTERCAPS.
TextureAddressCaps

Texture-addressing capabilities for texture objects. This member can be one or more of the following flags.

D3DPTADDRESSCAPS_BORDER
Device supports setting coordinates outside the range [0.0, 1.0] to the border color, as specified by the D3DSAMP_BORDERCOLOR texture-stage state.
D3DPTADDRESSCAPS_CLAMP
Device can clamp textures to addresses.
D3DPTADDRESSCAPS_INDEPENDENTUV
Device can separate the texture-addressing modes of the u and v coordinates of the texture. This ability corresponds to the D3DSAMP_ADDRESSU and D3DSAMP_ADDRESSV render-state values.
D3DPTADDRESSCAPS_MIRROR
Device can mirror textures to addresses.
D3DPTADDRESSCAPS_MIRRORONCE
Device can take the absolute value of the texture coordinate (thus, mirroring around 0) and then clamp to the maximum value.
D3DPTADDRESSCAPS_WRAP
Device can wrap textures to addresses.
VolumeTextureAddressCaps
Texture-addressing capabilities for a volume texture. This member can be one or more of the flags defined for the TextureAddressCaps member.
LineCaps

Defines the capabilities for line-drawing primitives.

D3DLINECAPS_ALPHACMP
Supports alpha-test comparisons.
D3DLINECAPS_ANTIALIAS
Antialiased lines are supported.
D3DLINECAPS_BLEND
Supports source-blending.
D3DLINECAPS_FOG
Supports fog.
D3DLINECAPS_TEXTURE
Supports texture-mapping.
D3DLINECAPS_ZTEST
Supports z-buffer comparisons.
MaxTextureWidth
Maximum texture width for this device.
MaxTextureHeight
Maximum texture height for this device.
MaxVolumeExtent
Maximum value for any of the three dimensions (width, height, and depth) of a volume texture.
MaxTextureRepeat

This number represents the maximum range of the integer bits of the post-normalized texture coordinates. A texture coordinate is stored as a 32-bit signed integer using 27 bits to store the integer part and 5 bits for the floating point fraction. The maximum integer index, 227, is used to determine the maximum texture coordinate, depending on how the hardware does texture-coordinate scaling.

Some hardware reports the cap TextureCaps. For this case, the device defers scaling texture coordinates by the texture size until after interpolation and application of the texture address mode, so the number of times a texture can be wrapped is given by the integer value in MaxTextureRepeat.

Less desirably, on some hardware TextureCaps is not set and the device scales the texture coordinates by the texture size (using the highest level of detail) prior to interpolation. This limits the number of times a texture can be wrapped to MaxTextureRepeat / texture size.

For example, assume that MaxTextureRepeat is equal to 32k and the size of the texture is 4k. If the hardware sets TextureCaps, then the number of times a texture can be wrapped is equal to MaxTextureRepeat, which is 32k in this example. Otherwise, the number of times a texture can be wrapped is equal to MaxTextureRepeat divided by texture size, which is 32k/4k in this example.

MaxTextureAspectRatio
Maximum texture aspect ratio supported by the hardware, typically a power of 2.
MaxAnisotropy
Maximum valid value for the D3DSAMP_MAXANISOTROPY texture-stage state.
MaxVertexW
Maximum W-based depth value that the device supports.
GuardBandLeft
Screen-space coordinate of the guard-band clipping region. Coordinates inside this rectangle but outside the viewport rectangle are automatically clipped.
GuardBandTop
Screen-space coordinate of the guard-band clipping region. Coordinates inside this rectangle but outside the viewport rectangle are automatically clipped.
GuardBandRight
Screen-space coordinate of the guard-band clipping region. Coordinates inside this rectangle but outside the viewport rectangle are automatically clipped.
GuardBandBottom
Screen-space coordinate of the guard-band clipping region. Coordinates inside this rectangle but outside the viewport rectangle are automatically clipped.
ExtentsAdjust
Number of pixels to adjust the extents rectangle outward to accommodate antialiasing kernels.
StencilCaps
Flags specifying supported stencil-buffer operations. Stencil operations are assumed to be valid for all three stencil-buffer operation render states (D3DRS_STENCILFAIL, D3DRS_STENCILPASS, and D3DRS_STENCILZFAIL).

For more information, see D3DSTENCILCAPS.

FVFCaps

Flexible vertex format capabilities.

D3DFVFCAPS_DONOTSTRIPELEMENTS
It is preferable that vertex elements not be stripped. That is, if the vertex format contains elements that are not used with the current render states, there is no need to regenerate the vertices. If this capability flag is not present, stripping extraneous elements from the vertex format provides better performance.
D3DFVFCAPS_PSIZE

Point size is determined by either the render state or the vertex data. If an flexible vertex format (FVF) is used, point size can come from point size data in the vertex declaration. Otherwise, point size is determined by the render state D3DRS_POINTSIZE. If the application provides point size in both (the render state and the vertex declaration), the vertex data overrides the render-state data.

D3DFVFCAPS_TEXCOORDCOUNTMASK
Masks the low WORD of FVFCaps. These bits, cast to the WORD data type, describe the total number of texture coordinate sets that the device can simultaneously use for multiple texture blending. (You can use up to eight texture coordinate sets for any vertex, but the device can blend using only the specified number of texture coordinate sets.)
TextureOpCaps

Combination of flags describing the texture operations supported by this device. The following flags are defined.

D3DTEXOPCAPS_ADD
The D3DTOP_ADD texture-blending operation is supported.
D3DTEXOPCAPS_ADDSIGNED
The D3DTOP_ADDSIGNED texture-blending operation is supported.
D3DTEXOPCAPS_ADDSIGNED2X
The D3DTOP_ADDSIGNED2X texture-blending operation is supported.
D3DTEXOPCAPS_ADDSMOOTH
The D3DTOP_ADDSMOOTH texture-blending operation is supported.
D3DTEXOPCAPS_BLENDCURRENTALPHA
The D3DTOP_BLENDCURRENTALPHA texture-blending operation is supported.
D3DTEXOPCAPS_BLENDDIFFUSEALPHA
The D3DTOP_BLENDDIFFUSEALPHA texture-blending operation is supported.
D3DTEXOPCAPS_BLENDFACTORALPHA
The D3DTOP_BLENDFACTORALPHA texture-blending operation is supported.
D3DTEXOPCAPS_BLENDTEXTUREALPHA
The D3DTOP_BLENDTEXTUREALPHA texture-blending operation is supported.
D3DTEXOPCAPS_BLENDTEXTUREALPHAPM
The D3DTOP_BLENDTEXTUREALPHAPM texture-blending operation is supported.
D3DTEXOPCAPS_BUMPENVMAP
The D3DTOP_BUMPENVMAP texture-blending operation is supported.
D3DTEXOPCAPS_BUMPENVMAPLUMINANCE
The D3DTOP_BUMPENVMAPLUMINANCE texture-blending operation is supported.
D3DTEXOPCAPS_DISABLE
The D3DTOP_DISABLE texture-blending operation is supported.
D3DTEXOPCAPS_DOTPRODUCT3
The D3DTOP_DOTPRODUCT3 texture-blending operation is supported.
D3DTEXOPCAPS_LERP
The D3DTOP_LERP texture-blending operation is supported.
D3DTEXOPCAPS_MODULATE
The D3DTOP_MODULATE texture-blending operation is supported.
D3DTEXOPCAPS_MODULATE2X
The D3DTOP_MODULATE2X texture-blending operation is supported.
D3DTEXOPCAPS_MODULATE4X
The D3DTOP_MODULATE4X texture-blending operation is supported.
D3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR
The D3DTOP_MODULATEALPHA_ADDCOLOR texture-blending operation is supported.
D3DTEXOPCAPS_MODULATECOLOR_ADDALPHA
The D3DTOP_MODULATECOLOR_ADDALPHA texture-blending operation is supported.
D3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR
The D3DTOP_MODULATEINVALPHA_ADDCOLOR texture-blending operation is supported.
D3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA
The D3DTOP_MODULATEINVCOLOR_ADDALPHA texture-blending operation is supported.
D3DTEXOPCAPS_MULTIPLYADD
The D3DTOP_MULTIPLYADD texture-blending operation is supported.
D3DTEXOPCAPS_PREMODULATE
The D3DTOP_PREMODULATE texture-blending operation is supported.
D3DTEXOPCAPS_SELECTARG1
The D3DTOP_SELECTARG1 texture-blending operation is supported.
D3DTEXOPCAPS_SELECTARG2
The D3DTOP_SELECTARG2 texture-blending operation is supported.
D3DTEXOPCAPS_SUBTRACT
The D3DTOP_SUBTRACT texture-blending operation is supported.
MaxTextureBlendStages
Maximum number of texture-blending stages supported in the fixed function pipeline. This value is the number of blenders available. In the programmable pixel pipeline, this corresponds to the number of unique texture registers used by pixel shader instructions.
MaxSimultaneousTextures
Maximum number of textures that can be simultaneously bound to the fixed-function pipeline sampler stages. If the same texture is bound to two sampler stages, it counts as two textures.

This value has no meaning in the programmable pipeline where the number of sampler stages is determined by each pixel shader version. Each pixel shader version also determines the number of texture declaration instructions. See ps_1_1, ps_1_2, ps_1_3, ps_1_4,ps_2_0,ps_2_x,ps_3_0,
VertexProcessingCaps

Vertex processing capabilities. For a given physical device, this capability might vary across Direct3D devices depending on the parameters supplied to IDirect3D9::CreateDevice. See D3DVTXPCAPS.

MaxActiveLights
Maximum number of lights that can be active simultaneously. For a given physical device, this capability might vary across Direct3D devices depending on the parameters supplied to IDirect3D9::CreateDevice.
MaxUserClipPlanes
Maximum number of user-defined clipping planes supported. This member can be 0. For a given physical device, this capability may vary across Direct3D devices depending on the parameters supplied to IDirect3D9::CreateDevice.
MaxVertexBlendMatrices
Maximum number of matrices that this device can apply when performing multimatrix vertex blending. For a given physical device, this capability may vary across Direct3D devices depending on the parameters supplied to IDirect3D9::CreateDevice.
MaxVertexBlendMatrixIndex
DWORD value that specifies the maximum matrix index that can be indexed into using the per-vertex indices. The number of matrices is MaxVertexBlendMatrixIndex + 1, which is the size of the matrix palette. If normals are present in the vertex data that needs to be blended for lighting, then the number of matrices is half the number specified by this capability flag. If MaxVertexBlendMatrixIndex is set to zero, the driver does not support indexed vertex blending. If this value is not zero then the valid range of indices is zero through MaxVertexBlendMatrixIndex.

A zero value for MaxVertexBlendMatrixIndex indicates that the driver does not support indexed matrices.

When software vertex processing is used, 256 matrices could be used for indexed vertex blending, with or without normal blending.

For a given physical device, this capability may vary across Direct3D devices depending on the parameters supplied to IDirect3D9::CreateDevice.

MaxPointSize
Maximum size of a point primitive. If set to 1.0f then device does not support point size control. The range is greater than or equal to 1.0f.
MaxPrimitiveCount
Maximum number of primitives for each IDirect3DDevice9::DrawPrimitive call. There are two cases:
  • If MaxPrimitiveCount is not equal to 0xffff, you can draw at most MaxPrimitiveCount primitives with each draw call.
  • However, if MaxPrimitiveCount equals 0xffff, you can still draw at most MaxPrimitiveCount primitive, but you may also use no more than MaxPrimitiveCount unique vertices (since each primitive can potentially use three different vertices).
MaxVertexIndex
Maximum size of indices supported for hardware vertex processing. It is possible to create 32-bit index buffers; however, you will not be able to render with the index buffer unless this value is greater than 0x0000FFFF.
MaxStreams
Maximum number of concurrent data streams for IDirect3DDevice9::SetStreamSource. The valid range is 1 to 16. Note that if this value is 0, then the driver is not a DirectX 9.0 driver.
MaxStreamStride
Maximum stride for IDirect3DDevice9::SetStreamSource.
VertexShaderVersion
Two numbers that represent the vertex shader main and sub versions. For more information about the instructions supported for each vertex shader version, see Version 1_x, Version 2_0, Version 2_0 Extended, or Version 3_0.
MaxVertexShaderConst
The number of vertex shader Registers that are reserved for constants.
PixelShaderVersion
Two numbers that represent the pixel shader main and sub versions. For more information about the instructions supported for each pixel shader version, see Version 1_x, Version 2_0, Version 2_0 Extended, or Version 3_0.
PixelShader1xMaxValue
Maximum value of pixel shader arithmetic component. This value indicates the internal range of values supported for pixel color blending operations. Within the range that they report to, implementations must allow data to pass through pixel processing unmodified (unclamped). Normally, the value of this member is an absolute value. For example, a 1.0 indicates that the range is -1.0 to 1, and an 8.0 indicates that the range is -8.0 to 8.0. The value must be >= 1.0 for any hardware that supports pixel shaders.
DevCaps2
Device driver capabilities for adaptive tessellation. For more information, see D3DDEVCAPS2
MaxNpatchTessellationLevel
Maximum number of N-patch subdivision levels. The driver will clamp applications to this value, if they are using presampled displacement mapping. See Tessellation and Displacement Mapping.
MasterAdapterOrdinal

This number indicates which device is the master for this subordinate. This number is taken from the same space as the adapter values.

For multihead support, one head will be denoted the master head, and all other heads on the same card be denoted subordinate heads. If more than one multihead adapter is present in a system, the master and its subordinates from one multihead adapter are called a group.

AdapterOrdinalInGroup
This number indicates the order in which heads are referenced by the application programming interface (API). The value for the master adapter is always 0. These values do not correspond to the adapter ordinals. They apply only to heads within a group.
NumberOfAdaptersInGroup
Number of adapters in this adapter group (only if master). This will be 1 for conventional adapters. The value will be greater than 1 for the master adapter of a multihead card. The value will be 0 for a subordinate adapter of a multihead card. Each card can have at most one master, but may have many subordinates.
DeclTypes
A combination of one or more data types contained in a vertex declaration. See D3DDTCAPS.
NumSimultaneousRTs
Number of simultaneous render targets. This number must be at least one.
StretchRectFilterCaps

Combination of constants that describe the operations supported by IDirect3DDevice9::StretchRect. The flags that may be set in this field are:

Constant | Description
D3DPTFILTERCAPS_MINFPOINT | Device supports point-sample filtering for minifying rectangles. This filter type is requested by calling IDirect3DDevice9::StretchRect using D3DTEXF_POINT.
D3DPTFILTERCAPS_MAGFPOINT | Device supports point-sample filtering for magnifying rectangles. This filter type is requested by calling IDirect3DDevice9::StretchRect using D3DTEXF_POINT.
D3DPTFILTERCAPS_MINFLINEAR | Device supports bilinear interpolation filtering for minifying rectangles. This filter type is requested by calling IDirect3DDevice9::StretchRect using D3DTEXF_LINEAR.
D3DPTFILTERCAPS_MAGFLINEAR | Device supports bilinear interpolation filtering for magnifying rectangles. This filter type is requested by calling IDirect3DDevice9::StretchRect using D3DTEXF_LINEAR.

For more information, see D3DTEXTUREFILTERTYPE and D3DTEXTUREFILTERTYPE.

VS20Caps
Device supports vertex shader version 2_0 extended capability. See D3DVS20CAPS.
PS20Caps
Device supports pixel shader version 2_0 extended capability. See D3DPS20CAPS.
VertexTextureFilterCaps
Device supports vertex shader texture filter capability. See D3DPTFILTERCAPS.
MaxVShaderInstructionsExecuted
Maximum number of vertex shader instructions that can be run.
MaxPShaderInstructionsExecuted
Maximum number of pixel shader instructions that can be run.
MaxVertexShader30InstructionSlots
Maximum number of vertex shader instruction slots supported. The maximum value that can be set on this cap is 32768. Devices that support vs_3_0 are required to support at least 512 instruction slots.
MaxPixelShader30InstructionSlots
Maximum number of pixel shader instruction slots supported. The maximum value that can be set on this cap is 32768. Devices that support ps_3_0 are required to support at least 512 instruction slots.
Reserved2
Reserved.
Reserved3
Reserved.

Remarks

The MaxTextureBlendStages and MaxSimultaneousTextures members might seem similar, but they contain different information. The MaxTextureBlendStages member contains the total number of texture-blending stages supported by the current device, and the MaxSimultaneousTextures member describes how many of those stages can have textures bound to them by using the IDirect3DDevice9::SetTexture method.

When the driver fills this structure, it can set values for execute-buffer capabilities, even when the interface being used to retrieve the capabilities (such as IDirect3DDevice9) does not support execute buffers.

In general, performance problems may occur if you use a texture and then modify it during a scene. Ensure that no texture used in the current IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene block is evicted unless absolutely necessary. In the case of extremely high texture usage within a scene, the results are undefined. This occurs when you modify a texture that you have used in the scene and there is no spare texture memory available. For such systems, the contents of the z-buffer become invalid at EndScene. Applications should not call IDirect3DDevice9::UpdateSurface to or from the back buffer on this type of hardware inside a BeginScene/EndScene pair. In addition, applications should not try to access the z-buffer if the D3DPRASTERCAPS_ZBUFFERLESSHSR capability flag is set. Finally, applications should not lock the back buffer or the z-buffer inside a BeginScene/EndScene pair.

The following flags concerning mipmapped textures are not supported in DirectX 9.0.

  • D3DPTFILTERCAPS_LINEAR
  • D3DPTFILTERCAPS_LINEARMIPLINEAR
  • D3DPTFILTERCAPS_LINEARMIPNEAREST
  • D3DPTFILTERCAPS_MIPNEAREST
  • D3DPTFILTERCAPS_NEAREST

Structure Information

Header | d3d9caps.h
Minimum operating systems | Windows 98

See Also

IDirect3D9::GetDeviceCaps, IDirect3DDevice9::GetDeviceCaps


D3DCLIPSTATUS9 Structure

Describes the current clip status.

Syntax

typedef struct _D3DCLIPSTATUS9 {
    DWORD ClipUnion;
    DWORD ClipIntersection;
} D3DCLIPSTATUS9;

Members

ClipUnion

Clip union flags that describe the current clip status. This member can be one or more of the following flags:

D3DCS_ALL
Combination of all clip flags.
D3DCS_LEFT
All vertices are clipped by the left plane of the viewing frustum.
D3DCS_RIGHT
All vertices are clipped by the right plane of the viewing frustum.
D3DCS_TOP
All vertices are clipped by the top plane of the viewing frustum.
D3DCS_BOTTOM
All vertices are clipped by the bottom plane of the viewing frustum.
D3DCS_FRONT
All vertices are clipped by the front plane of the viewing frustum.
D3DCS_BACK
All vertices are clipped by the back plane of the viewing frustum.
D3DCS_PLANE0
Application-defined clipping planes.
D3DCS_PLANE1
Application-defined clipping planes.
D3DCS_PLANE2
Application-defined clipping planes.
D3DCS_PLANE3
Application-defined clipping planes.
D3DCS_PLANE4
Application-defined clipping planes.
D3DCS_PLANE5
Application-defined clipping planes.
ClipIntersection
Clip intersection flags that describe the current clip status. This member can take the same flags as ClipUnion.

Remarks

When clipping is enabled during vertex processing (by IDirect3DDevice9::ProcessVertices, IDirect3DDevice9::DrawPrimitive, or other drawing functions), Microsoft Direct3D computes a clip code for every vertex. The clip code is a combination of D3DCS_* bits. When a vertex is outside a particular clipping plane, the corresponding bit is set in the clipping code. Direct3D maintains the clip status using D3DCLIPSTATUS9, which has ClipUnion and ClipIntersection members. ClipUnion is a bitwise OR of all vertex clip codes and ClipIntersection is a bitwise AND of all vertex clip codes. Initial values are zero for ClipUnion and 0xFFFFFFFF for ClipIntersection. When D3DRS_CLIPPING is set to FALSE, ClipUnion and ClipIntersection are set to zero. Direct3D updates the clip status during drawing calls. To compute clip status for a particular object, set ClipUnion and ClipIntersection to their initial value and continue drawing.

Clip status is not updated by IDirect3DDevice9::DrawRectPatch and IDirect3DDevice9::DrawTriPatch because there is no software emulation for them.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::GetClipStatus, IDirect3DDevice9::SetClipStatus


D3DCOLORVALUE Structure

Describes color values.

Syntax

typedef struct _D3DCOLORVALUE {
    float r;
    float g;
    float b;
    float a;
} D3DCOLORVALUE;

Members

r
Floating-point value specifying the red component of a color. This value generally is in the range from 0.0 through 1.0, with 0.0 being black.
g
Floating-point value specifying the green component of a color. This value generally is in the range from 0.0 through 1.0, with 0.0 being black.
b
Floating-point value specifying the blue component of a color. This value generally is in the range from 0.0 through 1.0, with 0.0 being black.
a
Floating-point value specifying the alpha component of a color. This value generally is in the range from 0.0 through 1.0, with 0.0 being black.

Remarks

You can set the members of this structure to values outside the range of 0 through 1 to implement some unusual effects. Values greater than 1 produce strong lights that tend to wash out a scene. Negative values produce dark lights that actually remove light from a scene.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98


D3DDEVICE_CREATION_PARAMETERS Structure

Describes the creation parameters for a device.

Syntax

typedef struct _D3DDEVICE_CREATION_PARAMETERS {
    UINT AdapterOrdinal;
    D3DDEVTYPE DeviceType;
    HWND hFocusWindow;
    DWORD BehaviorFlags;
} D3DDEVICE_CREATION_PARAMETERS;

Members

AdapterOrdinal
Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter.

Use this ordinal as the Adapter parameter for any of the IDirect3D9 methods. Note that different instances of Microsoft Direct3D 9.0 objects can use different ordinals. Adapters can enter or leave a system when users, for example, add or remove monitors from a multiple-monitor system or when they hot-swap a laptop. Consequently, use this ordinal only in a Direct3D 9.0 instance known to be valid, that is, either the Direct3D 9.0 that created this IDirect3DDevice9 interface or the Direct3D 9.0 returned from IDirect3DDevice9::GetDirect3D, as called through this IDirect3DDevice9 interface.
DeviceType
Member of the D3DDEVTYPE enumerated type. Denotes the amount of emulated functionality for this device. The value of this parameter mirrors the value passed to the IDirect3D9::CreateDevice call that created this device.
hFocusWindow
Window handle to which focus belongs for this Direct3D device. The value of this parameter mirrors the value passed to the IDirect3D9::CreateDevice call that created this device.
BehaviorFlags
A combination of one or more D3DCREATE constants that control global behavior of the device. These constants mirror the constants passed to IDirect3D9::CreateDevice when the device was created.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::GetCreationParameters, IDirect3D9::CreateDevice


D3DDEVINFO_D3D9BANDWIDTHTIMINGS Structure

Throughput metrics for help in understanding the performance of an application.

Syntax

typedef struct _D3DDEVINFO_D3D9BANDWIDTHTIMINGS {
    FLOAT MaxBandwidthUtilized;
    FLOAT FrontEndUploadMemoryUtilizedPercent;
    FLOAT VertexRateUtilizedPercent;
    FLOAT TriangleSetupRateUtilizedPercent;
    FLOAT FillRateUtilizedPercent;
} D3DDEVINFO_D3D9BANDWIDTHTIMINGS;

Members

MaxBandwidthUtilized
The bandwidth or maximum data transfer rate from the host CPU to the graphics processing unit (GPU). This is typically the bandwidth of the Peripheral Component Interconnect (PCI) or accelerated graphics port (AGP) bus which connects the CPU and the GPU.
FrontEndUploadMemoryUtilizedPercent
Memory utilized percentage when uploading data from the host CPU to the GPU.
VertexRateUtilizedPercent
Vertex throughput percentage. This is the number of vertices processed compared to the theoretical maximum vertex processing rate.
TriangleSetupRateUtilizedPercent
Triangle set-up throughput percentage. This is the number of triangles that are set up for rasterization compared to the theoretical maximum triangle set-up rate.
FillRateUtilizedPercent
Pixel fill throughput percentage. This is the number of pixels that are filled compared to the theoretical pixel fill.

Remarks

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DQuery9::GetData


D3DDEVINFO_D3D9CACHEUTILIZATION Structure

Measure the cache hit rate performance for textures and indexed vertices.

Syntax

typedef struct _D3DDEVINFO_D3D9CACHEUTILIZATION {
    FLOAT TextureCacheHitRate;
    FLOAT PostTransformVertexCacheHitRate;
} D3DDEVINFO_D3D9CACHEUTILIZATION;

Members

TextureCacheHitRate
The hit rate for finding a texture in the texture cache. This assumes there is a texture cache. Increasing the level of detail (LOD) bias to use the most detailed texture, using many large textures, or producing a near random texture access pattern on large textures with custom shader code can dramatically affect the texture cache hit rate.
PostTransformVertexCacheHitRate
The hit rate for finding transformed vertices in the vertex cache. The graphics processing unit (GPU) is designed to transform indexed vertices and may store them in a vertex cache. If you are using meshes, D3DXOptimizeFaces or D3DXOptimizeVertices may result in better vertex cache utilization.

Remarks

An efficient cache is typically closer to a 90 percent hit rate, and an inefficient cache is typically closer to a 10 percent hit rate (although a low percentage is not necessarily a problem).

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DQuery9::GetData


D3DDEVINFO_D3D9INTERFACETIMINGS Structure

Percent of time processing data in the driver. These statistics may help identify cases when the driver is waiting for other resources.

Syntax

typedef struct _D3DDEVINFO_D3D9INTERFACETIMINGS {
    FLOAT WaitingForGPUToUseApplicationResourceTimePercent;
    FLOAT WaitingForGPUToAcceptMoreCommandsTimePercent;
    FLOAT WaitingForGPUToStayWithinLatencyTimePercent;
    FLOAT WaitingForGPUExclusiveResourceTimePercent;
    FLOAT WaitingForGPUOtherTimePercent;
} D3DDEVINFO_D3D9INTERFACETIMINGS;

Members

WaitingForGPUToUseApplicationResourceTimePercent
Percentage of time the driver spent waiting for the graphics processing unit (GPU) to finish using a locked resource (and D3DLOCK_DONOTWAIT wasn't specified).
WaitingForGPUToAcceptMoreCommandsTimePercent
Percentage of time the driver spent waiting for the GPU to finish processing some commands before the driver could send more. This indicates the driver has run out of room to send commands to the GPU.
WaitingForGPUToStayWithinLatencyTimePercent
Percentage of time the driver spent waiting for the GPU latency to reduce to less than three rendering frames.

If an application is GPU-limited, the driver must stall the CPU until the GPU gets within three frames. This prevents an application from queueing up many seconds' worth of rendering calls which may dramatically increase the latency between when the user inputs new data and when the user sees the results of that input. In general, the driver can track the number of times IDirect3DDevice9::Present is called to prevent queueing up more than three frames of rendering work.
WaitingForGPUExclusiveResourceTimePercent
Percentage of time the driver spent waiting for a resource that cannot be pipelined (that is operated in parallel). An application may want to avoid using a non-pipelined resource for performance reasons.
WaitingForGPUOtherTimePercent
Percentage of time the driver spent waiting for other GPU processing.

Remarks

These metrics help identify when a driver is waiting and what it is waiting for. High percentages are not necessarily a problem.

These system-global metrics may or may not be implemented. Depending on the specific hardware, these metrics may not support multiple queries simultaneously.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DQuery9::GetData


D3DDEVINFO_D3D9PIPELINETIMINGS Structure

Percent of time processing data in the pipeline.

Syntax

typedef struct _D3DDEVINFO_D3D9PIPELINETIMINGS {
    FLOAT VertexProcessingTimePercent;
    FLOAT PixelProcessingTimePercent;
    FLOAT OtherGPUProcessingTimePercent;
    FLOAT GPUIdleTimePercent;
} D3DDEVINFO_D3D9PIPELINETIMINGS;

Members

VertexProcessingTimePercent
Percent of time spent running vertex shaders.
PixelProcessingTimePercent
Percent of time spent running pixel shaders.
OtherGPUProcessingTimePercent
Percent of time spent doing other processing.
GPUIdleTimePercent
Percent of time not processing anything.

Remarks

For best performance, a balanced load is recommended.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DQuery9::GetData


D3DDEVINFO_D3D9STAGETIMINGS Structure

Percent of time processing shader data.

Syntax

typedef struct _D3DDEVINFO_D3D9STAGETIMINGS {
    FLOAT MemoryProcessingPercent;
    FLOAT ComputationProcessingPercent;
} D3DDEVINFO_D3D9STAGETIMINGS;

Members

MemoryProcessingPercent
Percent of time in shader spent on memory accesses.
ComputationProcessingPercent
Percent of time processing (moving data around in registers or doing mathematical operations).

Remarks

For best performance, a balanced load is recommended.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DQuery9::GetData


D3DDEVINFO_D3DVERTEXSTATS Structure

Reports the number of triangles that have been processed and clipped by the runtime's software vertex processing.

Syntax

typedef struct _D3DDEVINFO_D3DVERTEXSTATS {
    DWORD NumRenderedTriangles;
    DWORD NumExtraClippingTriangles;
} D3DDEVINFO_D3DVERTEXSTATS;

Members

NumRenderedTriangles
Total number of triangles that are not clipped in this frame.
NumExtraClippingTriangles
Number of new triangles generated by clipping.

Remarks

Use the debug runtime and software vertex processing to get the number of non-clipped and clipped primitives for a particular scene. Primitives will typically be clipped based on a guard band (if one is present). The clipping guard band is set with parameters such as GuardBandLeft in D3DCAPS9.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98


D3DDEVINFO_RESOURCEMANAGER Structure

Resource usage statistics.

Syntax

typedef struct _D3DDEVINFO_RESOURCEMANAGER {
    D3DRESOURCESTATS stats[D3DRTYPECOUNT];
} D3DDEVINFO_RESOURCEMANAGER;

Members

stats
Array of resource statistics elements. See D3DRESOURCESTATS.

Remarks

D3DRTYPECOUNT refers to the number of enumerations in D3DRESOURCETYPE.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98


D3DDEVINFO_VCACHE Structure

Vertex cache optimization hints.

Syntax

typedef struct D3DDEVINFO_VCACHE {
    DWORD Pattern;
    DWORD OptMethod;
    DWORD CacheSize;
    DWORD MagicNumber;
} D3DDEVINFO_VCACHE;

Members

Pattern
Bit pattern. Return value must be the four-character code (FOURCC) ('C', 'A', 'C', 'H').
OptMethod
Optimizations method. Use 0 to get the longest strips. Use 1 to optimize the vertex cache usage.
CacheSize
Cache size used as a target for optimization. This is required only if OptMethod is 1.
MagicNumber
Used by internal optimization methods to determine when to restart strips. This cannot be set or modified by a user. This is required only if OptMethod is 1.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DQuery9::GetData


D3DDISPLAYMODE Structure

Describes the display mode.

Syntax

typedef struct _D3DDISPLAYMODE {
    UINT Width;
    UINT Height;
    UINT RefreshRate;
    D3DFORMAT Format;
} D3DDISPLAYMODE;

Members

Width
Screen width, in pixels.
Height
Screen height, in pixels.
RefreshRate
Refresh rate. The value of 0 indicates an adapter default.
Format
Member of the D3DFORMAT enumerated type, describing the surface format of the display mode.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3D9::EnumAdapterModes, IDirect3D9::GetAdapterDisplayMode, IDirect3DDevice9::GetDisplayMode


D3DGAMMARAMP Structure

Contains red, green, and blue ramp data.

Syntax

typedef struct _D3DGAMMARAMP {
    WORD red[256];
    WORD green[256];
    WORD blue[256];
} D3DGAMMARAMP;

Members

red
Array of 256 WORD element that describes the red gamma ramp.
green
Array of 256 WORD element that describes the green gamma ramp.
blue
Array of 256 WORD element that describes the blue gamma ramp.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::GetGammaRamp, IDirect3DDevice9::SetGammaRamp


D3DINDEXBUFFER_DESC Structure

Describes an index buffer.

Syntax

typedef struct _D3DINDEXBUFFER_DESC {
    D3DFORMAT Format;
    D3DRESOURCETYPE Type;
    DWORD Usage;
    D3DPOOL Pool;
    UINT Size;
} D3DINDEXBUFFER_DESC;

Members

Format
Member of the D3DFORMAT enumerated type, describing the surface format of the index buffer data.
Type
Member of the D3DRESOURCETYPE enumerated type, identifying this resource as an index buffer.
Usage
Combination of one or more of the following flags, specifying the usage for this resource.

D3DUSAGE_DONOTCLIP
Set to indicate that the index buffer content will never require clipping.
D3DUSAGE_DYNAMIC
Set to indicate that the index buffer requires dynamic memory use. This is useful for drivers because it enables them to decide where to place the buffer. In general, static index buffers are placed in video memory and dynamic index buffers are placed in accelerated graphics port (AGP) memory. Note that there is no separate static usage; if you do not specify D3DUSAGE_DYNAMIC the index buffer is made static. D3DUSAGE_DYNAMIC is strictly enforced through the D3DLOCK_DISCARD and D3DLOCK_NOOVERWRITE locking flags. As a result, D3DLOCK_DISCARD and D3DLOCK_NOOVERWRITE are only valid on index buffers created with D3DUSAGE_DYNAMIC; they are not valid flags on static vertex buffers.

For more information about using dynamic index buffers, see Using Dynamic Vertex and Index Buffers.

Note that D3DUSAGE_DYNAMIC cannot be specified on managed index buffers. For more information, see Managing Resources.
D3DUSAGE_RTPATCHES
Set to indicate when the index buffer is to be used for drawing high-order primitives.
D3DUSAGE_NPATCHES
Set to indicate when the index buffer is to be used for drawing N patches.
D3DUSAGE_POINTS
Set to indicate when the index buffer is to be used for drawing point sprites or indexed point lists.
D3DUSAGE_SOFTWAREPROCESSING
Set to indicate that the buffer is to be used with software processing.
D3DUSAGE_WRITEONLY
Informs the system that the application writes only to the index buffer. Using this flag enables the driver to choose the best memory location for efficient write operations and rendering. Attempts to read from an index buffer that is created with this capability can result in degraded performance.
Pool
Member of the D3DPOOL enumerated type, specifying the class of memory allocated for this index buffer.
Size
Size of the index buffer, in bytes.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DIndexBuffer9::GetDesc


D3DLIGHT9 Structure

Defines a set of lighting properties.

Syntax

typedef struct _D3DLIGHT9 {
    D3DLIGHTTYPE Type;
    D3DCOLORVALUE Diffuse;
    D3DCOLORVALUE Specular;
    D3DCOLORVALUE Ambient;
    D3DVECTOR Position;
    D3DVECTOR Direction;
    float Range;
    float Falloff;
    float Attenuation0;
    float Attenuation1;
    float Attenuation2;
    float Theta;
    float Phi;
} D3DLIGHT9;

Members

Type
Type of the light source. This value is one of the members of the D3DLIGHTTYPE enumerated type.
Diffuse
Diffuse color emitted by the light. This member is a D3DCOLORVALUE structure.
Specular
Specular color emitted by the light. This member is a D3DCOLORVALUE structure.
Ambient
Ambient color emitted by the light. This member is a D3DCOLORVALUE structure.
Position
Position of the light in world space, specified by a D3DVECTOR structure. This member has no meaning for directional lights and is ignored in that case.
Direction
Direction that the light is pointing in world space, specified by a D3DVECTOR structure. This member has meaning only for directional and spotlights. This vector need not be normalized, but it should have a nonzero length.
Range
Distance beyond which the light has no effect. The maximum allowable value for this member is the square root of FLT_MAX. This member does not affect directional lights.
Falloff
Decrease in illumination between a spotlight's inner cone (the angle specified by Theta) and the outer edge of the outer cone (the angle specified by Phi).

The effect of falloff on the lighting is subtle. Furthermore, a small performance penalty is incurred by shaping the falloff curve. For these reasons, most developers set this value to 1.0.

Attenuation0
Value specifying how the light intensity changes over distance. Attenuation values are ignored for directional lights. This member represents an attenuation constant. For information about attenuation, see Light Properties. Valid values for this member range from 0.0 to infinity. For non-directional lights, all three attenuation values should not be set to 0.0 at the same time.
Attenuation1
Value specifying how the light intensity changes over distance. Attenuation values are ignored for directional lights. This member represents an attenuation constant. For information about attenuation, see Light Properties. Valid values for this member range from 0.0 to infinity. For non-directional lights, all three attenuation values should not be set to 0.0 at the same time.
Attenuation2
Value specifying how the light intensity changes over distance. Attenuation values are ignored for directional lights. This member represents an attenuation constant. For information about attenuation, see Light Properties. Valid values for this member range from 0.0 to infinity. For non-directional lights, all three attenuation values should not be set to 0.0 at the same time.
Theta
Angle, in radians, of a spotlight's inner cone—that is, the fully illuminated spotlight cone. This value must be in the range from 0 through the value specified by Phi.
Phi
Angle, in radians, defining the outer edge of the spotlight's outer cone. Points outside this cone are not lit by the spotlight. This value must be between 0 and pi.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::GetLight, IDirect3DDevice9::SetLight


D3DLOCKED_BOX Structure

Describes a locked box (volume).

Syntax

typedef struct _D3DLOCKED_BOX {
    int RowPitch;
    int SlicePitch;
    void *pBits;
} D3DLOCKED_BOX;

Members

RowPitch
Byte offset from the left edge of one row to the left edge of the next row.
SlicePitch
Byte offset from the top-left of one slice to the top-left of the next deepest slice.
pBits
Pointer to the beginning of the volume box. If a D3DBOX was provided to the LockBox call, pBits will be appropriately offset from the start of the volume.

Remarks

Volumes can be visualized as being organized into slices of width x height 2-D surfaces stacked up to make a width x height x depth volume. For more information, see Volume Texture Resources.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DVolume9::LockBox, IDirect3DVolumeTexture9::LockBox


D3DLOCKED_RECT Structure

Describes a locked rectangular region.

Syntax

typedef struct _D3DLOCKED_RECT {
    INT Pitch;
    void *pBits;
} D3DLOCKED_RECT;

Members

Pitch
Pitch of surface, in bytes.
pBits
Pointer to the locked bits. If a RECT World Wide Web link was provided to the IDirect3DSurface9::LockRect call, pBits will be appropriately offset from the start of the surface.

Remarks

The pitch for DXTn formats is different from what was returned in Microsoft DirectX 7.0. It now refers to the number of bytes in a row of blocks. For example, if you have a width of 16, then you will have a pitch of 4 blocks (4*8 for DXT1, 4*16 for DXT2-5.)

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DCubeTexture9::LockRect, IDirect3DSurface9::LockRect, IDirect3DTexture9::LockRect


D3DMATERIAL9 Structure

Specifies material properties.

Syntax

typedef struct _D3DMATERIAL9 {
    D3DCOLORVALUE Diffuse;
    D3DCOLORVALUE Ambient;
    D3DCOLORVALUE Specular;
    D3DCOLORVALUE Emissive;
    float Power;
} D3DMATERIAL9;

Members

Diffuse
Value specifying the diffuse color of the material. See D3DCOLORVALUE.
Ambient
Value specifying the ambient color of the material. See D3DCOLORVALUE.
Specular
Value specifying the specular color of the material. See D3DCOLORVALUE.
Emissive
Value specifying the emissive color of the material. See D3DCOLORVALUE.
Power
Floating-point value specifying the sharpness of specular highlights. The higher the value, the sharper the highlight.

Remarks

To turn off specular highlights, set D3DRS_SPECULARENABLE to FALSE, using D3DRENDERSTATETYPE. This is the fastest option because no specular highlights will be calculated.

For more information about using the lighting engine to calculate specular lighting, see Specular Lighting.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::GetMaterial, IDirect3DDevice9::SetMaterial


D3DMATRIX Structure

Describes a matrix.

Syntax

typedef struct _D3DMATRIX {
    union {
        struct {
            float        _11, _12, _13, _14;
            float        _21, _22, _23, _24;
            float        _31, _32, _33, _34;
            float        _41, _42, _43, _44;

        };
        float m[4][4];
    };
} D3DMATRIX;

Members

_ij
An array of floats that represent a 4x4 matrix, where i is the row number and j is the column number. For example, _34 means the same as [a34], the component in the third row and fourth column.

Remarks

In Microsoft Direct3D, the _34 element of a projection matrix cannot be a negative number. If your application needs to use a negative value in this location, it should scale the entire projection matrix by –1 instead.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::GetTransform, IDirect3DDevice9::MultiplyTransform, IDirect3DDevice9::SetTransform, D3DXMATRIX, Matrix Transforms


D3DPRESENT_PARAMETERS Structure

Describes the presentation parameters.

Syntax

typedef struct _D3DPRESENT_PARAMETERS_ {
    UINT BackBufferWidth, BackBufferHeight;
    D3DFORMAT BackBufferFormat;
    UINT BackBufferCount;
    D3DMULTISAMPLE_TYPE MultiSampleType;
    DWORD MultiSampleQuality;
    D3DSWAPEFFECT SwapEffect;
    HWND hDeviceWindow;
    BOOL Windowed;
    BOOL EnableAutoDepthStencil;
    D3DFORMAT AutoDepthStencilFormat;
    DWORD Flags;
    UINT FullScreen_RefreshRateInHz;
    UINT PresentationInterval;
} D3DPRESENT_PARAMETERS;

Members

BackBufferWidth, BackBufferHeight

Width and height of the new swap chain's back buffers, in pixels. If Windowed is FALSE (the presentation is full-screen), these values must equal the width and height of one of the enumerated display modes found through IDirect3D9::EnumAdapterModes. If Windowed is TRUE and either of these values is zero, the corresponding dimension of the client area of the hDeviceWindow (or the focus window, if hDeviceWindow is NULL) is taken.

BackBufferFormat

The back buffer format. For more information about formats, see D3DFORMAT. This value must be one of the render-target formats as validated by IDirect3D9::CheckDeviceType. You can use IDirect3DDevice9::GetDisplayMode to obtain the current format.

In fact, D3DFMT_UNKNOWN can be specified for the BackBufferFormat while in windowed mode. This tells the runtime to use the current display-mode format and eliminates the need to call IDirect3DDevice9::GetDisplayMode.

For windowed applications, the back buffer format no longer needs to match the display-mode format because color conversion can now be done by the hardware (if the hardware supports color conversion). The set of possible back buffer formats is constrained, but the runtime will allow any valid back buffer format to be presented to any desktop format. (There is the additional requirement that the device be operable in the desktop mode; devices typically do not operate in 8 bits per pixel modes.)

Full-screen applications cannot do color conversion.

BackBufferCount

This value can be 0 (or 1, 0 is treated as 1), 2, or 3. If the number of back buffers cannot be created, the runtime will fail the method call and fill this value with the number of back buffers that could be created. As a result, an application can call the method twice with the same D3DPRESENT_PARAMETERS structure and expect it to work the second time.

The method fails if one back buffer cannot be created. The value of BackBufferCount influences what set of swap effects are allowed. Specifically, any D3DSWAPEFFECT_COPY swap effect requires that there be exactly one back buffer.

MultiSampleType

Member of the D3DMULTISAMPLE_TYPE enumerated type. The value must be D3DMULTISAMPLE_NONE unless SwapEffect has been set to D3DSWAPEFFECT_DISCARD. Multisampling is supported only if the swap effect is D3DSWAPEFFECT_DISCARD.

MultiSampleQuality

Quality level. The valid range is between zero and one less than the level returned by pQualityLevels used by IDirect3D9::CheckDeviceMultiSampleType. Passing a larger value returns the error D3DERR_INVALIDCALL. Paired values of render targets or of depth stencil surfaces and D3DMULTISAMPLE_TYPE must match.

SwapEffect

Member of the D3DSWAPEFFECT enumerated type. The runtime will guarantee the implied semantics concerning buffer swap behavior; therefore, if Windowed is TRUE and SwapEffect is set to D3DSWAPEFFECT_FLIP, the runtime will create one extra back buffer and copy whichever becomes the front buffer at presentation time.

D3DSWAPEFFECT_COPY requires that BackBufferCount be set to 1.

D3DSWAPEFFECT_DISCARD will be enforced in the debug runtime by filling any buffer with noise after it is presented.

hDeviceWindow
The device window determines the location and size of the back buffer on screen. This is used by Microsoft Direct3D when the back buffer contents are copied to the front buffer during IDirect3DDevice9::Present.
  • For a full-screen application, this is a handle to the top window (which is the focus window).

    For applications that use multiple full-screen devices (such as a multimonitor system), exactly one device can use the focus window as the device window. All other devices must have unique device windows.
  • For a windowed-mode application, this handle will be the default target window for IDirect3DDevice9::Present. If this handle is NULL, the focus window will be taken.

Note that no attempt is made by the runtime to reflect user changes in window size. The back buffer is not implicitly reset when this window is reset. However, the IDirect3DDevice9::Present method does automatically track window position changes.

Windowed

TRUE if the application runs windowed; FALSE if the application runs full-screen.

EnableAutoDepthStencil

If this value is TRUE, Direct3D will manage depth buffers for the application. The device will create a depth-stencil buffer when it is created. The depth-stencil buffer will be automatically set as the render target of the device. When the device is reset, the depth-stencil buffer will be automatically destroyed and recreated in the new size.

If EnableAutoDepthStencil is TRUE, then AutoDepthStencilFormat must be a valid depth-stencil format.

AutoDepthStencilFormat

Member of the D3DFORMAT enumerated type. The format of the automatic depth-stencil surface that the device will create. This member is ignored unless EnableAutoDepthStencil is TRUE.

Flags

One of the D3DPRESENTFLAG constants.

FullScreen_RefreshRateInHz

The rate at which the display adapter refreshes the screen. The value depends on the mode in which the application is running:

  • For windowed mode, the refresh rate must be 0.
  • For full-screen mode, the refresh rate is one of the refresh rates returned by IDirect3D9::EnumAdapterModes.
PresentationInterval

The maximum rate at which the swap chain's back buffers can be presented to the front buffer. For a detailed explanation of the modes and the intervals that are supported, see D3DPRESENT.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3D9::CreateDevice, IDirect3DDevice9::CreateAdditionalSwapChain, IDirect3DDevice9::Present, IDirect3DDevice9::Reset


D3DPSHADERCAPS2_0 Structure

Pixel shader driver caps.

Syntax

typedef struct _D3DPSHADERCAPS2_0 {
    DWORD Caps;
    INT DynamicFlowControlDepth;
    INT NumTemps;
    INT StaticFlowControlDepth;
    INT NumInstructionSlots;
} D3DPSHADERCAPS2_0;

Members

Caps
Instruction predication is supported if this value is nonzero. See setp_comp.
DynamicFlowControlDepth
Either 0 or 24, which represents the depth of the dynamic flow control instruction nesting. See D3DPS20CAPS.
NumTemps
The number of temporary registers supported. See D3DPS20CAPS.
StaticFlowControlDepth
The depth of nesting of the loop/rep and call/callnz bool instructions. See D3DPS20CAPS.
NumInstructionSlots
The number of instruction slots supported. See D3DPS20CAPS.

Structure Information

Header | d3d9caps.h
Minimum operating systems | Windows 98

See Also

D3DCAPS9


D3DRANGE Structure

Defines a range.

Syntax

typedef struct _D3DRANGE {
    UINT Offset;
    UINT Size;
} D3DRANGE;

Members

Offset
Offset, in bytes.
Size
Size, in bytes.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98


D3DRASTER_STATUS Structure

Describes the raster status.

Syntax

typedef struct _D3DRASTER_STATUS {
    BOOL InVBlank;
    UINT ScanLine;
} D3DRASTER_STATUS;

Members

InVBlank
TRUE if the raster is in the vertical blank period. FALSE if the raster is not in the vertical blank period.
ScanLine
If InVBlank is FALSE, then this value is an integer roughly corresponding to the current scan line painted by the raster. Scan lines are numbered in the same way as Microsoft Direct3D surface coordinates: 0 is the top of the primary surface, extending to the value (height of the surface - 1) at the bottom of the display.

If InVBlank is TRUE, then this value is set to zero and can be ignored.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::GetRasterStatus


D3DRECT Structure

Defines a rectangle.

Syntax

typedef struct _D3DRECT {
    LONG x1, y1;
    LONG x2, y2;
} D3DRECT;

Members

x1, y1
Coordinates of the upper-left corner of the rectangle.
x2, y2
Coordinates of the lower-right corner of the rectangle.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::Clear


D3DRECTPATCH_INFO Structure

Describes a rectangular high-order patch.

Syntax

typedef struct _D3DRECTPATCH_INFO {
    UINT StartVertexOffsetWidth;
    UINT StartVertexOffsetHeight;
    UINT Width;
    UINT Height;
    UINT Stride;
    D3DBASISTYPE Basis;
    D3DDEGREETYPE Degree;
} D3DRECTPATCH_INFO;

Members

StartVertexOffsetWidth
Starting vertex offset width, in number of vertices.
StartVertexOffsetHeight
Starting vertex offset height, in number of vertices.
Width
Width of each vertex, in number of vertices.
Height
Height of each vertex, in number of vertices.
Stride
Width of the imaginary two-dimensional vertex array, which occupies the same space as the vertex buffer. For an example, see the diagram below.
Basis
Member of the D3DBASISTYPE enumerated type, defining the basis type for the rectangular high-order patch.

Value | Order supported | Width and height
D3DBASIS_BEZIER | Linear, cubic, and quintic | Width = height = (DWORD)order + 1
D3DBASIS_BSPLINE | Linear, cubic, and quintic | Width = height > (DWORD)order
D3DBASIS_INTERPOLATE | Cubic | Width = height > (DWORD)order

Degree
Member of the D3DDEGREETYPE enumerated type, defining the degree for the rectangular patch.

Remarks

The following diagram identifies the parameters that specify a rectangle patch.

Rectangular high-order patch with parameters that specify it

Each of the vertices in the vertex buffer is shown as a black dot. In this case, the vertex buffer has 20 vertices in it, 16 of which are in the rectangle patch. The stride is the number of vertices in the width of the vertex buffer, in this case five. The x offset to the first vertex is called the StartIndexVertexWidth and is in this case 1. The y offset to the first patch vertex is called the StartIndexVertexHeight and is in this case 0.

To render a stream of individual rectangular patches (non-mosaic), you should interpret your geometry as a long narrow (1×N) rectangular patch. The D3DRECTPATCH_INFO structure for such a strip (cubic Bézier) would be set up in the following manner.

D3DRECTPATCH_INFO RectInfo;

RectInfo.Width = 4;
RectInfo.Height = 4;
RectInfo.Stride = 4;
RectInfo.Basis = D3DBASIS_BEZIER;
RectInfo.Order = D3DORDER_CUBIC;
RectInfo.StartVertexOffsetWidth = 0;
RectInfo.StartVertexOffsetHeight = 4*i;  // The variable i is the index of the
                                         //   patch you want to render.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::DrawRectPatch, D3DXTessellateRectPatch


D3DRESOURCESTATS Structure

Resource statistics gathered by the D3DDEVINFO_RESOURCEMANAGER when using the asynchronous query mechanism.

Syntax

typedef struct D3DRESOURCESTATS {
    BOOL bThrashing;
    DWORD ApproxBytesDownloaded;
    DWORD NumEvicts;
    DWORD NumVidCreates;
    DWORD LastPri;
    DWORD NumUsed;
    DWORD NumUsedInVidMem;
    DWORD WorkingSet;
    DWORD WorkingSetBytes;
    DWORD TotalManaged;
    DWORD TotalBytes;
} D3DRESOURCESTATS;

Members

bThrashing
Indicates if thrashing is occurring.
ApproxBytesDownloaded
Approximate number of bytes downloaded by the resource manager.
NumEvicts
Number of objects evicted.
NumVidCreates
Number of objects created in video memory.
LastPri
Priority of last object evicted.
NumUsed
Number of objects set to the device.
NumUsedInVidMem
Number of objects set to the device, which are already in video memory.
WorkingSet
Number of objects in video memory.
WorkingSetBytes
Number of bytes in video memory.
TotalManaged
Total number of managed objects.
TotalBytes
Total number of bytes of managed objects.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

Asynchronous Notification


D3DSURFACE_DESC Structure

Describes a surface.

Syntax

typedef struct _D3DSURFACE_DESC {
    D3DFORMAT Format;
    D3DRESOURCETYPE Type;
    DWORD Usage;
    D3DPOOL Pool;
    D3DMULTISAMPLE_TYPE MultiSampleType;
    DWORD MultiSampleQuality;
    UINT Width;
    UINT Height;
} D3DSURFACE_DESC;

Members

Format
Member of the D3DFORMAT enumerated type, describing the surface format.
Type
Member of the D3DRESOURCETYPE enumerated type, identifying this resource as a surface.
Usage
Either the D3DUSAGE_DEPTHSTENCIL or D3DUSAGE_RENDERTARGET values. For more information, see D3DUSAGE.
Pool
Member of the D3DPOOL enumerated type, specifying the class of memory allocated for this surface.
MultiSampleType
Member of the D3DMULTISAMPLE_TYPE enumerated type, specifying the levels of full-scene multisampling supported by the surface.
MultiSampleQuality
Quality level. The valid range is between zero and one less than the level returned by pQualityLevels used by IDirect3D9::CheckDeviceMultiSampleType. Passing a larger value returns the error, D3DERR_INVALIDCALL. The MultisampleQuality values of paired render targets, depth stencil surfaces and the MultiSample type must all match.
Width
Width of the surface, in pixels.
Height
Height of the surface, in pixels.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DCubeTexture9::GetLevelDesc, IDirect3DSurface9::GetDesc, IDirect3DTexture9::GetLevelDesc


D3DTRIPATCH_INFO Structure

Describes a triangular high-order patch.

Syntax

typedef struct _D3DTRIPATCH_INFO {
    UINT StartVertexOffset;
    UINT NumVertices;
    D3DBASISTYPE Basis;
    D3DDEGREETYPE Degree;
} D3DTRIPATCH_INFO;

Members

StartVertexOffset
Starting vertex offset, in number of vertices.
NumVertices
Number of vertices.
Basis
Member of the D3DBASISTYPE enumerated type, which defines the basis type for the triangular high-order patch. The only valid value for this member is D3DBASIS_BEZIER.
Degree

Member of the D3DDEGREETYPE enumerated type, defining the degree type for the triangular high-order patch.

Value | Number of vertices
D3DDEGREE_CUBIC | 10
D3DDEGREE_LINEAR | 3
D3DDEGREE_QUADRATIC | N/A
D3DDEGREE_QUINTIC | 21

N/A - Not available. Not supported.

Remarks

For example, the following diagram identifies the vertex order and segment numbers for a cubic Bézier triangle patch. The vertex order determines the segment numbers used by IDirect3DDevice9::DrawTriPatch. The offset is the number of bytes to the first triangle patch vertex in the vertex buffer.

Triangular high-order patch with nine vertices

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::DrawTriPatch, D3DXTessellateTriPatch


D3DVECTOR Structure

Defines a vector.

Syntax

typedef struct _D3DVECTOR {
    float x, y, z;
} D3DVECTOR;

Members

x, y, z
Floating-point values describing the vector.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98


D3DVERTEXBUFFER_DESC Structure

Describes a vertex buffer.

Syntax

typedef struct _D3DVERTEXBUFFER_DESC {
    D3DFORMAT Format;
    D3DRESOURCETYPE Type;
    DWORD Usage;
    D3DPOOL Pool;
    UINT Size;
    DWORD FVF;
} D3DVERTEXBUFFER_DESC;

Members

Format
Member of the D3DFORMAT enumerated type, describing the surface format of the vertex buffer data.
Type
Member of the D3DRESOURCETYPE enumerated type, identifying this resource as a vertex buffer.
Usage
Combination of one or more D3DUSAGE flags.
Pool
Member of the D3DPOOL enumerated type, specifying the class of memory allocated for this vertex buffer.
Size
Size of the vertex buffer, in bytes.
FVF
Combination of D3DFVF that describes the vertex format of the vertices in this buffer.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DVertexBuffer9::GetDesc


D3DVERTEXELEMENT9 Structure

Defines the vertex data layout. Each vertex can contain one or more data types and each data type is described by a vertex element.

Syntax

typedef struct _D3DVERTEXELEMENT9 {
    WORD Stream;
    WORD Offset;
    BYTE Type;
    BYTE Method;
    BYTE Usage;
    BYTE UsageIndex;
} D3DVERTEXELEMENT9;

Members

Stream
Stream number.
Offset
Offset from the beginning of the vertex data to the data associated with the particular data type.
Type
The data type, specified as a D3DDECLTYPE. One of several predefined types that define the data size. Some methods have an implied type.
Method
The method specifies the tessellator processing, which determines how the tessellator interprets (or operates) on the vertex data. For more information, see D3DDECLMETHOD.
Usage
Defines what the data will be used for; that is, the interoperability between vertex data layouts and vertex shaders. Each usage acts to bind a vertex declaration to a vertex shader. In some cases, they have a special interpretation. For example, an element that specifies D3DDECLUSAGE_NORMAL or D3DDECLUSAGE_POSITION is used by the N-patch tessellator to set up tessellation. See D3DDECLUSAGE for a list of the available semantics. D3DDECLUSAGE_TEXCOORD can be used for user-defined fields (which don't have an existing usage defined).
UsageIndex
Modifies the usage data to allow the user to specify multiple usage types.

Remarks

Vertex data is defined using an array of D3DVERTEXELEMENT9 structures. Use D3DDECL_END to declare the last element in the declaration.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

Vertex Declaration


D3DVIEWPORT9 Structure

Defines the window dimensions of a render-target surface onto which a 3-D volume projects.

Syntax

typedef struct _D3DVIEWPORT9 {
    DWORD X;
    DWORD Y;
    DWORD Width;
    DWORD Height;
    float MinZ;
    float MaxZ;
} D3DVIEWPORT9;

Members

X
Pixel coordinate of the upper-left corner of the viewport on the render-target surface. Unless you want to render to a subset of the surface, this member can be set to 0.
Y
Pixel coordinate of the upper-left corner of the viewport on the render-target surface. Unless you want to render to a subset of the surface, this member can be set to 0.
Width
Width dimension of the clip volume, in pixels. Unless you are rendering only to a subset of the surface, this member should be set to the width dimension of the render-target surface.
Height
Height dimension of the clip volume, in pixels. Unless you are rendering only to a subset of the surface, this member should be set to the height dimension of the render-target surface.
MinZ
Together with MaxZ, value describing the range of depth values into which a scene is to be rendered, the minimum and maximum values of the clip volume. Most applications set this value to 0.0. Clipping is performed after applying the projection matrix.
MaxZ
Together with MinZ, value describing the range of depth values into which a scene is to be rendered, the minimum and maximum values of the clip volume. Most applications set this value to 1.0. Clipping is performed after applying the projection matrix.

Remarks

The X, Y, Width, and Height members describe the position and dimensions of the viewport on the render-target surface. Usually, applications render to the entire target surface; when rendering on a 640×480 surface, these members should be 0, 0, 640, and 480, respectively. The MinZ and MaxZ are typically set to 0.0 and 1.0 but can be set to other values to achieve specific effects. For example, you might set them both to 0.0 to force the system to render objects to the foreground of a scene, or both to 1.0 to force the objects into the background.

When the viewport parameters for a device change (because of a call to the IDirect3DDevice9::SetViewport method), the driver builds a new transformation matrix.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::GetViewport, IDirect3DDevice9::SetViewport


D3DVOLUME_DESC Structure

Describes a volume.

Syntax

typedef struct _D3DVOLUME_DESC {
    D3DFORMAT Format;
    D3DRESOURCETYPE Type;
    DWORD Usage;
    D3DPOOL Pool;
    UINT Width;
    UINT Height;
    UINT Depth;
} D3DVOLUME_DESC;

Members

Format
Member of the D3DFORMAT enumerated type, describing the surface format of the volume.
Type
Member of the D3DRESOURCETYPE enumerated type, identifying this resource as a volume.
Usage
Currently not used. Always returned as 0.
Pool
Member of the D3DPOOL enumerated type, specifying the class of memory allocated for this volume.
Width
Width of the volume, in pixels.
Height
Height of the volume, in pixels.
Depth
Depth of the volume, in pixels.

Structure Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DVolume9::GetDesc, IDirect3DVolumeTexture9::GetLevelDesc


D3DVSHADERCAPS2_0 Structure

Vertex shader caps.

Syntax

typedef struct _D3DVSHADERCAPS2_0 {
    DWORD Caps;
    INT DynamicFlowControlDepth;
    INT NumTemps;
    INT StaticFlowControlDepth;
} D3DVSHADERCAPS2_0;

Members

Caps
Instruction predication is supported if this value is nonzero. See setp_comp.
DynamicFlowControlDepth
Either 0 or 24, which represents the depth of the dynamic flow control instruction nesting. See D3DVS20CAPS.
NumTemps
The number of temporary registers supported. See D3DVS20CAPS.
StaticFlowControlDepth
The depth of nesting of the loop/rep and call/callnz bool instructions. See D3DVS20CAPS.

Structure Information

Header | d3d9caps.h
Minimum operating systems | Windows 98

See Also

D3DPSHADERCAPS2_0, D3DCAPS9


PALETTEENTRY Structure

Specifies the color and usage of an entry in a logical palette.

Syntax

typedef struct tagPALETTEENTRY {
    BYTE peRed;
    BYTE peGreen;
    BYTE peBlue;
    BYTE peFlags;
} PALETTEENTRY;

Members

peRed
The red intensity value for the palette entry.
peGreen
The green intensity value for the palette entry.
peBlue
The blue intensity value for the palette entry.
peFlags
The alpha intensity value for the palette entry. Note that as of Microsoft DirectX 8.0, this member is treated differently than documented in the Microsoft Platform Software Development Kit (SDK).

Structure Information

Header | wingdi.h
Minimum operating systems | Windows 98


Enumerated Types
Microsoft DirectX 9.0 SDK Update (October 2004)

Enumerated Types

This section contains information about the following enumerated types used with Microsoft Direct3D.

Enumerations

  • D3DBACKBUFFER_TYPE
  • D3DBASISTYPE
  • D3DBLEND
  • D3DBLENDOP
  • D3DCMPFUNC
  • D3DCUBEMAP_FACES
  • D3DCULL
  • D3DDEBUGMONITORTOKENS
  • D3DDECLMETHOD
  • D3DDECLTYPE
  • D3DDECLUSAGE
  • D3DDEGREETYPE
  • D3DDEVTYPE
  • D3DERR
  • D3DFILLMODE
  • D3DFOGMODE
  • D3DFORMAT
  • D3DLIGHTTYPE
  • D3DMATERIALCOLORSOURCE
  • D3DMULTISAMPLE_TYPE
  • D3DPATCHEDGESTYLE
  • D3DPOOL
  • D3DPRIMITIVETYPE
  • D3DQUERYTYPE
  • D3DRENDERSTATETYPE
  • D3DRESOURCETYPE
  • D3DSAMPLER_TEXTURE_TYPE
  • D3DSAMPLERSTATETYPE
  • D3DSHADEMODE
  • D3DSTATEBLOCKTYPE
  • D3DSTENCILOP
  • D3DSWAPEFFECT
  • D3DTEXTUREADDRESS
  • D3DTEXTUREFILTERTYPE
  • D3DTEXTUREOP
  • D3DTEXTURESTAGESTATETYPE
  • D3DTEXTURETRANSFORMFLAGS
  • D3DTRANSFORMSTATETYPE
  • D3DVERTEXBLENDFLAGS
  • Return Values
  • D3DZBUFFERTYPE


D3DBACKBUFFER_TYPE Enumerated Type

Defines constants that describe the type of back buffer.

Syntax

typedef enum _D3DBACKBUFFER_TYPE {
    D3DBACKBUFFER_TYPE_MONO = 0,
    D3DBACKBUFFER_TYPE_LEFT = 1,
    D3DBACKBUFFER_TYPE_RIGHT = 2,
    D3DBACKBUFFER_TYPE_FORCE_DWORD = 0x7fffffff
} D3DBACKBUFFER_TYPE;

Constants

D3DBACKBUFFER_TYPE_MONO

Specifies a nonstereo swap chain.

D3DBACKBUFFER_TYPE_LEFT

Specifies the left side of a stereo pair in a swap chain.

D3DBACKBUFFER_TYPE_RIGHT

Specifies the right side of a stereo pair in a swap chain.

D3DBACKBUFFER_TYPE_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Microsoft DirectX 9.0 does not support stereo view, so Microsoft Direct3D does not use the D3DBACKBUFFER_TYPE_LEFT and D3DBACKBUFFER_TYPE_RIGHT values of this enumerated type.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::GetBackBuffer, IDirect3DSwapChain9::GetBackBuffer


D3DBASISTYPE Enumerated Type

Defines the basis type of a high-order patch surface.

Syntax

typedef enum _D3DBASISTYPE {
    D3DBASIS_BEZIER = 0,
    D3DBASIS_BSPLINE = 1,
    D3DBASIS_CATMULL_ROM = 2,
    D3DBASIS_FORCE_DWORD = 0x7fffffff
} D3DBASISTYPE;

Constants

D3DBASIS_BEZIER

Input vertices are treated as a series of Bézier patches. The number of vertices specified must be divisible by 3 + 1. Portions of the mesh beyond this criterion will not be rendered. Full continuity is assumed between sub-patches in the interior of the surface rendered by each call. Only the vertices at the corners of each sub-patch are guaranteed to lie on the resulting surface.

D3DBASIS_BSPLINE

Input vertices are treated as control points of a B-spline surface. The number of apertures rendered is two fewer than the number of apertures in that direction. In general, the generated surface does not contain the control vertices specified.

D3DBASIS_CATMULL_ROM

An interpolating basis defines the surface so that the surface goes through all the input vertices specified. In Microsoft DirectX 8.0, this was D3DBASIS_INTERPOLATE.

D3DBASIS_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The members of D3DBASISTYPE specify the formulation to be used in evaluating the high-order patch surface primitive during tessellation.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DRECTPATCH_INFO, D3DTRIPATCH_INFO


D3DBLEND Enumerated Type

Defines the supported blend mode.

Syntax

typedef enum _D3DBLEND {
    D3DBLEND_ZERO = 1,
    D3DBLEND_ONE = 2,
    D3DBLEND_SRCCOLOR = 3,
    D3DBLEND_INVSRCCOLOR = 4,
    D3DBLEND_SRCALPHA = 5,
    D3DBLEND_INVSRCALPHA = 6,
    D3DBLEND_DESTALPHA = 7,
    D3DBLEND_INVDESTALPHA = 8,
    D3DBLEND_DESTCOLOR = 9,
    D3DBLEND_INVDESTCOLOR = 10,
    D3DBLEND_SRCALPHASAT = 11,
    D3DBLEND_BOTHSRCALPHA = 12,
    D3DBLEND_BOTHINVSRCALPHA = 13,
    D3DBLEND_BLENDFACTOR = 14,
    D3DBLEND_INVBLENDFACTOR = 15,
    D3DBLEND_FORCE_DWORD = 0x7fffffff
} D3DBLEND;

Constants

D3DBLEND_ZERO

Blend factor is (0, 0, 0, 0).

D3DBLEND_ONE

Blend factor is (1, 1, 1, 1).

D3DBLEND_SRCCOLOR

Blend factor is (Rs, Gs, Bs, As).

D3DBLEND_INVSRCCOLOR

Blend factor is (1 - Rs, 1 - Gs, 1 - Bs, 1 - As).

D3DBLEND_SRCALPHA

Blend factor is (As, As, As, As).

D3DBLEND_INVSRCALPHA

Blend factor is ( 1 - As, 1 - As, 1 - As, 1 - As).

D3DBLEND_DESTALPHA

Blend factor is (Ad, Ad, Ad, Ad).

D3DBLEND_INVDESTALPHA

Blend factor is (1 - Ad, 1 - Ad, 1 - Ad, 1 - Ad).

D3DBLEND_DESTCOLOR

Blend factor is (Rd, Gd, Bd, Ad).

D3DBLEND_INVDESTCOLOR

Blend factor is (1 - Rd, 1 - Gd, 1 - Bd, 1 - Ad).

D3DBLEND_SRCALPHASAT

Blend factor is (f, f, f, 1); f = min(As, 1 - Ad).

D3DBLEND_BOTHSRCALPHA

Obsolete. For Microsoft DirectX 6.0 and later, you can achieve the same effect by setting the source and destination blend factors to D3DBLEND_SRCALPHA and D3DBLEND_INVSRCALPHA in separate calls.

D3DBLEND_BOTHINVSRCALPHA

Source blend factor is (1 - As, 1 - As, 1 - As, 1 - As), and destination blend factor is (As, As, As, As); the destination blend selection is overridden. This blend mode is supported only for the D3DRS_SRCBLEND render state.

D3DBLEND_BLENDFACTOR

Constant color blending factor used by the frame-buffer blender. This blend mode is supported only if D3DPBLEND_BLENDFACTOR is on.

D3DBLEND_INVBLENDFACTOR

Inverted constant color-blending factor used by the frame-buffer blender. This blend mode is supported only if the D3DPBLEND_BLENDFACTOR bit is set in the SrcBlendCaps or DestBlendCaps members of D3DCAPS9.

D3DBLEND_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

In the member descriptions above, the RGBA values of the source and destination are indicated by the s and d subscripts.

The values in this enumerated type are used by the following render states:
  • D3DRS_SRCBLEND
  • D3DRS_DESTBLEND
  • D3DRS_SRCBLENDALPHA
  • D3DRS_DESTBLENDALPHA

See D3DRENDERSTATETYPE

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98


D3DBLENDOP Enumerated Type

Defines the supported blend operations. See Remarks for definitions of terms.

Syntax

typedef enum _D3DBLENDOP {
    D3DBLENDOP_ADD = 1,
    D3DBLENDOP_SUBTRACT = 2,
    D3DBLENDOP_REVSUBTRACT = 3,
    D3DBLENDOP_MIN = 4,
    D3DBLENDOP_MAX = 5,
    D3DBLENDOP_FORCE_DWORD = 0x7fffffff
} D3DBLENDOP;

Constants

D3DBLENDOP_ADD

The result is the destination added to the source.

Result = Source + Destination

D3DBLENDOP_SUBTRACT

The result is the destination subtracted from to the source.

Result = Source - Destination

D3DBLENDOP_REVSUBTRACT

The result is the source subtracted from the destination.

Result = Destination - Source

D3DBLENDOP_MIN

The result is the minimum of the source and destination.

Result = MIN(Source, Destination)

D3DBLENDOP_MAX

The result is the maximum of the source and destination.

Result = MAX(Source, Destination)

D3DBLENDOP_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Source, Destination, and Result are defined as:

Term | Type | Description
Source | Input | Color of the source pixel before the operation.
Destination | Input | Color of the pixel in the destination buffer before the operation.
Result | Output | Returned value that is the blended color resulting from the operation.

This enumerated type defines values used by the following render states:

  • D3DRS_BLENDOP
  • D3DRS_BLENDOPALPHA

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DCAPS9, D3DRENDERSTATETYPE


D3DCMPFUNC Enumerated Type

Defines the supported compare functions.

Syntax

typedef enum _D3DCMPFUNC {
    D3DCMP_NEVER = 1,
    D3DCMP_LESS = 2,
    D3DCMP_EQUAL = 3,
    D3DCMP_LESSEQUAL = 4,
    D3DCMP_GREATER = 5,
    D3DCMP_NOTEQUAL = 6,
    D3DCMP_GREATEREQUAL = 7,
    D3DCMP_ALWAYS = 8,
    D3DCMP_FORCE_DWORD = 0x7fffffff
} D3DCMPFUNC;

Constants

D3DCMP_NEVER

Always fail the test.

D3DCMP_LESS

Accept the new pixel if its value is less than the value of the current pixel.

D3DCMP_EQUAL

Accept the new pixel if its value equals the value of the current pixel.

D3DCMP_LESSEQUAL

Accept the new pixel if its value is less than or equal to the value of the current pixel.

D3DCMP_GREATER

Accept the new pixel if its value is greater than the value of the current pixel.

D3DCMP_NOTEQUAL

Accept the new pixel if its value does not equal the value of the current pixel.

D3DCMP_GREATEREQUAL

Accept the new pixel if its value is greater than or equal to the value of the current pixel.

D3DCMP_ALWAYS

Always pass the test.

D3DCMP_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The values in this enumerated type define the supported compare functions for the D3DRS_ZFUNC, D3DRS_ALPHAFUNC, and D3DRS_STENCILFUNC render states.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DRENDERSTATETYPE


D3DCUBEMAP_FACES Enumerated Type

Defines the faces of a cubemap.

Syntax

typedef enum _D3DCUBEMAP_FACES {
    D3DCUBEMAP_FACE_POSITIVE_X = 0,
    D3DCUBEMAP_FACE_NEGATIVE_X = 1,
    D3DCUBEMAP_FACE_POSITIVE_Y = 2,
    D3DCUBEMAP_FACE_NEGATIVE_Y = 3,
    D3DCUBEMAP_FACE_POSITIVE_Z = 4,
    D3DCUBEMAP_FACE_NEGATIVE_Z = 5,
    D3DCUBEMAP_FACE_FORCE_DWORD = 0xffffffff
} D3DCUBEMAP_FACES;

Constants

D3DCUBEMAP_FACE_POSITIVE_X

Positive x-face of the cubemap.

D3DCUBEMAP_FACE_NEGATIVE_X

Negative x-face of the cubemap.

D3DCUBEMAP_FACE_POSITIVE_Y

Positive y-face of the cubemap.

D3DCUBEMAP_FACE_NEGATIVE_Y

Negative y-face of the cubemap.

D3DCUBEMAP_FACE_POSITIVE_Z

Positive z-face of the cubemap.

D3DCUBEMAP_FACE_NEGATIVE_Z

Negative z-face of the cubemap.

D3DCUBEMAP_FACE_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DCubeTexture9::AddDirtyRect, IDirect3DCubeTexture9::GetCubeMapSurface, IDirect3DCubeTexture9::LockRect, IDirect3DCubeTexture9::UnlockRect


D3DCULL Enumerated Type

Defines the supported culling modes.

Syntax

typedef enum _D3DCULL {
    D3DCULL_NONE = 1,
    D3DCULL_CW = 2,
    D3DCULL_CCW = 3,
    D3DCULL_FORCE_DWORD = 0x7fffffff
} D3DCULL;

Constants

D3DCULL_NONE

Do not cull back faces.

D3DCULL_CW

Cull back faces with clockwise vertices.

D3DCULL_CCW

Cull back faces with counterclockwise vertices.

D3DCULL_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The values in this enumerated type are used by the D3DRS_CULLMODE render state. The culling modes define how back faces are culled when rendering a geometry.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DCAPS9, D3DRENDERSTATETYPE


D3DDEBUGMONITORTOKENS Enumerated Type

Defines the debug monitor tokens.

Syntax

typedef enum _D3DDEBUGMONITORTOKENS {
    D3DDMT_ENABLE = 0,
    D3DDMT_DISABLE = 1,
    D3DDMT_FORCE_DWORD = 0x7fffffff
} D3DDEBUGMONITORTOKENS;

Constants

D3DDMT_ENABLE

Enable the debug monitor.

D3DDMT_DISABLE

Disable the debug monitor.

D3DDMT_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The values in this enumerated type are used by the D3DRS_DEBUGMONITORTOKEN render state and are only relevant for debug builds.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DRENDERSTATETYPE


D3DDECLMETHOD Enumerated Type

Defines the vertex declaration method which is a predefined operation performed by the tessellator (or any procedural geometry routine on the vertex data during tessellation).

Syntax

typedef enum _D3DDECLMETHOD {
    D3DDECLMETHOD_DEFAULT = 0,
    D3DDECLMETHOD_PARTIALU = 1,
    D3DDECLMETHOD_PARTIALV = 2,
    D3DDECLMETHOD_CROSSUV = 3,
    D3DDECLMETHOD_UV = 4,
    D3DDECLMETHOD_LOOKUP = 5,
    D3DDECLMETHOD_LOOKUPPRESAMPLED = 6
} D3DDECLMETHOD;

Constants

D3DDECLMETHOD_DEFAULT

Default value. The tessellator copies the vertex data (spline data for patches) as is, with no additional calculations. When the tessellator is used, this element is interpolated. Otherwise vertex data is copied into the input register. The input and output type can be any value, but are always the same type.

D3DDECLMETHOD_PARTIALU

Computes the tangent at a point on the rectangle or triangle patch in the U direction. The input type can be one of the following:

  • D3DDECLTYPE_D3DCOLOR
  • D3DDECLTYPE_FLOAT3
  • D3DDECLTYPE_FLOAT4
  • D3DDECLTYPE_SHORT4
  • D3DDECLTYPE_UBYTE4
The output type is always D3DDECLTYPE_FLOAT3.

D3DDECLMETHOD_PARTIALV

Computes the tangent at a point on the rectangle or triangle patch in the V direction. The input type can be one of the following:

  • D3DDECLTYPE_D3DCOLOR
  • D3DDECLTYPE_FLOAT3
  • D3DDECLTYPE_FLOAT4
  • D3DDECLTYPE_SHORT4
  • D3DDECLTYPE_UBYTE4
The output type is always D3DDECLTYPE_FLOAT3.

D3DDECLMETHOD_CROSSUV

Computes the normal at a point on the rectangle or triangle patch by taking the cross product of two tangents. The input type can be one of the following:

  • D3DDECLTYPE_D3DCOLOR
  • D3DDECLTYPE_FLOAT3
  • D3DDECLTYPE_FLOAT4
  • D3DDECLTYPE_SHORT4
  • D3DDECLTYPE_UBYTE4
The output type is always D3DDECLTYPE_FLOAT3.

D3DDECLMETHOD_UV

Copy out the U, V values at a point on the rectangle or triangle patch. This results in a 2-D float. The input type must be set to D3DDECLTYPE_UNUSED. The output data type is always D3DDECLTYPE_FLOAT2. The input stream and offset are also unused (but must be set to 0).

D3DDECLMETHOD_LOOKUP

Look up a displacement map. The input type can be one of the following:

  • D3DDECLTYPE_FLOAT2
  • D3DDECLTYPE_FLOAT3
  • D3DDECLTYPE_FLOAT4
Only the .x and .y components are used for the texture map lookup. The output type is always D3DDECLTYPE_FLOAT1. The device must support displacement mapping. For more information about displacement mapping, see Displacement Mapping. This constant is supported only by the programmable pipeline on N-patch data, if N-patches are enabled.

D3DDECLMETHOD_LOOKUPPRESAMPLED

Look up a presampled displacement map. The input type must be set to D3DDECLTYPE_UNUSED; the stream index and the stream offset must be set to 0. The output type for this operation is always D3DDECLTYPE_FLOAT1. The device must support displacement mapping. For more information about displacement mapping, see Displacement Mapping. This constant is supported only by the programmable pipeline on N-patch data, if N-patches are enabled. This method can be used only with D3DDECLUSAGE_SAMPLE.

Remarks

The tessellator looks at the method to determine what data to calculate from the vertex data during tessellation. Mesh data should use the default value. Patches can use any of the other implemented types.

Vertex data is declared with an array of D3DVERTEXELEMENT9 structures. Each element in the array contains a vertex declaration method.

In addition to using D3DDECLMETHOD_DEFAULT, a normal mesh can use D3DDECLMETHOD_LOOKUP and D3DDECLMETHOD_LOOKUPPRESAMPLED methods when N-patches are enabled.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98


D3DDECLTYPE Enumerated Type

Defines a vertex declaration data type.

Syntax

typedef enum _D3DDECLTYPE {
    D3DDECLTYPE_FLOAT1 = 0,
    D3DDECLTYPE_FLOAT2 = 1,
    D3DDECLTYPE_FLOAT3 = 2,
    D3DDECLTYPE_FLOAT4 = 3,
    D3DDECLTYPE_D3DCOLOR = 4,
    D3DDECLTYPE_UBYTE4 = 5,
    D3DDECLTYPE_SHORT2 = 6,
    D3DDECLTYPE_SHORT4 = 7,
    D3DDECLTYPE_UBYTE4N = 8,
    D3DDECLTYPE_SHORT2N = 9,
    D3DDECLTYPE_SHORT4N = 10,
    D3DDECLTYPE_USHORT2N = 11,
    D3DDECLTYPE_USHORT4N = 12,
    D3DDECLTYPE_UDEC3 = 13,
    D3DDECLTYPE_DEC3N = 14,
    D3DDECLTYPE_FLOAT16_2 = 15,
    D3DDECLTYPE_FLOAT16_4 = 16,
    D3DDECLTYPE_UNUSED = 17
} D3DDECLTYPE;

Constants

D3DDECLTYPE_FLOAT1

One-component float expanded to (float, 0, 0, 1).

D3DDECLTYPE_FLOAT2

Two-component float expanded to (float, float, 0, 1).

D3DDECLTYPE_FLOAT3

Three-component float expanded to (float, float, float, 1).

D3DDECLTYPE_FLOAT4

Four-component float expanded to (float, float, float, float).

D3DDECLTYPE_D3DCOLOR

Four-component, packed, unsigned bytes mapped to 0 to 1 range. Input is a D3DCOLOR and is expanded to RGBA order.

D3DDECLTYPE_UBYTE4

Four-component, unsigned byte.

D3DDECLTYPE_SHORT2

Two-component, signed short expanded to (value, value, 0, 1).

D3DDECLTYPE_SHORT4

Four-component, signed short expanded to (value, value, value, value).

D3DDECLTYPE_UBYTE4N

Four-component byte with each byte normalized by dividing with 255.0f.

D3DDECLTYPE_SHORT2N

Normalized, two-component, signed short, expanded to (first short/32767.0, second short/32767.0, 0, 1).

D3DDECLTYPE_SHORT4N

Normalized, four-component, signed short, expanded to (first short/32767.0, second short/32767.0, third short/32767.0, fourth short/32767.0).

D3DDECLTYPE_USHORT2N

Normalized, two-component, unsigned short, expanded to (first short/65535.0, short short/65535.0, 0, 1).

D3DDECLTYPE_USHORT4N

Normalized, four-component, unsigned short, expanded to (first short/65535.0, second short/65535.0, third short/65535.0, fourth short/65535.0).

D3DDECLTYPE_UDEC3

Three-component, unsigned, 10 10 10 format expanded to (value, value, value, 1).

D3DDECLTYPE_DEC3N

Three-component, signed, 10 10 10 format normalized and expanded to (v[0]/511.0, v[1]/511.0, v[2]/511.0, 1).

D3DDECLTYPE_FLOAT16_2

Two-component, 16-bit, floating point expanded to (value, value, 0, 1).

D3DDECLTYPE_FLOAT16_4

Four-component, 16-bit, floating point expanded to (value, value, value, value).

D3DDECLTYPE_UNUSED

Type field in the declaration is unused. This is designed for use with D3DDECLMETHOD_UV and D3DDECLMETHOD_LOOKUPPRESAMPLED.

Remarks

Vertex data is declared with an array of D3DVERTEXELEMENT9 structures. Each element in the array contains a vertex declaration data type.

Use the DirectX Caps Viewer tool to see which types are supported on your device.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DDECLMETHOD


D3DDECLUSAGE Enumerated Type

Identifies the intended use of vertex data.

Syntax

typedef enum _D3DDECLUSAGE {
    D3DDECLUSAGE_POSITION = 0,
    D3DDECLUSAGE_BLENDWEIGHT = 1,
    D3DDECLUSAGE_BLENDINDICES = 2,
    D3DDECLUSAGE_NORMAL = 3,
    D3DDECLUSAGE_PSIZE = 4,
    D3DDECLUSAGE_TEXCOORD = 5,
    D3DDECLUSAGE_TANGENT = 6,
    D3DDECLUSAGE_BINORMAL = 7,
    D3DDECLUSAGE_TESSFACTOR = 8,
    D3DDECLUSAGE_POSITIONT = 9,
    D3DDECLUSAGE_COLOR = 10,
    D3DDECLUSAGE_FOG = 11,
    D3DDECLUSAGE_DEPTH = 12,
    D3DDECLUSAGE_SAMPLE = 13
} D3DDECLUSAGE;

Constants

D3DDECLUSAGE_POSITION

Position data ranging from (-1,-1) to (1,1). Use D3DDECLUSAGE_POSITION with a usage index of 0 to specify untransformed position for fixed function vertex processing and the n-patch tessellator. Use D3DDECLUSAGE_POSITION with a usage index of 1 to specify untransformed position in the fixed function vertex shader for vertex tweening.

D3DDECLUSAGE_BLENDWEIGHT

Blending weight data. Use D3DDECLUSAGE_BLENDWEIGHT with a usage index of 0 to specify the blend weights used in indexed and nonindexed vertex blending.

D3DDECLUSAGE_BLENDINDICES

Blending indices data. Use D3DDECLUSAGE_BLENDINDICES with a usage index of 0 to specify matrix indices for indexed paletted skinning.

D3DDECLUSAGE_NORMAL

Vertex normal data. Use D3DDECLUSAGE_NORMAL with a usage index of 0 to specify vertex normals for fixed function vertex processing and the n-patch tessellator. Use D3DDECLUSAGE_NORMAL with a usage index of 1 to specify vertex normals for fixed function vertex processing for vertex tweening.

D3DDECLUSAGE_PSIZE

Point size data. Use D3DDECLUSAGE_PSIZE with a usage index of 0 to specify the point-size attribute used by the setup engine of the rasterizer to expand a point into a quad for the point-sprite functionality.

D3DDECLUSAGE_TEXCOORD

Texture coordinate data. Use D3DDECLUSAGE_TEXCOORD, n to specify texture coordinates in fixed function vertex processing and in pixel shaders prior to ps_3_0. These can be used to pass user defined data.

D3DDECLUSAGE_TANGENT

Vertex tangent data.

D3DDECLUSAGE_BINORMAL

Vertex binormal data.

D3DDECLUSAGE_TESSFACTOR

Single positive floating point value. Use D3DDECLUSAGE_TESSFACTOR with a usage index of 0 to specify a tessellation factor used in the tessellation unit to control the rate of tessellation. For more information about the data type, see D3DDECLTYPE_FLOAT1.

D3DDECLUSAGE_POSITIONT

Vertex data contains transformed position data ranging from (0,0) to (viewport width, viewport height). Use D3DDECLUSAGE_POSITIONT with a usage index of 0 to specify transformed position. When a declaration containing this is set, the pipeline does not perform vertex processing.

D3DDECLUSAGE_COLOR

Vertex data contains diffuse or specular color. Use D3DDECLUSAGE_COLOR with a usage index of 0 to specify the diffuse color in the fixed function vertex shader and pixel shaders prior to ps_3_0. Use D3DDECLUSAGE_COLOR with a usage index of 1 to specify the specular color in the fixed function vertex shader and pixel shaders prior to ps_3_0.

D3DDECLUSAGE_FOG

Vertex data contains fog data. Use D3DDECLUSAGE_FOG with a usage index of 0 to specify a fog blend value used after pixel shading finishes. This applies to pixel shaders prior to version ps_3_0.

D3DDECLUSAGE_DEPTH

Vertex data contains depth data.

D3DDECLUSAGE_SAMPLE

Vertex data contains sampler data. Use D3DDECLUSAGE_SAMPLE with a usage index of 0 to specify the displacement value to look up. It can be used only with D3DDECLUSAGE_LOOKUPPRESAMPLED or D3DDECLUSAGE_LOOKUP.

Remarks

Vertex data is declared with an array of D3DVERTEXELEMENT9 structures. Each element in the array contains a usage type.

For more information about vertex declarations, see Vertex Declaration.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

Vertex Declaration


D3DDEGREETYPE Enumerated Type

Defines the degree of the variables in the equation that describes a curve.

Syntax

typedef enum _D3DDEGREETYPE {
    D3DDEGREE_LINEAR = 1,
    D3DDEGREE_QUADRATIC = 2,
    D3DDEGREE_CUBIC = 3,
    D3DDEGREE_QUINTIC = 5,
    D3DCULL_FORCE_DWORD = 0x7fffffff
} D3DDEGREETYPE;

Constants

D3DDEGREE_LINEAR

Curve is described by variables of first order.

D3DDEGREE_QUADRATIC

Curve is described by variables of second order.

D3DDEGREE_CUBIC

Curve is described by variables of third order.

D3DDEGREE_QUINTIC

Curve is described by variables of fourth order.

D3DCULL_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The values in this enumeration are used to describe the curves used by rectangle and triangle patches. For more information, see D3DRS_CULLMODE.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 95

See Also

D3DCAPS9, D3DRENDERSTATETYPE


D3DDEVTYPE Enumerated Type

Defines device types.

Syntax

typedef enum _D3DDEVTYPE {
    D3DDEVTYPE_HAL = 1,
    D3DDEVTYPE_NULLREF = 4,
    D3DDEVTYPE_REF = 2,
    D3DDEVTYPE_SW = 3,
    D3DDEVTYPE_FORCE_DWORD = 0xffffffff
} D3DDEVTYPE;

Constants

D3DDEVTYPE_HAL

Hardware rasterization. Shading is done with software, hardware, or mixed transform and lighting.

D3DDEVTYPE_NULLREF

Initialize Microsoft Direct3D on a computer that has neither hardware nor reference rasterization available, and enable resources for 3-D content creation. See Remarks.

D3DDEVTYPE_REF

Direct3D features are implemented in software; however, the reference rasterizer does make use of special CPU instructions whenever it can.

D3DDEVTYPE_SW

A pluggable software device that has been registered with IDirect3D9::RegisterSoftwareDevice.

D3DDEVTYPE_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

All methods of the IDirect3D9 interface that take a D3DDEVTYPE device type will fail if D3DDEVTYPE_NULLREF is specified. To use these methods, substitute D3DDEVTYPE_REF in the method call.

A D3DDEVTYPE_REF device should be created in D3DPOOL_SCRATCH memory, unless vertex and index buffers are required. To support vertex and index buffers, create the device in D3DPOOL_SYSTEMMEM memory.

If D3dref9.dll is installed, Direct3D will use the reference rasterizer to create a D3DDEVTYPE_REF device type, even if D3DDEVTYPE_NULLREF is specified. If D3dref9.dll is not available and D3DDEVTYPE_NULLREF is specified, Direct3D will neither render nor present the scene.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3D9::CheckDeviceFormat, IDirect3D9::CheckDeviceMultiSampleType, IDirect3D9::CheckDeviceType, IDirect3D9::CreateDevice, IDirect3D9::GetDeviceCaps, D3DDEVICE_CREATION_PARAMETERS


D3DERR Enumerated Type

Errors are represented by negative values and cannot be combined. The following is a list of the values that can be returned by Microsoft Direct3D methods. See the individual method descriptions for lists of the values that each can return. These lists are not necessarily comprehensive.

Syntax

typedef enum {
    D3D_OK,
    D3DOK_NOAUTOGEN,
    D3DERR_CONFLICTINGRENDERSTATE,
    D3DERR_CONFLICTINGTEXTUREFILTER,
    D3DERR_CONFLICTINGTEXTUREPALETTE,
    D3DERR_DEVICELOST,
    D3DERR_DEVICENOTRESET,
    D3DERR_DRIVERINTERNALERROR,
    D3DERR_DRIVERINVALIDCALL,
    D3DERR_INVALIDCALL,
    D3DERR_INVALIDDEVICE,
    D3DERR_MOREDATA,
    D3DERR_NOTAVAILABLE,
    D3DERR_NOTFOUND,
    D3DERR_OUTOFVIDEOMEMORY,
    D3DERR_TOOMANYOPERATIONS,
    D3DERR_UNSUPPORTEDALPHAARG,
    D3DERR_UNSUPPORTEDALPHAOPERATION,
    D3DERR_UNSUPPORTEDCOLORARG,
    D3DERR_UNSUPPORTEDCOLOROPERATION,
    D3DERR_UNSUPPORTEDFACTORVALUE,
    D3DERR_UNSUPPORTEDTEXTUREFILTER,
    D3DERR_WASSTILLDRAWING,
    D3DERR_WRONGTEXTUREFORMAT,
    E_FAIL,
    E_INVALIDARG,
    E_INVALIDCALL,
    E_NOINTERFACE,
    E_NOTIMPL,
    E_OUTOFMEMORY,
    S_OK
} D3DERR;

Constants

D3D_OK

No error occurred.

D3DOK_NOAUTOGEN

This is a success code. However, the autogeneration of mipmaps is not supported for this format. This means that resource creation will succeed but the mipmap levels will not be automatically generated.

D3DERR_CONFLICTINGRENDERSTATE

The currently set render states cannot be used together.

D3DERR_CONFLICTINGTEXTUREFILTER

The current texture filters cannot be used together.

D3DERR_CONFLICTINGTEXTUREPALETTE

The current textures cannot be used simultaneously.

D3DERR_DEVICELOST

The device has been lost but cannot be reset at this time. Therefore, rendering is not possible.

D3DERR_DEVICENOTRESET

The device has been lost but can be reset at this time.

D3DERR_DRIVERINTERNALERROR

Internal driver error. Applications should destroy and recreate the device when receiving this error. For hints on debugging this error, see Driver Internal Errors.

D3DERR_DRIVERINVALIDCALL

Not used.

D3DERR_INVALIDCALL

The method call is invalid. For example, a method's parameter may not be a valid pointer.

D3DERR_INVALIDDEVICE

The requested device type is not valid.

D3DERR_MOREDATA

There is more data available than the specified buffer size can hold.

D3DERR_NOTAVAILABLE

This device does not support the queried technique.

D3DERR_NOTFOUND

The requested item was not found.

D3DERR_OUTOFVIDEOMEMORY

Direct3D does not have enough display memory to perform the operation.

D3DERR_TOOMANYOPERATIONS

The application is requesting more texture-filtering operations than the device supports.

D3DERR_UNSUPPORTEDALPHAARG

The device does not support a specified texture-blending argument for the alpha channel.

D3DERR_UNSUPPORTEDALPHAOPERATION

The device does not support a specified texture-blending operation for the alpha channel.

D3DERR_UNSUPPORTEDCOLORARG

The device does not support a specified texture-blending argument for color values.

D3DERR_UNSUPPORTEDCOLOROPERATION

The device does not support a specified texture-blending operation for color values.

D3DERR_UNSUPPORTEDFACTORVALUE

The device does not support the specified texture factor value. Not used; provided only to support older drivers.

D3DERR_UNSUPPORTEDTEXTUREFILTER

The device does not support the specified texture filter.

D3DERR_WASSTILLDRAWING

The previous blit operation that is transferring information to or from this surface is incomplete.

D3DERR_WRONGTEXTUREFORMAT

The pixel format of the texture surface is not valid.

E_FAIL

An undetermined error occurred inside the Direct3D subsystem.

E_INVALIDARG

An invalid parameter was passed to the returning function.

E_INVALIDCALL

The method call is invalid. For example, a method's parameter may have an invalid value.

E_NOINTERFACE

No object interface is available.

E_NOTIMPL

Not implemented.

E_OUTOFMEMORY

Direct3D could not allocate sufficient memory to complete the call.

S_OK

No error occurred.

Remarks

The facility code _FACD3D is used to generate error codes, as in the following macros.

// Direct3D Errors
#define D3DERR_UNSUPPORTEDFACTORVALUE  MAKE_D3DHRESULT(2079)
#define D3DERR_WASSTILLDRAWING         MAKE_D3DHRESULT(540)

#define _FACD3D                  0x876   // Direct3D facility code
#define MAKE_D3DHRESULT( code )  MAKE_HRESULT( 1, _FACD3D, code )
#define MAKE_D3DSTATUS( code )   MAKE_HRESULT( 0, _FACD3D, code )

Enumerated Type Information

Header | d3d9.h
Minimum operating systems | Windows 98


D3DFILLMODE Enumerated Type

Defines constants describing the fill mode.

Syntax

typedef enum _D3DFILLMODE {
    D3DFILL_POINT = 1,
    D3DFILL_WIREFRAME = 2,
    D3DFILL_SOLID = 3,
    D3DFILL_FORCE_DWORD = 0x7fffffff
} D3DFILLMODE;

Constants

D3DFILL_POINT

Fill points.

D3DFILL_WIREFRAME

Fill wireframes.

D3DFILL_SOLID

Fill solids.

D3DFILL_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The values in this enumerated type are used by the D3DRS_FILLMODE render state.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DRENDERSTATETYPE


D3DFOGMODE Enumerated Type

Defines constants that describe the fog mode.

Syntax

typedef enum _D3DFOGMODE {
    D3DFOG_NONE = 0,
    D3DFOG_EXP = 1,
    D3DFOG_EXP2 = 2,
    D3DFOG_LINEAR = 3,
    D3DFOG_FORCE_DWORD = 0x7fffffff
} D3DFOGMODE;

Constants

D3DFOG_NONE

No fog effect.

D3DFOG_EXP

Fog effect intensifies exponentially, according to the following formula.

Fog-effect intensity formula

D3DFOG_EXP2

Fog effect intensifies exponentially with the square of the distance, according to the following formula.

Fog-effect intensity formula

D3DFOG_LINEAR

Fog effect intensifies linearly between the start and end points, according to the following formula.

Fog-effect intensity formula

This is the only fog mode currently supported.

D3DFOG_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The values in this enumerated type are used by the D3DRS_FOGTABLEMODE and D3DRS_FOGVERTEXMODE render states.

Fog can be considered a measure of visibility—the lower the fog value produced by a fog equation, the less visible an object is.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DRENDERSTATETYPE


D3DFORMAT
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DFORMAT

Defines the various types of surface formats.

Syntax

typedef enum _D3DFORMAT {

... (values)

} D3DFORMAT;

There are several types of formats:

  • BackBuffer or Display Formats
  • Buffer Formats
  • DXTn Compressed Texture Formats
  • Floating-Point Formats
  • FOURCC Formats
  • IEEE Formats
  • Mixed Formats
  • Signed Formats
  • Unsigned Formats
  • Other

All formats are listed from left to right, most significant bit (MSB) to least significant bit (LSB). For example, D3DFORMAT_ARGB is ordered from the MSB channel A (alpha), to the LSB channel B (blue). When traversing surface data, the data is stored in memory from LSB to MSB, which means that the channel order in memory is from LSB (blue) to MSB (alpha).

The default value for formats that contain undefined channels (G16R16, A8, and so on) is 1. The only exception is the A8 format, which is initialized to 000 for the three color channels.

The order of the bits is from the most significant byte first, so D3DFMT_A8L8 indicates that the high byte of this 2-byte format is alpha. D3DFMT_D16 indicates a 16-bit integer value and an application-lockable surface.

Pixel formats have been chosen to enable the expression of hardware-vendor-defined extension formats, as well as to include the well-established four-character code (FOURCC) method. The set of formats understood by the Microsoft Direct3D runtime is defined by D3DFORMAT.

Note that formats are supplied by independent hardware vendors (IHVs) and many FOURCC codes are not listed. The formats in this enumeration are unique in that they are sanctioned by the runtime, meaning that the reference rasterizer will operate on all these types. IHV-supplied formats will be supported by the individual IHVs on a card-by-card basis.

BackBuffer or Display Formats

These formats are the only valid formats for a back buffer or a display.

Format | Back buffer | Display
A2R10G10B10 | x | x (full-screen mode only)
A8R8G8B8 | x |
X8R8G8B8 | x | x
A1R5G5B5 | x |
X1R5G5B5 | x | x
R5G6B5 | x | x

Buffer Formats

Depth, stencil, vertex, and index buffers each have unique formats.

Buffer flags | Value | Format
D3DFMT_D16_LOCKABLE | 70 | 16-bit z-buffer bit depth.
D3DFMT_D32 | 71 | 32-bit z-buffer bit depth.
D3DFMT_D15S1 | 73 | 16-bit z-buffer bit depth where 15 bits are reserved for the depth channel and 1 bit is reserved for the stencil channel.
D3DFMT_D24S8 | 75 | 32-bit z-buffer bit depth using 24 bits for the depth channel and 8 bits for the stencil channel.
D3DFMT_D24X8 | 77 | 32-bit z-buffer bit depth using 24 bits for the depth channel.
D3DFMT_D24X4S4 | 79 | 32-bit z-buffer bit depth using 24 bits for the depth channel and 4 bits for the stencil channel.
D3DFMT_D32F_LOCKABLE | 82 | A lockable format where the depth value is represented as a standard Institute of Electrical and Electronics Engineers (IEEE) floating-point number.
D3DFMT_D24FS8 | 83 | A non-lockable format that contains 24 bits of depth (in a 24-bit floating point format - 20e4) and 8 bits of stencil.
D3DFMT_D16 | 80 | 16-bit z-buffer bit depth.
D3DFMT_VERTEXDATA | 100 | Describes a vertex buffer surface.
D3DFMT_INDEX16 | 101 | 16-bit index buffer bit depth.
D3DFMT_INDEX32 | 102 | 32-bit index buffer bit depth.

All depth-stencil formats except D3DFMT_D16_LOCKABLE indicate no particular bit ordering per pixel, and the driver is allowed to consume more than the indicated number of bits-per-depth channel (but not stencil channel).

DXTn Compressed Texture Formats

These flags are used for compressed textures:

DXTn Compressed Texture flags | Value | Format
D3DFMT_DXT1 | MAKEFOURCC('D', 'X', 'T', '1') | DXT1 compression texture format
D3DFMT_DXT2 | MAKEFOURCC('D', 'X', 'T', '2') | DXT2 compression texture format
D3DFMT_DXT3 | MAKEFOURCC('D', 'X', 'T', '3') | DXT3 compression texture format
D3DFMT_DXT4 | MAKEFOURCC('D', 'X', 'T', '4') | DXT4 compression texture format
D3DFMT_DXT5 | MAKEFOURCC('D', 'X', 'T', '5') | DXT5 compression texture format

The runtime will not allow an application to create a surface using a DXTn format unless the surface dimensions are multiples of 4. This applies to offscreen-plain surfaces, render targets, 2-D textures, cube textures, and volume textures.

Floating-Point Formats

These flags are used for floating-point surface formats. These 16-bits-per-channel formats are also known as s10e5 formats.

Floating-point flags | Value | Format
D3DFMT_R16F | 111 | 16-bit float format using 16 bits for the red channel.
D3DFMT_G16R16F | 112 | 32-bit float format using 16 bits for the red channel and 16 bits for the green channel.
D3DFMT_A16B16G16R16F | 113 | 64-bit float format using 16 bits for the each channel (alpha, blue, green, red).

FOURCC Formats

Data in a FOURCC format is compressed data.

MAKEFOURCC

A macro for generating four-character codes follows:

#define MAKEFOURCC(ch0, ch1, ch2, ch3)                              \
                ((DWORD)(BYTE)(ch0) | ((DWORD)(BYTE)(ch1) << 8) |   \
                ((DWORD)(BYTE)(ch2) << 16) | ((DWORD)(BYTE)(ch3) << 24 ))

Here are the defined FOURCC formats:

FOURCC flags | Value | Format
D3DFMT_MULTI2_ARGB8 | MAKEFOURCC('M','E','T','1') | MultiElement texture (not compressed)
D3DFMT_G8R8_G8B8 | MAKEFOURCC('G', 'R', 'G', 'B') | A 16-bit packed RGB format analogous to YUY2 (Y0U0, Y1V0, Y2U2, and so on). It requires a pixel pair in order to properly represent the color value. The first pixel in the pair contains 8 bits of green (in the high 8 bits) and 8 bits of red (in the low 8 bits). The second pixel contains 8 bits of green (in the high 8 bits) and 8 bits of blue (in the low 8 bits). Together, the two pixels share the red and blue components, while each has a unique green component (G0R0, G1B0, G2R2, and so on). The texture sampler does not normalize the colors when looking up into a pixel shader; they remain in the range of 0.0f to 255.0f. This is true for all programmable pixel shader models. For the fixed function pixel shader, the hardware should normalize to the 0.f to 1.f range and essentially treat it as the YUY2 texture. Hardware that exposes this format must have the PixelShader1xMaxValue member of D3DCAPS9 set to a value capable of handling that range.
D3DFMT_R8G8_B8G8 | MAKEFOURCC('R', 'G', 'B', 'G') | A 16-bit packed RGB format analogous to UYVY (U0Y0, V0Y1, U2Y2, and so on). It requires a pixel pair in order to properly represent the color value. The first pixel in the pair contains 8 bits of green (in the low 8 bits) and 8 bits of red (in the high 8 bits). The second pixel contains 8 bits of green (in the low 8 bits) and 8 bits of blue (in the high 8 bits). Together, the two pixels share the red and blue components, while each has a unique green component (R0G0, B0G1, R2G2, and so on). The texture sampler does not normalize the colors when looking up into a pixel shader; they remain in the range of 0.0f to 255.0f. This is true for all programmable pixel shader models. For the fixed function pixel shader, the hardware should normalize to the 0.f to 1.f range and essentially treat it as the YUY2 texture. Hardware that exposes this format must have PixelShader1xMaxValue member of D3DCAPS9 set to a value capable of handling that range.
D3DFMT_UYVY | MAKEFOURCC('U', 'Y', 'V', 'Y') | UYVY format (PC98 compliance)
D3DFMT_YUY2 | MAKEFOURCC('Y', 'U', 'Y', '2') | YUY2 format (PC98 compliance)

IEEE Formats

These flags are used for floating-point surface formats. These 32-bits-per-channel formats are also known as s23e8 formats.

Floating-point flags | Value | Format
D3DFMT_R32F | 114 | 32-bit float format using 32 bits for the red channel.
D3DFMT_G32R32F | 115 | 64-bit float format using 32 bits for the red channel and 32 bits for the green channel.
D3DFMT_A32B32G32R32F | 116 | 128-bit float format using 32 bits for the each channel (alpha, blue, green, red).

Mixed Formats

Data in mixed formats can contain a combination of unsigned data and signed data.

Mixed format flags | Value | Format
D3DFMT_L6V5U5 | 61 | 16-bit bump-map format with luminance using 6 bits for luminance, and 5 bits each for v and u.
D3DFMT_X8L8V8U8 | 62 | 32-bit bump-map format with luminance using 8 bits for each channel.
D3DFMT_A2W10V10U10 | 67 | 32-bit bump-map format using 2 bits for alpha and 10 bits each for w, v, and u.

Signed Formats

Data in a signed format can be both positive and negative. Signed formats use combinations of (U), (V), (W), and (Q) data.

Signed format flags | Value | Format
D3DFMT_V8U8 | 60 | 16-bit bump-map format using 8 bits each for u and v data.
D3DFMT_Q8W8V8U8 | 63 | 32-bit bump-map format using 8 bits for each channel.
D3DFMT_V16U16 | 64 | 32-bit bump-map format using 16 bits for each channel.
D3DFMT_Q16W16V16U16 | 110 | 64-bit bump-map format using 16 bits for each component.
D3DFMT_CxV8U8 | 117 | 16-bit normal compression format. The texture sampler computes the C channel from: C = sqrt(1 - U2 - V2).

Unsigned Formats

Data in an unsigned format must be positive. Unsigned formats use combinations of (R)ed, (G)reen, (B)lue, (A)lpha, (L)uminance, and (P)alette data. Palette data is also referred to as color indexed data because the data is used to index a color palette.

Unsigned format flags | Value | Format
D3DFMT_R8G8B8 | 20 | 24-bit RGB pixel format with 8 bits per channel.
D3DFMT_A8R8G8B8 | 21 | 32-bit ARGB pixel format with alpha, using 8 bits per channel.
D3DFMT_X8R8G8B8 | 22 | 32-bit RGB pixel format, where 8 bits are reserved for each color.
D3DFMT_R5G6B5 | 23 | 16-bit RGB pixel format with 5 bits for red, 6 bits for green, and 5 bits for blue.
D3DFMT_X1R5G5B5 | 24 | 16-bit pixel format where 5 bits are reserved for each color.
D3DFMT_A1R5G5B5 | 25 | 16-bit pixel format where 5 bits are reserved for each color and 1 bit is reserved for alpha.
D3DFMT_A4R4G4B4 | 26 | 16-bit ARGB pixel format with 4 bits for each channel.
D3DFMT_R3G3B2 | 27 | 8-bit RGB texture format using 3 bits for red, 3 bits for green, and 2 bits for blue.
D3DFMT_A8 | 28 | 8-bit alpha only.
D3DFMT_A8R3G3B2 | 29 | 16-bit ARGB texture format using 8 bits for alpha, 3 bits each for red and green, and 2 bits for blue.
D3DFMT_X4R4G4B4 | 30 | 16-bit RGB pixel format using 4 bits for each color.
D3DFMT_A2B10G10R10 | 31 | 32-bit pixel format using 10 bits for each color and 2 bits for alpha.
D3DFMT_A8B8G8R8 | 32 | 32-bit ARGB pixel format with alpha, using 8 bits per channel.
D3DFMT_X8B8G8R8 | 33 | 32-bit RGB pixel format, where 8 bits are reserved for each color.
D3DFMT_G16R16 | 34 | 32-bit pixel format using 16 bits each for green and red.
D3DFMT_A2R10G10B10 | 35 | 32-bit pixel format using 10 bits each for red, green, and blue, and 2 bits for alpha.
D3DFMT_A16B16G16R16 | 36 | 64-bit pixel format using 16 bits for each component.
D3DFMT_A8P8 | 40 | 8-bit color indexed with 8 bits of alpha.
D3DFMT_P8 | 41 | 8-bit color indexed.
D3DFMT_L8 | 50 | 8-bit luminance only.
D3DFMT_L16 | 81 | 16-bit luminance only.
D3DFMT_A8L8 | 51 | 16-bit using 8 bits each for alpha and luminance.
D3DFMT_A4L4 | 52 | 8-bit using 4 bits each for alpha and luminance.

Other

This flag is used for undefined formats.

Other flags | Value | Format
D3DFMT_UNKNOWN | 0 | Surface format is unknown


D3DLIGHTTYPE Enumerated Type

Defines the light type.

Syntax

typedef enum _D3DLIGHTTYPE {
    D3DLIGHT_POINT = 1,
    D3DLIGHT_SPOT = 2,
    D3DLIGHT_DIRECTIONAL = 3,
    D3DLIGHT_FORCE_DWORD = 0x7fffffff
} D3DLIGHTTYPE;

Constants

D3DLIGHT_POINT

Light is a point source. The light has a position in space and radiates light in all directions.

D3DLIGHT_SPOT

Light is a spotlight source. This light is like a point light, except that the illumination is limited to a cone. This light type has a direction and several other parameters that determine the shape of the cone it produces. For information about these parameters, see the D3DLIGHT9 structure.

D3DLIGHT_DIRECTIONAL

Light is a directional light source. This is equivalent to using a point light source at an infinite distance.

D3DLIGHT_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Directional lights are slightly faster than point light sources, but point lights look a little better. Spotlights offer interesting visual effects but are computationally time-consuming.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DLIGHT9


D3DMATERIALCOLORSOURCE Enumerated Type

Defines the location at which a color or color component must be accessed for lighting calculations.

Syntax

typedef enum _D3DMATERIALCOLORSOURCE {
    D3DMCS_MATERIAL = 0,
    D3DMCS_COLOR1 = 1,
    D3DMCS_COLOR2 = 2,
    D3DMCS_FORCE_DWORD = 0x7fffffff
} D3DMATERIALCOLORSOURCE;

Constants

D3DMCS_MATERIAL

Use the color from the current material.

D3DMCS_COLOR1

Use the diffuse vertex color.

D3DMCS_COLOR2

Use the specular vertex color.

D3DMCS_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

These flags are used to set the value of the following render states in the D3DRENDERSTATETYPE enumerated type.

  • D3DRS_DIFFUSEMATERIALSOURCE
  • D3DRS_SPECULARMATERIALSOURCE
  • D3DRS_AMBIENTMATERIALSOURCE
  • D3DRS_EMISSIVEMATERIALSOURCE

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DRENDERSTATETYPE


D3DMULTISAMPLE_TYPE Enumerated Type

Defines levels of full-scene multisampling that the device can apply.

Syntax

typedef enum _D3DMULTISAMPLE_TYPE {
    D3DMULTISAMPLE_NONE = 0,
    D3DMULTISAMPLE_NONMASKABLE = 1,
    D3DMULTISAMPLE_2_SAMPLES = 2,
    D3DMULTISAMPLE_3_SAMPLES = 3,
    D3DMULTISAMPLE_4_SAMPLES = 4,
    D3DMULTISAMPLE_5_SAMPLES = 5,
    D3DMULTISAMPLE_6_SAMPLES = 6,
    D3DMULTISAMPLE_7_SAMPLES = 7,
    D3DMULTISAMPLE_8_SAMPLES = 8,
    D3DMULTISAMPLE_9_SAMPLES = 9,
    D3DMULTISAMPLE_10_SAMPLES = 10,
    D3DMULTISAMPLE_11_SAMPLES = 11,
    D3DMULTISAMPLE_12_SAMPLES = 12,
    D3DMULTISAMPLE_13_SAMPLES = 13,
    D3DMULTISAMPLE_14_SAMPLES = 14,
    D3DMULTISAMPLE_15_SAMPLES = 15,
    D3DMULTISAMPLE_16_SAMPLES = 16,
    D3DMULTISAMPLE_FORCE_DWORD = 0xffffffff
} D3DMULTISAMPLE_TYPE;

Constants

D3DMULTISAMPLE_NONE

No level of full-scene multisampling is available.

D3DMULTISAMPLE_NONMASKABLE

Enables the multisample quality value. See Remarks.

D3DMULTISAMPLE_2_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_3_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_4_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_5_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_6_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_7_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_8_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_9_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_10_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_11_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_12_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_13_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_14_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_15_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_16_SAMPLES

Level of full-scene multisampling available.

D3DMULTISAMPLE_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

In addition to enabling full-scene multisampling at IDirect3DDevice9::Reset time, there will be render states that turn various aspects on and off at fine-grained levels.

Multisampling is valid only on a swap chain that is being created or reset with the D3DSWAPEFFECT_DISCARD swap effect.

The multisampling antialiasing value can be set with the parameters (or sub-parameters) in the following methods.

Method | Parameters | Sub-parameters
IDirect3D9::CheckDeviceMultiSampleType | MultiSampleType and pQualityLevels
IDirect3DDevice9::CreateDepthStencilSurface> | MultiSampleType and pQualityLevels
IDirect3DDevice9::CreateRenderTarget | MultiSampleType and pQualityLevels
IDirect3DDevice9::CreateAdditionalSwapChain | pPresentationParameters | MultiSampleType and pQualityLevels
IDirect3D9::CreateDevice | pPresentationParameters | MultiSampleType and pQualityLevels
IDirect3DDevice9::Reset | pPresentationParameters | MultiSampleType and pQualityLevels

It is not good practice to switch from one multisample type to another to raise the quality of the antialiasing.

D3DMULTISAMPLE_NONE enables swap effects other than discarding, locking, etc.

Whether the display device supports maskable multisampling (more than one sample for a multiple-sample render-target format plus antialias support) or just non-maskable multisampling (only antialias support), the driver for the device provides the number of quality levels for the D3DMULTISAMPLE_NONMASKABLE multiple-sample type. Applications that just use multisampling for antialiasing purposes only need to query for the number of non-maskable multiple-sample quality levels that the driver supports.

The quality levels supported by the device can be obtained with the pQualityLevels parameter of IDirect3D9::CheckDeviceMultiSampleType. Quality levels used by the application are set with the MultiSampleQuality parameter of IDirect3DDevice9::CreateDepthStencilSurface and IDirect3DDevice9::CreateRenderTarget.

See D3DRS_MULTISAMPLEMASK for discussion of maskable multisampling.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DPRESENT_PARAMETERS, D3DSURFACE_DESC


D3DPATCHEDGESTYLE Enumerated Type

Defines whether the current tessellation mode is discrete or continuous.

Syntax

typedef enum _D3DPATCHEDGESTYLE {
    D3DPATCHEDGE_DISCRETE = 0,
    D3DPATCHEDGE_CONTINUOUS = 1,
    D3DPATCHEDGE_FORCE_DWORD = 0x7fffffff
} D3DPATCHEDGESTYLE;

Constants

D3DPATCHEDGE_DISCRETE

Discrete edge style. In discrete mode, you can specify float tessellation but it will be truncated to integers.

D3DPATCHEDGE_CONTINUOUS

Continuous edge style. In continuous mode, tessellation is specified as float values which can be smoothly varied to reduce "popping" artifacts.

D3DPATCHEDGE_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Note that continuous tessellation produces a completely different tessellation pattern from the discrete one for the same tessellation values (this is more apparent in wireframe mode). Thus, 4.0 continuous is not the same as 4 discrete.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98


D3DPOOL Enumerated Type

Defines the memory class that holds a resource's buffers.

Syntax

typedef enum _D3DPOOL {
    D3DPOOL_DEFAULT = 0,
    D3DPOOL_MANAGED = 1,
    D3DPOOL_SYSTEMMEM = 2,
    D3DPOOL_SCRATCH = 3,
    D3DPOOL_FORCE_DWORD = 0x7fffffff
} D3DPOOL;

Constants

D3DPOOL_DEFAULT

Resources are placed in the memory pool most appropriate for the set of usages requested for the given resource. This is usually video memory, including both local video memory and accelerated graphics port (AGP) memory. The D3DPOOL_DEFAULT pool is separate from D3DPOOL_MANAGED and D3DPOOL_SYTEMMEM, and it specifies that the resource is placed in the preferred memory for device access. Note that D3DPOOL_DEFAULT never indicates that either D3DPOOL_MANAGED or D3DPOOL_SYSTEMMEM should be chosen as the memory pool type for this resource. Textures placed in the D3DPOOL_DEFAULT pool cannot be locked unless they are dynamic textures or they are private, four-character code (FOURCC), driver formats. To access unlockable textures, you must use functions such as IDirect3DDevice9::UpdateSurface, IDirect3DDevice9::UpdateTexture, IDirect3DDevice9::GetFrontBufferData, and IDirect3DDevice9::GetRenderTargetData. D3DPOOL_MANAGED is probably a better choice than D3DPOOL_DEFAULT for most applications. Note that some textures created in driver-proprietary pixel formats, unknown to the Microsoft Direct3D runtime, can be locked. Also note that—unlike textures—swap chain back buffers, render targets, vertex buffers, and index buffers can be locked. When a device is lost, resources created using D3DPOOL_DEFAULT must be released before calling IDirect3DDevice9::Reset. For more information, see Lost Devices.

When creating resources with D3DPOOL_DEFAULT, if video card memory is already committed, managed resources will be evicted to free enough memory to satisfy the request.

D3DPOOL_MANAGED

Resources are copied automatically to device-accessible memory as needed. Managed resources are backed by system memory and do not need to be re-created when a device is lost. See Managing Resources for more information. Managed resources can be locked. Only the system-memory copy is directly modified. Direct3D copies your changes to driver-accessible memory as needed.

D3DPOOL_SYSTEMMEM

Resources are placed in memory that is not typically accessible by the Direct3D device. This memory allocation consumes system RAM but does not reduce pageable RAM. These resources do not need to be re-created when a device is lost. Resources in this pool can be locked and can be used as the source for a IDirect3DDevice9::UpdateSurface or IDirect3DDevice9::UpdateTexture operation to a memory resource created with D3DPOOL_DEFAULT.

D3DPOOL_SCRATCH

Resources are placed in system RAM and do not need to be re-created when a device is lost. These resources are not bound by device size or format restrictions. Because of this, these resources cannot be accessed by the Direct3D device nor set as textures or render targets. However, these resources can always be created, locked, and copied.

D3DPOOL_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

All pool types are valid with all resources. This includes: vertex buffers, index buffers, textures, and surfaces.

The following tables indicate restrictions on pool types for render targets, depth stencils, and dynamic and mipmap usages. An x indicates a compatible combination; lack of an x indicates incompatibility.

Pool | D3DUSAGE_RENDERTARGET | D3DUSAGE_DEPTHSTENCIL
D3DPOOL_DEFAULT | x | x
D3DPOOL_MANAGED
D3DPOOL_SCRATCH
D3DPOOL_SYSTEMMEM

Pool | D3DUSAGE_DYNAMIC | D3DUSAGE_AUTOGENMIPMAP
D3DPOOL_DEFAULT | x | x
D3DPOOL_MANAGED | x
D3DPOOL_SCRATCH
D3DPOOL_SYSTEMMEM | x

For more information about usage types, see D3DUSAGE.

Pools cannot be mixed for different objects contained within one resource (mip levels in a mipmap) and, when a pool is chosen, it cannot be changed.

Applications should use D3DPOOL_MANAGED for most static resources because this saves the application from having to deal with lost devices. (Managed resources are restored by the runtime.) This is especially beneficial for unified memory architecture (UMA) systems. Other dynamic resources are not a good match for D3DPOOL_MANAGED. In fact, index buffers and vertex buffers cannot be created using D3DPOOL_MANAGED together with D3DUSAGE_DYNAMIC.

For dynamic textures, it is sometimes desirable to use a pair of video memory and system memory textures, allocating the video memory using D3DPOOL_DEFAULT and the system memory using D3DPOOL_SYSTEMMEM. You can lock and modify the bits of the system memory texture using a locking method. Then you can update the video memory texture using IDirect3DDevice9::UpdateTexture.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DUSAGE, IDirect3DDevice9::CreateCubeTexture, IDirect3DDevice9::CreateIndexBuffer, IDirect3DDevice9::CreateTexture, IDirect3DDevice9::CreateVolumeTexture, IDirect3DDevice9::CreateVertexBuffer, D3DINDEXBUFFER_DESC, D3DSURFACE_DESC, D3DVERTEXBUFFER_DESC, D3DVOLUME_DESC


D3DPRIMITIVETYPE Enumerated Type

Defines the primitives supported by Microsoft Direct3D.

Syntax

typedef enum _D3DPRIMITIVETYPE {
    D3DPT_POINTLIST = 1,
    D3DPT_LINELIST = 2,
    D3DPT_LINESTRIP = 3,
    D3DPT_TRIANGLELIST = 4,
    D3DPT_TRIANGLESTRIP = 5,
    D3DPT_TRIANGLEFAN = 6,
    D3DPT_FORCE_DWORD = 0x7fffffff
} D3DPRIMITIVETYPE;

Constants

D3DPT_POINTLIST

Renders the vertices as a collection of isolated points. This value is unsupported for indexed primitives.

D3DPT_LINELIST

Renders the vertices as a list of isolated straight line segments.

D3DPT_LINESTRIP

Renders the vertices as a single polyline.

D3DPT_TRIANGLELIST

Renders the specified vertices as a sequence of isolated triangles. Each group of three vertices defines a separate triangle.

Back-face culling is affected by the current winding-order render state.

D3DPT_TRIANGLESTRIP

Renders the vertices as a triangle strip. The backface-culling flag is automatically flipped on even-numbered triangles.

D3DPT_TRIANGLEFAN

Renders the vertices as a triangle fan.

D3DPT_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Using Triangle Strips or Triangle Fans is often more efficient than using triangle lists because fewer vertices are duplicated.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::DrawIndexedPrimitive, IDirect3DDevice9::DrawIndexedPrimitiveUP, IDirect3DDevice9::DrawPrimitive, IDirect3DDevice9::DrawPrimitiveUP


D3DQUERYTYPE Enumerated Type

Identifies the query type. For information about queries, see Queries

Syntax

typedef enum _D3DQUERYTYPE {
    D3DQUERYTYPE_VCACHE = 4,
    D3DQUERYTYPE_RESOURCEMANAGER = 5,
    D3DQUERYTYPE_VERTEXSTATS = 6,
    D3DQUERYTYPE_EVENT = 8,
    D3DQUERYTYPE_OCCLUSION = 9,
    D3DQUERYTYPE_TIMESTAMP = 10,
    D3DQUERYTYPE_TIMESTAMPDISJOINT = 11,
    D3DQUERYTYPE_TIMESTAMPFREQ = 12,
    D3DQUERYTYPE_PIPELINETIMINGS = 13,
    D3DQUERYTYPE_INTERFACETIMINGS = 14,
    D3DQUERYTYPE_VERTEXTIMINGS = 15,
    D3DQUERYTYPE_PIXELTIMINGS = 16,
    D3DQUERYTYPE_BANDWIDTHTIMINGS = 17,
    D3DQUERYTYPE_CACHEUTILIZATION = 18
} D3DQUERYTYPE;

Constants

D3DQUERYTYPE_VCACHE

Query for driver hints about data layout for vertex caching.

D3DQUERYTYPE_RESOURCEMANAGER

Query the resource manager. For this query, the device behavior flags must include D3DCREATE_DISABLE_DRIVER_MANAGEMENT.

D3DQUERYTYPE_VERTEXSTATS

Query vertex statistics.

D3DQUERYTYPE_EVENT

Query for any and all asynchronous events that have been issued from application programming interface (API) calls.

D3DQUERYTYPE_OCCLUSION

An occlusion query returns the number of pixels that pass z-testing. These pixels are for primitives drawn between the issue of D3DISSUE_BEGIN and D3DISSUE_END. This enables an application to check the occlusion result against 0. Zero is fully occluded, which means the pixels are not visible from the current camera position.

D3DQUERYTYPE_TIMESTAMP

Returns a 64-bit timestamp.

D3DQUERYTYPE_TIMESTAMPDISJOINT

Use this query to notify an application if the counter frequency has changed from the D3DQUERYTYPE_TIMESTAMP.

D3DQUERYTYPE_TIMESTAMPFREQ

This query result is TRUE if the values from D3DQUERYTYPE_TIMESTAMP queries cannot be guaranteed to be continuous throughout the duration of the D3DQUERYTYPE_TIMESTAMPDISJOINT query. Otherwise, the query result is FALSE.

D3DQUERYTYPE_PIPELINETIMINGS

Percent of time processing pipeline data.

D3DQUERYTYPE_INTERFACETIMINGS

Percent of time processing data in the driver.

D3DQUERYTYPE_VERTEXTIMINGS

Percent of time processing vertex shader data.

D3DQUERYTYPE_PIXELTIMINGS

Percent of time processing pixel shader data.

D3DQUERYTYPE_BANDWIDTHTIMINGS

Throughput measurement comparisons for help in understanding the performance of an application.

D3DQUERYTYPE_CACHEUTILIZATION

Measure the cache hit-rate performance for textures and indexed vertices.

Remarks

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::CreateQuery


D3DRENDERSTATETYPE Enumerated Type

Render states define set-up states for all kinds of vertex and pixel processing. Some render states set-up vertex processing, and some set-up pixel processing (see Render States). Render states can be saved and restored using stateblocks (see State Blocks Save and Restore State).

Syntax

typedef enum _D3DRENDERSTATETYPE {
    D3DRS_ZENABLE = 7,
    D3DRS_FILLMODE = 8,
    D3DRS_SHADEMODE = 9,
    D3DRS_ZWRITEENABLE = 14,
    D3DRS_ALPHATESTENABLE = 15,
    D3DRS_LASTPIXEL = 16,
    D3DRS_SRCBLEND = 19,
    D3DRS_DESTBLEND = 20,
    D3DRS_CULLMODE = 22,
    D3DRS_ZFUNC = 23,
    D3DRS_ALPHAREF = 24,
    D3DRS_ALPHAFUNC = 25,
    D3DRS_DITHERENABLE = 26,
    D3DRS_ALPHABLENDENABLE = 27,
    D3DRS_FOGENABLE = 28,
    D3DRS_SPECULARENABLE = 29,
    D3DRS_FOGCOLOR = 34,
    D3DRS_FOGTABLEMODE = 35,
    D3DRS_FOGSTART = 36,
    D3DRS_FOGEND = 37,
    D3DRS_FOGDENSITY = 38,
    D3DRS_RANGEFOGENABLE = 48,
    D3DRS_STENCILENABLE = 52,
    D3DRS_STENCILFAIL = 53,
    D3DRS_STENCILZFAIL = 54,
    D3DRS_STENCILPASS = 55,
    D3DRS_STENCILFUNC = 56,
    D3DRS_STENCILREF = 57,
    D3DRS_STENCILMASK = 58,
    D3DRS_STENCILWRITEMASK = 59,
    D3DRS_TEXTUREFACTOR = 60,
    D3DRS_WRAP0 = 128,
    D3DRS_WRAP1 = 129,
    D3DRS_WRAP2 = 130,
    D3DRS_WRAP3 = 131,
    D3DRS_WRAP4 = 132,
    D3DRS_WRAP5 = 133,
    D3DRS_WRAP6 = 134,
    D3DRS_WRAP7 = 135,
    D3DRS_CLIPPING = 136,
    D3DRS_LIGHTING = 137,
    D3DRS_AMBIENT = 139,
    D3DRS_FOGVERTEXMODE = 140,
    D3DRS_COLORVERTEX = 141,
    D3DRS_LOCALVIEWER = 142,
    D3DRS_NORMALIZENORMALS = 143,
    D3DRS_DIFFUSEMATERIALSOURCE = 145,
    D3DRS_SPECULARMATERIALSOURCE = 146,
    D3DRS_AMBIENTMATERIALSOURCE = 147,
    D3DRS_EMISSIVEMATERIALSOURCE = 148,
    D3DRS_VERTEXBLEND = 151,
    D3DRS_CLIPPLANEENABLE = 152,
    D3DRS_POINTSIZE = 154,
    D3DRS_POINTSIZE_MIN = 155,
    D3DRS_POINTSPRITEENABLE = 156,
    D3DRS_POINTSCALEENABLE = 157,
    D3DRS_POINTSCALE_A = 158,
    D3DRS_POINTSCALE_B = 159,
    D3DRS_POINTSCALE_C = 160,
    D3DRS_MULTISAMPLEANTIALIAS = 161,
    D3DRS_MULTISAMPLEMASK = 162,
    D3DRS_PATCHEDGESTYLE = 163,
    D3DRS_DEBUGMONITORTOKEN = 165,
    D3DRS_POINTSIZE_MAX = 166,
    D3DRS_INDEXEDVERTEXBLENDENABLE = 167,
    D3DRS_COLORWRITEENABLE = 168,
    D3DRS_TWEENFACTOR = 170,
    D3DRS_BLENDOP = 171,
    D3DRS_POSITIONDEGREE = 172,
    D3DRS_NORMALDEGREE = 173,
    D3DRS_SCISSORTESTENABLE = 174,
    D3DRS_SLOPESCALEDEPTHBIAS = 175,
    D3DRS_ANTIALIASEDLINEENABLE = 176,
    D3DRS_MINTESSELLATIONLEVEL = 178,
    D3DRS_MAXTESSELLATIONLEVEL = 179,
    D3DRS_ADAPTIVETESS_X = 180,
    D3DRS_ADAPTIVETESS_Y = 181,
    D3DRS_ADAPTIVETESS_Z = 182,
    D3DRS_ADAPTIVETESS_W = 183,
    D3DRS_ENABLEADAPTIVETESSELLATION = 184,
    D3DRS_TWOSIDEDSTENCILMODE = 185,
    D3DRS_CCW_STENCILFAIL = 186,
    D3DRS_CCW_STENCILZFAIL = 187,
    D3DRS_CCW_STENCILPASS = 188,
    D3DRS_CCW_STENCILFUNC = 189,
    D3DRS_COLORWRITEENABLE1 = 190,
    D3DRS_COLORWRITEENABLE2 = 191,
    D3DRS_COLORWRITEENABLE3 = 192,
    D3DRS_BLENDFACTOR = 193,
    D3DRS_SRGBWRITEENABLE = 194,
    D3DRS_DEPTHBIAS = 195,
    D3DRS_WRAP8 = 198,
    D3DRS_WRAP9 = 199,
    D3DRS_WRAP10 = 200,
    D3DRS_WRAP11 = 201,
    D3DRS_WRAP12 = 202,
    D3DRS_WRAP13 = 203,
    D3DRS_WRAP14 = 204,
    D3DRS_WRAP15 = 205,
    D3DRS_SEPARATEALPHABLENDENABLE = 206,
    D3DRS_SRCBLENDALPHA = 207,
    D3DRS_DESTBLENDALPHA = 208,
    D3DRS_BLENDOPALPHA = 209,
    D3DRS_FORCE_DWORD = 0x7fffffff
} D3DRENDERSTATETYPE;

Constants

D3DRS_ZENABLE

Depth-buffering state as one member of the D3DZBUFFERTYPE enumerated type. Set this state to D3DZB_TRUE to enable z-buffering, D3DZB_USEW to enable w-buffering, or D3DZB_FALSE to disable depth buffering.

The default value for this render state is D3DZB_TRUE if a depth stencil was created along with the swap chain by setting the EnableAutoDepthStencil member of the D3DPRESENT_PARAMETERS structure to TRUE, and D3DZB_FALSE otherwise.

D3DRS_FILLMODE

One or more members of the D3DFILLMODE enumerated type. The default value is D3DFILL_SOLID.

D3DRS_SHADEMODE

One or more members of the D3DSHADEMODE enumerated type. The default value is D3DSHADE_GOURAUD.

D3DRS_ZWRITEENABLE

TRUE to enable the application to write to the depth buffer. The default value is TRUE. This member enables an application to prevent the system from updating the depth buffer with new depth values. If FALSE, depth comparisons are still made according to the render state D3DRS_ZFUNC, assuming that depth buffering is taking place, but depth values are not written to the buffer.

D3DRS_ALPHATESTENABLE

TRUE to enable per pixel alpha testing. If the test passes, the pixel is processed by the frame buffer. Otherwise, all frame-buffer processing is skipped for the pixel.

The test is done by comparing the incoming alpha value with the reference alpha value, using the comparison function provided by the D3DRS_ALPHAFUNC render state. The reference alpha value is determined by the value set for D3DRS_ALPHAREF. For more information, see Alpha Testing State.

The default value of this parameter is FALSE.

D3DRS_LASTPIXEL

The default value is TRUE, which enables drawing of the last pixel in a line. To prevent drawing of the last pixel, set this value to FALSE. For more information, see Outline and Fill State.

D3DRS_SRCBLEND

One member of the D3DBLEND enumerated type. The default value is D3DBLEND_ONE.

D3DRS_DESTBLEND

One member of the D3DBLEND enumerated type. The default value is D3DBLEND_ZERO.

D3DRS_CULLMODE

Specifies how back-facing triangles are culled, if at all. This can be set to one member of the D3DCULL enumerated type. The default value is D3DCULL_CCW.

D3DRS_ZFUNC

One member of the D3DCMPFUNC enumerated type. The default value is D3DCMP_LESSEQUAL. This member enables an application to accept or reject a pixel, based on its distance from the camera.

The depth value of the pixel is compared with the depth-buffer value. If the depth value of the pixel passes the comparison function, the pixel is written.

The depth value is written to the depth buffer only if the render state is TRUE.

Software rasterizers and many hardware accelerators work faster if the depth test fails, because there is no need to filter and modulate the texture if the pixel is not going to be rendered.

D3DRS_ALPHAREF

Value that specifies a reference alpha value against which pixels are tested when alpha testing is enabled. This is an 8-bit value placed in the low 8 bits of the DWORD render-state value. Values can range from 0x00000000 through 0x000000FF. The default value is 0.

D3DRS_ALPHAFUNC

One member of the D3DCMPFUNC enumerated type. The default value is D3DCMP_ALWAYS. This member enables an application to accept or reject a pixel, based on its alpha value.

D3DRS_DITHERENABLE

TRUE to enable dithering. The default value is FALSE.

D3DRS_ALPHABLENDENABLE

TRUE to enable alpha-blended transparency. The default value is FALSE.

The type of alpha blending is determined by the D3DRS_SRCBLEND and D3DRS_DESTBLEND render states.

D3DRS_FOGENABLE

TRUE to enable fog blending. The default value is FALSE. For more information about using fog blending, see Fog.

D3DRS_SPECULARENABLE

TRUE to enable specular highlights. The default value is FALSE.

Specular highlights are calculated as though every vertex in the object being lit is at the object's origin. This gives the expected results as long as the object is modeled around the origin and the distance from the light to the object is relatively large. In other cases, the results as undefined.

When this member is set to TRUE, the specular color is added to the base color after the texture cascade but before alpha blending.

D3DRS_FOGCOLOR

Value whose type is D3DCOLOR. The default value is 0. For more information about fog color, see Fog Color.

D3DRS_FOGTABLEMODE

The fog formula to be used for pixel fog. Set to one of the members of the D3DFOGMODE enumerated type. The default value is D3DFOG_NONE. For more information about pixel fog, see Pixel Fog.

D3DRS_FOGSTART

Depth at which pixel or vertex fog effects begin for linear fog mode. The default value is 0.0f. Depth is specified in world space for vertex fog and either device space [0.0, 1.0] or world space for pixel fog. For pixel fog, these values are in device space when the system uses z for fog calculations and world-world space when the system is using eye-relative fog (w-fog). For more information, see Fog Parameters and Eye-Relative vs. Z-based Depth.

Values for the this render state are floating-point values. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

pDevice9->SetRenderState(D3DRS_FOGSTART, *((DWORD*) (&fFogStart)));

D3DRS_FOGEND

Depth at which pixel or vertex fog effects end for linear fog mode. The default value is 1.0f. Depth is specified in world space for vertex fog and either device space [0.0, 1.0] or world space for pixel fog. For pixel fog, these values are in device space when the system uses z for fog calculations and in world space when the system is using eye-relative fog (w-fog). For more information, see Fog Parameters and Eye-Relative vs. Z-based Depth.

Values for this render state are floating-point values. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

m_pDevice9->SetRenderState(D3DRS_FOGEND, *((DWORD*) (&fFogEnd)));

D3DRS_FOGDENSITY

Fog density for pixel or vertex fog used in the exponential fog modes (D3DFOG_EXP and D3DFOG_EXP2). Valid density values range from 0.0 through 1.0. The default value is 1.0. For more information, see Fog Parameters.

Values for this render state are floating-point values. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

m_pDevice9->SetRenderState(D3DRS_FOGDENSITY, *((DWORD*) (&fFogDensity)));

D3DRS_RANGEFOGENABLE

TRUE to enable range-based vertex fog. The default value is FALSE, in which case the system uses depth-based fog. In range-based fog, the distance of an object from the viewer is used to compute fog effects, not the depth of the object (that is, the z-coordinate) in the scene. In range-based fog, all fog methods work as usual, except that they use range instead of depth in the computations.

Range is the correct factor to use for fog computations, but depth is commonly used instead because range is time-consuming to compute and depth is generally already available. Using depth to calculate fog has the undesirable effect of having the fogginess of peripheral objects change as the viewer's eye moves—in this case, the depth changes and the range remains constant.

Because no hardware currently supports per-pixel range-based fog, range correction is offered only for vertex fog.

For more information, see Vertex Fog.

D3DRS_STENCILENABLE

TRUE to enable stenciling, or FALSE to disable stenciling. The default value is FALSE. For more information, see Stencil Buffer Techniques.

D3DRS_STENCILFAIL

Stencil operation to perform if the stencil test fails. Values are from the D3DSTENCILOP enumerated type. The default value is D3DSTENCILOP_KEEP.

D3DRS_STENCILZFAIL

Stencil operation to perform if the stencil test passes and the depth test (z-test) fails. Values are from the D3DSTENCILOP enumerated type. The default value is D3DSTENCILOP_KEEP.

D3DRS_STENCILPASS

Stencil operation to perform if both the stencil and the depth (z) tests pass. Values are from the D3DSTENCILOP enumerated type. The default value is D3DSTENCILOP_KEEP.

D3DRS_STENCILFUNC

Comparison function for the stencil test. Values are from the D3DCMPFUNC enumerated type. The default value is D3DCMP_ALWAYS.

The comparison function is used to compare the reference value to a stencil buffer entry. This comparison applies only to the bits in the reference value and stencil buffer entry that are set in the stencil mask (set by the D3DRS_STENCILMASK render state). If TRUE, the stencil test passes.

D3DRS_STENCILREF

An int reference value for the stencil test. The default value is 0.

D3DRS_STENCILMASK

Mask applied to the reference value and each stencil buffer entry to determine the significant bits for the stencil test. The default mask is 0xFFFFFFFF.

D3DRS_STENCILWRITEMASK

Write mask applied to values written into the stencil buffer. The default mask is 0xFFFFFFFF.

D3DRS_TEXTUREFACTOR

Color used for multiple-texture blending with the D3DTA_TFACTOR texture-blending argument or the D3DTOP_BLENDFACTORALPHA texture-blending operation. The associated value is a D3DCOLOR variable. The default value is opaque white (0xFFFFFFFF).

D3DRS_WRAP0

Texture-wrapping behavior for multiple sets of texture coordinates. Valid values for this render state can be any combination of the D3DWRAPCOORD_0 (or D3DWRAP_U), D3DWRAPCOORD_1 (or D3DWRAP_V), D3DWRAPCOORD_2 (or D3DWRAP_W), and D3DWRAPCOORD_3 flags. These cause the system to wrap in the direction of the first, second, third, and fourth dimensions, sometimes referred to as the s, t, r, and q directions, for a given texture. The default value for this render state is 0 (wrapping disabled in all directions).

D3DRS_WRAP1

See D3DRS_WRAP0.

D3DRS_WRAP2

See D3DRS_WRAP0.

D3DRS_WRAP3

See D3DRS_WRAP0.

D3DRS_WRAP4

See D3DRS_WRAP0.

D3DRS_WRAP5

See D3DRS_WRAP0.

D3DRS_WRAP6

See D3DRS_WRAP0.

D3DRS_WRAP7

See D3DRS_WRAP0.

D3DRS_CLIPPING

TRUE to enable primitive clipping by Microsoft Direct3D, or FALSE to disable it. The default value is TRUE.

D3DRS_LIGHTING

TRUE to enable Direct3D lighting, or FALSE to disable it. The default value is TRUE. Only vertices that include a vertex normal are properly lit; vertices that do not contain a normal employ a dot product of 0 in all lighting calculations.

D3DRS_AMBIENT

Ambient light color. This value is of type D3DCOLOR. The default value is 0.

D3DRS_FOGVERTEXMODE

Fog formula to be used for vertex fog. Set to one member of the D3DFOGMODE enumerated type. The default value is D3DFOG_NONE.

D3DRS_COLORVERTEX

TRUE to enable per-vertex color or FALSE to disable it. The default value is TRUE. Enabling per-vertex color allows the system to include the color defined for individual vertices in its lighting calculations.

For more information, see the following render states:

  • D3DRS_DIFFUSEMATERIALSOURCE
  • D3DRS_SPECULARMATERIALSOURCE
  • D3DRS_AMBIENTMATERIALSOURCE
  • D3DRS_EMISSIVEMATERIALSOURCE

D3DRS_LOCALVIEWER

TRUE to enable camera-relative specular highlights, or FALSE to use orthogonal specular highlights. The default value is TRUE. Applications that use orthogonal projection should specify false.

D3DRS_NORMALIZENORMALS

TRUE to enable automatic normalization of vertex normals, or FALSE to disable it. The default value is FALSE. Enabling this feature causes the system to normalize the vertex normals for vertices after transforming them to camera space, which can be computationally time-consuming.

D3DRS_DIFFUSEMATERIALSOURCE

Diffuse color source for lighting calculations. Valid values are members of the D3DMATERIALCOLORSOURCE enumerated type. The default value is D3DMCS_COLOR1. The value for this render state is used only if the D3DRS_COLORVERTEX render state is set to TRUE.

D3DRS_SPECULARMATERIALSOURCE

Specular color source for lighting calculations. Valid values are members of the D3DMATERIALCOLORSOURCE enumerated type. The default value is D3DMCS_COLOR2.

D3DRS_AMBIENTMATERIALSOURCE

Ambient color source for lighting calculations. Valid values are members of the D3DMATERIALCOLORSOURCE enumerated type. The default value is D3DMCS_MATERIAL.

D3DRS_EMISSIVEMATERIALSOURCE

Emissive color source for lighting calculations. Valid values are members of the D3DMATERIALCOLORSOURCE enumerated type. The default value is D3DMCS_MATERIAL.

D3DRS_VERTEXBLEND

Number of matrices to use to perform geometry blending, if any. Valid values are members of the D3DVERTEXBLENDFLAGS enumerated type. The default value is D3DVBF_DISABLE.

D3DRS_CLIPPLANEENABLE

Enables or disables user-defined clipping planes. Valid values are any DWORD in which the status of each bit (set or not set) toggles the activation state of a corresponding user-defined clipping plane. The least significant bit (bit 0) controls the first clipping plane at index 0, and subsequent bits control the activation of clipping planes at higher indexes. If a bit is set, the system applies the appropriate clipping plane during scene rendering. The default value is 0.

The D3DCLIPPLANEn macros are defined to provide a convenient way to enable clipping planes.

D3DRS_POINTSIZE

A float value that specifies the size to use for point size computation in cases where point size is not specified for each vertex. This value is not used when the vertex contains point size. This value is in screen space units if D3DRS_POINTSCALEENABLE is FALSE; otherwise this value is in world space units. The default value is the value a driver returns. If a driver returns 0 or 1, the default value is 64, which allows software point size emulation. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

m_pDevice9->SetRenderState(D3DRS_POINTSIZE, *((DWORD*)&PointSize));

D3DRS_POINTSIZE_MIN

A float value that specifies the minimum size of point primitives. Point primitives are clamped to this size during rendering. Setting this to values smaller than 1.0 results in points dropping out when the point does not cover a pixel center and antialiasing is disabled or being rendered with reduced intensity when antialiasing is enabled. The default value is 1.0f. The range for this value is greater than or equal to 0.0f. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

m_pDevice9->SetRenderState(D3DRS_POINTSIZE_MIN, *((DWORD*)&PointSizeMin));

D3DRS_POINTSPRITEENABLE

BOOL value. When TRUE, texture coordinates of point primitives are set so that full textures are mapped on each point. When FALSE, the vertex texture coordinates are used for the entire point. The default value is FALSE. You can achieve Microsoft DirectX 7.0 style single-pixel points by setting D3DRS_POINTSCALEENABLE to FALSE and D3DRS_POINTSIZE to 1.0, which are the default values.

D3DRS_POINTSCALEENABLE

BOOL value that controls computation of size for point primitives. When TRUE, the point size is interpreted as a camera space value and is scaled by the distance function and the frustum to viewport y-axis scaling to compute the final screen-space point size. When FALSE, the point size is interpreted as screen space and used directly. The default value is FALSE.

D3DRS_POINTSCALE_A

A float value that controls for distance-based size attenuation for point primitives. Active only when D3DRS_POINTSCALEENABLE is TRUE. The default value is 1.0f. The range for this value is greater than or equal to 0.0f. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

m_pDevice9->SetRenderState(D3DRS_POINTSCALE_A, *((DWORD*)&PointScaleA));

D3DRS_POINTSCALE_B

A float value that controls for distance-based size attenuation for point primitives. Active only when D3DRS_POINTSCALEENABLE is TRUE. The default value is 0.0f. The range for this value is greater than or equal to 0.0f. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

m_pDevice9->SetRenderState(D3DRS_POINTSCALE_B, *((DWORD*)&PointScaleB));

D3DRS_POINTSCALE_C

A float value that controls for distance-based size attenuation for point primitives. Active only when D3DRS_POINTSCALEENABLE is TRUE. The default value is 0.0f. The range for this value is greater than or equal to 0.0f. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

m_pDevice9->SetRenderState(D3DRS_POINTSCALE_C, *((DWORD*)&PointScaleC));

D3DRS_MULTISAMPLEANTIALIAS

BOOL value that determines how individual samples are computed when using a multisample render-target buffer. When set to TRUE, the multiple samples are computed so that full-scene antialiasing is performed by sampling at different sample positions for each multiple sample. When set to FALSE, the multiple samples are all written with the same sample value, sampled at the pixel center, which allows non-antialiased rendering to a multisample buffer. This render state has no effect when rendering to a single sample buffer. The default value is TRUE.

D3DRS_MULTISAMPLEMASK

Each bit in this mask, starting at the least significant bit (LSB), controls modification of one of the samples in a multisample render target. Thus, for an 8-sample render target, the low byte contains the eight write enables for each of the eight samples. This render state has no effect when rendering to a single sample buffer. The default value is 0xFFFFFFFF.

This render state enables use of a multisample buffer as an accumulation buffer, doing multipass rendering of geometry where each pass updates a subset of samples.

If there are n multisamples and k enabled samples, the resulting intensity of the rendered image should be k/n. Each component RGB of every pixel is factored by k/n.

D3DRS_PATCHEDGESTYLE

Sets whether patch edges will use float style tessellation. Possible values are defined by the D3DPATCHEDGESTYLE enumerated type. The default value is D3DPATCHEDGE_DISCRETE.

D3DRS_DEBUGMONITORTOKEN

Set only for debugging the monitor. Possible values are defined by the D3DDEBUGMONITORTOKENS enumerated type. Note that if D3DRS_DEBUGMONITORTOKEN is set, the call is treated as passing a token to the debug monitor. For example, if—after passing D3DDMT_ENABLE or D3DDMT_DISABLE to D3DRS_DEBUGMONITORTOKEN—other token values are passed in, the state (enabled or disabled) of the debug monitor will still persist.

This state is only useful for debug builds. The debug monitor defaults to D3DDMT_ENABLE.

D3DRS_POINTSIZE_MAX

A float value that specifies the maximum size to which point sprites will be clamped. The value must be less than or equal to the MaxPointSize member of D3DCAPS9 and greater than or equal to D3DRS_POINTSIZE_MIN. The default value is 64.0. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

m_pDevice9->SetRenderState(D3DRS_PONTSIZE_MAX, *((DWORD*)&PointSizeMax));

D3DRS_INDEXEDVERTEXBLENDENABLE

BOOL value that enables or disables indexed vertex blending. The default value is FALSE. When set to TRUE, indexed vertex blending is enabled. When set to FALSE, indexed vertex blending is disabled. If this render state is enabled, the user must pass matrix indices as a packed DWORDwith every vertex. When the render state is disabled and vertex blending is enabled through the D3DRS_VERTEXBLEND state, it is equivalent to having matrix indices 0, 1, 2, 3 in every vertex.

D3DRS_COLORWRITEENABLE

UINT value that enables a per-channel write for the render-target color buffer. A set bit results in the color channel being updated during 3-D rendering. A clear bit results in the color channel being unaffected. This functionality is available if the D3DPMISCCAPS_COLORWRITEENABLE capabilities bit is set in the PrimitiveMiscCaps member of the D3DCAPS9 structure for the device. This render state does not affect the clear operation. The default value is 0x0000000F.

Valid values for this render state can be any combination of the D3DCOLORWRITEENABLE_ALPHA, D3DCOLORWRITEENABLE_BLUE, D3DCOLORWRITEENABLE_GREEN, or D3DCOLORWRITEENABLE_RED flags.

D3DRS_TWEENFACTOR

A float value that controls the tween factor. The default value is 0.0f. Because the IDirect3DDevice9::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

m_pDevice9->SetRenderState(D3DRS_TWEENFACTOR, *((DWORD*)&TweenFactor));

D3DRS_BLENDOP

Value used to select the arithmetic operation applied when the alpha blending render state, D3DRS_ALPHABLENDENABLE, is set to TRUE. Valid values are defined by the D3DBLENDOP enumerated type. The default value is D3DBLENDOP_ADD.

If the D3DPMISCCAPS_BLENDOP device capability is not supported, then D3DBLENDOP_ADD is performed.

D3DRS_POSITIONDEGREE

N-patch position interpolation degree. The values can be D3DDEGREE_CUBIC (default) or D3DDEGREE_LINEAR. For more information, see D3DDEGREETYPE.

D3DRS_NORMALDEGREE

N-patch normal interpolation degree. The values can be D3DDEGREE_LINEAR (default) or D3DDEGREE_QUADRATIC. For more information, see D3DDEGREETYPE.

D3DRS_SCISSORTESTENABLE

TRUE to enable scissor testing and FALSE to disable it. The default value is FALSE.

D3DRS_SLOPESCALEDEPTHBIAS

Used to determine how much bias can be applied to co-planar primitives to reduce z fighting. The default value is 0.

bias = (max * D3DRS_SLOPESCALEDEPTHBIAS) + D3DRS_DEPTHBIAS.

where max is the maximum depth slope of the triangle being rendered.

D3DRS_ANTIALIASEDLINEENABLE

TRUE to enable line antialiasing, FALSE to disable line antialiasing. The default value is FALSE.

When rendering to a multisample render target, D3DRS_ANTIALIASEDLINEENABLE is ignored and all lines are rendered aliased. Use ID3DXLine for antialiased line rendering in a multisample render target.

D3DRS_MINTESSELLATIONLEVEL

Minimum tessellation level. The default value is 1.0f. See Tessellation.

D3DRS_MAXTESSELLATIONLEVEL

Maximum tessellation level. The default value is 1.0f. See Tessellation.

D3DRS_ADAPTIVETESS_X

Amount to adaptively tessellate, in the x direction. Default value is 0.0f. See Adaptive Tessellation.

D3DRS_ADAPTIVETESS_Y

Amount to adaptively tessellate, in the y direction. Default value is 0.0f. See Adaptive Tessellation.

D3DRS_ADAPTIVETESS_Z

Amount to adaptively tessellate, in the z direction. Default value is 1.0f. See Adaptive Tessellation.

D3DRS_ADAPTIVETESS_W

Amount to adaptively tessellate, in the w direction. Default value is 0.0f. See Adaptive Tessellation.

D3DRS_ENABLEADAPTIVETESSELLATION

TRUE to enable adaptive tessellation, FALSE to disable it. The default value is FALSE. See Adaptive Tessellation.

D3DRS_TWOSIDEDSTENCILMODE

TRUE enables two-sided stenciling, FALSE disables it. The default value is FALSE. The application should set D3DRS_CULLMODE to D3DCULL_NONE to enable two-sided stencil mode. If the triangle winding order is clockwise, the D3DRS_STENCIL* operations will be used. If the winding order is counterclocwise, the D3DRS_CCW_STENCIL* operations will be used.

To see if two-sided stencil is supported, check the StencilCaps member of D3DCAPS9 for D3DSTENCILCAPS_TWOSIDED. See also D3DSTENCILCAPS.

D3DRS_CCW_STENCILFAIL

Stencil operation to perform if CCW stencil test fails. Values are from the D3DSTENCILOP enumerated type. The default value is D3DSTENCILOP_KEEP.

D3DRS_CCW_STENCILZFAIL

Stencil operation to perform if CCW stencil test passes and z-test fails. Values are from the D3DSTENCILOP enumerated type. The default value is D3DSTENCILOP_KEEP.

D3DRS_CCW_STENCILPASS

Stencil operation to perform if both CCW stencil and z-tests pass. Values are from the D3DSTENCILOP enumerated type. The default value is D3DSTENCILOP_KEEP.

D3DRS_CCW_STENCILFUNC

The comparison function. CCW stencil test passes if ((ref & mask) stencil function (stencil & mask)) is true. Values are from the D3DCMPFUNC enumerated type. The default value is D3DCMP_ALWAYS.

D3DRS_COLORWRITEENABLE1

Additional ColorWriteEnable values for the devices. See D3DRS_COLORWRITEENABLE. This functionality is available if the D3DPMISCCAPS_INDEPENDENTWRITEMASKS capabilities bit is set in the PrimitiveMiscCaps member of the D3DCAPS9 structure for the device. The default value is 0x0000000f.

D3DRS_COLORWRITEENABLE2

Additional ColorWriteEnable values for the devices. See D3DRS_COLORWRITEENABLE. This functionality is available if the D3DPMISCCAPS_INDEPENDENTWRITEMASKS capabilities bit is set in the PrimitiveMiscCaps member of the D3DCAPS9 structure for the device. The default value is 0x0000000f.

D3DRS_COLORWRITEENABLE3

Additional ColorWriteEnable values for the devices. See D3DRS_COLORWRITEENABLE. This functionality is available if the D3DPMISCCAPS_INDEPENDENTWRITEMASKS capabilities bit is set in the PrimitiveMiscCaps member of the D3DCAPS9 structure for the device. The default value is 0x0000000f.

D3DRS_BLENDFACTOR

D3DCOLOR used for a constant blend-factor during alpha blending. This functionality is available if the D3DPBLENDCAPS_BLENDFACTOR capabilities bit is set in the SrcBlendCaps member of D3DCAPS9 or the DestBlendCaps member of D3DCAPS9. See D3DRENDERSTATETYPE. The default value is 0xffffffff.

D3DRS_SRGBWRITEENABLE

Enable render-target writes to be gamma corrected to sRGB. The format must expose D3DUSAGE_SRGBWRITE. The default value is 0.

D3DRS_DEPTHBIAS

A floating-point value that is used for comparison of depth values. See Depth Bias. The default value is 0.

D3DRS_WRAP8

See D3DRS_WRAP0.

D3DRS_WRAP9

See D3DRS_WRAP0.

D3DRS_WRAP10

See D3DRS_WRAP0.

D3DRS_WRAP11

See D3DRS_WRAP0.

D3DRS_WRAP12

See D3DRS_WRAP0.

D3DRS_WRAP13

See D3DRS_WRAP0.

D3DRS_WRAP14

See D3DRS_WRAP0.

D3DRS_WRAP15

See D3DRS_WRAP0.

D3DRS_SEPARATEALPHABLENDENABLE

TRUE enables the separate blend mode for the alpha channel. The default value is FALSE.

When set to false, the render-target blending factors and operations applied to alpha are forced to be the same as those defined for color. This mode is effectively hardwired to false on implementations that don't set the cap D3DPMISCCAPS_SEPARATEALPHABLEND. See D3DPMISCCAPS.

The type of separate alpha blending is determined by the D3DRS_SRCBLENDALPHA and D3DRS_DESTBLENDALPHA render states.

D3DRS_SRCBLENDALPHA

One member of the D3DBLEND enumerated type. This value is ignored unless D3DRS_SEPARATEALPHAENABLE is true. The default value is D3DBLEND_ONE.

D3DRS_DESTBLENDALPHA

One member of the D3DBLEND enumerated type. This value is ignored unless D3DRS_SEPARATEALPHAENABLE is true. The default value is D3DBLEND_ZERO.

D3DRS_BLENDOPALPHA

Value used to select the arithmetic operation applied to separate alpha blending when the render state, D3DRS_SEPARATEALPHABLENDENABLE, is set to TRUE.

Valid values are defined by the D3DBLENDOP enumerated type. The default value is D3DBLENDOP_ADD.

If the D3DPMISCCAPS_BLENDOP device capability is not supported, then D3DBLENDOP_ADD is performed. See D3DPMISCCAPS.

D3DRS_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Render States
ps_1_1 to ps_1_3 4 texture samplers

Direct3D defines the D3DRENDERSTATE_WRAPBIAS constant as a convenience for applications to enable or disable texture wrapping, based on the zero-based integer of a texture coordinate set (rather than explicitly using one of the D3DRS_WRAP n state values). Add the D3DRENDERSTATE_WRAPBIAS value to the zero-based index of a texture coordinate set to calculate the D3DRS_WRAP n value that corresponds to that index, as shown in the following example.

// Enable U/V wrapping for textures that use the texture
// coordinate set at the index within the dwIndex variable

HRESULT hr = pd3dDevice->SetRenderState(
    dwIndex + D3DRENDERSTATE_WRAPBIAS,
    D3DWRAPCOORD_0 | D3DWRAPCOORD_1);

// If dwIndex is 3, the value that results from
// the addition equals D3DRS_WRAP3 (131)

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::GetRenderState, IDirect3DDevice9::SetRenderState


D3DRESOURCETYPE Enumerated Type

Defines resource types.

Syntax

typedef enum _D3DRESOURCETYPE {
    D3DRTYPE_SURFACE = 1,
    D3DRTYPE_VOLUME = 2,
    D3DRTYPE_TEXTURE = 3,
    D3DRTYPE_VOLUMETEXTURE = 4,
    D3DRTYPE_CUBETEXTURE = 5,
    D3DRTYPE_VERTEXBUFFER = 6,
    D3DRTYPE_INDEXBUFFER = 7,
    D3DRTYPE_FORCE_DWORD = 0x7fffffff
} D3DRESOURCETYPE;

Constants

D3DRTYPE_SURFACE

Surface resource.

D3DRTYPE_VOLUME

Volume resource.

D3DRTYPE_TEXTURE

Texture resource.

D3DRTYPE_VOLUMETEXTURE

Volume texture resource.

D3DRTYPE_CUBETEXTURE

Cube texture resource.

D3DRTYPE_VERTEXBUFFER

Vertex buffer resource.

D3DRTYPE_INDEXBUFFER

Index buffer resource.

D3DRTYPE_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DResource9::GetType


D3DSAMPLER_TEXTURE_TYPE Enumerated Type

Defines the sampler texture types for vertex shaders.

Syntax

typedef enum _D3DSAMPLER_TEXTURE_TYPE {
    D3DSTT_UNKNOWN,
    D3DSTT_1D,
    D3DSTT_2D,
    D3DSTT_CUBE,
    D3DSTT_VOLUME,
    D3DSTT_FORCE_DWORD
} D3DSAMPLER_TEXTURE_TYPE;

Constants

D3DSTT_UNKNOWN

Uninitialized value. The value of this element is D3DSP_TEXTURETYPE_SHIFT.

D3DSTT_1D

Declaring a 1-D texture. The value of this element is D3DSP_TEXTURETYPE_SHIFT * 2.

D3DSTT_2D

Declaring a 2-D texture. The value of this element is D3DSP_TEXTURETYPE_SHIFT * 4.

D3DSTT_CUBE

Declaring a cube texture. The value of this element is D3DSP_TEXTURETYPE_SHIFT * 8.

D3DSTT_VOLUME

Declaring a volume texture. The value of this element is D3DSP_TEXTURETYPE_SHIFT * 16.

D3DSTT_FORCE_DWORD

Force 32-bit size enum. The value of this element is 0x7fffffff.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98


D3DSAMPLERSTATETYPE Enumerated Type

Sampler states define texture sampling operations such as texture addressing and texture filtering. Some sampler states set-up vertex processing, and some set-up pixel processing. Sampler states can be saved and restored using stateblocks (see State Blocks Save and Restore State).

Syntax

typedef enum _D3DSAMPLERSTATETYPE {
    D3DSAMP_ADDRESSU = 1,
    D3DSAMP_ADDRESSV = 2,
    D3DSAMP_ADDRESSW = 3,
    D3DSAMP_BORDERCOLOR = 4,
    D3DSAMP_MAGFILTER = 5,
    D3DSAMP_MINFILTER = 6,
    D3DSAMP_MIPFILTER = 7,
    D3DSAMP_MIPMAPLODBIAS = 8,
    D3DSAMP_MAXMIPLEVEL = 9,
    D3DSAMP_MAXANISOTROPY = 10,
    D3DSAMP_SRGBTEXTURE = 11,
    D3DSAMP_ELEMENTINDEX = 12,
    D3DSAMP_DMAPOFFSET = 13,
    D3DSAMP_FORCE_DWORD = 0x7fffffff
} D3DSAMPLERSTATETYPE;

Constants

D3DSAMP_ADDRESSU

Texture-address mode for the u coordinate. The default is D3DTADDRESS_WRAP. For more information, see D3DTEXTUREADDRESS.

D3DSAMP_ADDRESSV

Texture-address mode for the v coordinate. The default is D3DTADDRESS_WRAP. For more information, see D3DTEXTUREADDRESS.

D3DSAMP_ADDRESSW

Texture-address mode for the w coordinate. The default is D3DTADDRESS_WRAP. For more information, see D3DTEXTUREADDRESS.

D3DSAMP_BORDERCOLOR

Border color or type D3DCOLOR. The default color is 0x00000000.

D3DSAMP_MAGFILTER

Magnification filter of type D3DTEXTUREFILTERTYPE. The default value is D3DTEXF_POINT.

D3DSAMP_MINFILTER

Minification filter of type D3DTEXTUREFILTERTYPE. The default value is D3DTEXF_POINT.

D3DSAMP_MIPFILTER

Mipmap filter to use during minification. See D3DTEXTUREFILTERTYPE. The default value is D3DTEXF_NONE.

D3DSAMP_MIPMAPLODBIAS

Mipmap level of detail (LOD) bias. The default value is zero.

D3DSAMP_MAXMIPLEVEL

LOD index of largest map to use. Values range from 0 to (n - 1) where 0 is the largest. The default value is zero.

D3DSAMP_MAXANISOTROPY

DWORD maximum anisotropy. The default value is 1.

D3DSAMP_SRGBTEXTURE

Gamma correction value. The default value is 0, which means gamma is 1.0 and no correction is required. Otherwise, this value means that the sampler should assume gamma of 2.2 on the content and convert it to linear (gamma 1.0) before presenting it to the pixel shader.

D3DSAMP_ELEMENTINDEX

When a multielement texture is assigned to the sampler, this indicates which element index to use. The default value is 0.

D3DSAMP_DMAPOFFSET

Vertex offset in the presampled displacement map. This is a constant used by the tessellator, its default value is 0.

D3DSAMP_FORCE_DWORD

This value forces a 32-bit enumeration.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98


D3DSHADEMODE Enumerated Type

Defines constants that describe the supported shading modes.

Syntax

typedef enum _D3DSHADEMODE {
    D3DSHADE_FLAT = 1,
    D3DSHADE_GOURAUD = 2,
    D3DSHADE_PHONG = 3,
    D3DSHADE_FORCE_DWORD = 0x7fffffff
} D3DSHADEMODE;

Constants

D3DSHADE_FLAT

Flat shading mode. The color and specular component of the first vertex in the triangle are used to determine the color and specular component of the face. These colors remain constant across the triangle; that is, they are not interpolated. The specular alpha is interpolated. See Remarks.

D3DSHADE_GOURAUD

Gouraud shading mode. The color and specular components of the face are determined by a linear interpolation between all three of the triangle's vertices.

D3DSHADE_PHONG

Not supported.

D3DSHADE_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The first vertex of a triangle for flat shading mode is defined in the following manner.

  • For a triangle list, the first vertex of the triangle i is i * 3.
  • For a triangle strip, the first vertex of the triangle i is vertex i.
  • For a triangle fan, the first vertex of the triangle i is vertex i + 1.

The members of this enumerated type define the vales for the D3DRS_SHADEMODE render state.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DRENDERSTATETYPE


D3DSTATEBLOCKTYPE Enumerated Type

Predefined sets of pipeline state used by state blocks (see State Blocks Save and Restore State).

Syntax

typedef enum _D3DSTATEBLOCKTYPE {
    D3DSBT_ALL = 1,
    D3DSBT_PIXELSTATE = 2,
    D3DSBT_VERTEXSTATE = 2,
    D3DSBT_FORCE_DWORD = 0xffffffff
} D3DSTATEBLOCKTYPE;

Constants

D3DSBT_ALL

Capture the current device state.

D3DSBT_PIXELSTATE

Capture the current pixel state.

D3DSBT_VERTEXSTATE

Capture the current vertex state.

D3DSBT_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

As the diagram below shows, vertex and pixel state are both subsets of device state.

There are only a few states that are considered both vertex and pixel state. These states are:

  • Render state: D3DRS_FOGDENSITY
  • Render state: D3DRS_FOGSTART
  • Render state: D3DRS_FOGEND
  • Texture state: D3DTSS_TEXCOORDINDEX
  • Texture state: D3DTSS_TEXTURETRANSFORMFLAGS

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::CreateStateBlock


D3DSTENCILOP Enumerated Type

Defines stencil-buffer operations.

Syntax

typedef enum _D3DSTENCILOP {
    D3DSTENCILOP_KEEP = 1,
    D3DSTENCILOP_ZERO = 2,
    D3DSTENCILOP_REPLACE = 3,
    D3DSTENCILOP_INCRSAT = 4,
    D3DSTENCILOP_DECRSAT = 5,
    D3DSTENCILOP_INVERT = 6,
    D3DSTENCILOP_INCR = 7,
    D3DSTENCILOP_DECR = 8,
    D3DSTENCILOP_FORCE_DWORD = 0x7fffffff
} D3DSTENCILOP;

Constants

D3DSTENCILOP_KEEP

Do not update the entry in the stencil buffer. This is the default value.

D3DSTENCILOP_ZERO

Set the stencil-buffer entry to 0.

D3DSTENCILOP_REPLACE

Replace the stencil-buffer entry with a reference value.

D3DSTENCILOP_INCRSAT

Increment the stencil-buffer entry, clamping to the maximum value.

D3DSTENCILOP_DECRSAT

Decrement the stencil-buffer entry, clamping to zero.

D3DSTENCILOP_INVERT

Invert the bits in the stencil-buffer entry.

D3DSTENCILOP_INCR

Increment the stencil-buffer entry, wrapping to zero if the new value exceeds the maximum value.

D3DSTENCILOP_DECR

Decrement the stencil-buffer entry, wrapping to the maximum value if the new value is less than zero.

D3DSTENCILOP_FORCE_DWORD

Force this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Stencil-buffer entries are integer values ranging from 0 through 2n - 1, where n is the bit depth of the stencil buffer.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98


D3DSWAPEFFECT Enumerated Type

Defines swap effects.

Syntax

typedef enum _D3DSWAPEFFECT {
    D3DSWAPEFFECT_DISCARD = 1,
    D3DSWAPEFFECT_FLIP = 2,
    D3DSWAPEFFECT_COPY = 3,
    D3DSWAPEFFECT_FORCE_DWORD = 0xFFFFFFFF
} D3DSWAPEFFECT;

Constants

D3DSWAPEFFECT_DISCARD

When a swap chain is created with a swap effect of D3DSWAPEFFECT_FLIP or D3DSWAPEFFECT_COPY, the runtime will guarantee that an IDirect3DDevice9::Present operation will not affect the content of any of the back buffers. Unfortunately, meeting this guarantee can involve substantial video memory or processing overheads, especially when implementing flip semantics for a windowed swap chain or copy semantics for a full-screen swap chain. An application may use the D3DSWAPEFFECT_DISCARD swap effect to avoid these overheads and to enable the display driver to select the most efficient presentation technique for the swap chain. This is also the only swap effect that may be used when specifying a value other than D3DMULTISAMPLE_NONE for the MultiSampleType member of D3DPRESENT_PARAMETERS.

Like a swap chain that uses D3DSWAPEFFECT_FLIP, a swap chain that uses D3DSWAPEFFECT_DISCARD might include more than one back buffer, any of which may be accessed using IDirect3DDevice9::GetBackBuffer or IDirect3DSwapChain9::GetBackBuffer. The swap chain is best envisaged as a queue in which 0 always indexes the back buffer that will be displayed by the next Present operation and from which buffers are discarded when they have been displayed.

An application that uses this swap effect cannot make any assumptions about the contents of a discarded back buffer and should therefore update an entire back buffer before invoking a Present operation that would display it. Although this is not enforced, the debug version of the runtime will overwrite the contents of discarded back buffers with random data to enable developers to verify that their applications are updating the entire back buffer surfaces correctly.

D3DSWAPEFFECT_FLIP

The swap chain might include multiple back buffers and is best envisaged as a circular queue that includes the front buffer. Within this queue, the back buffers are always numbered sequentially from 0 to (n - 1), where n is the number of back buffers, so that 0 denotes the least recently presented buffer. When Present is invoked, the queue is "rotated" so that the front buffer becomes back buffer (n - 1), while the back buffer 0 becomes the new front buffer.

D3DSWAPEFFECT_COPY

This swap effect may be specified only for a swap chain comprising a single back buffer. Whether the swap chain is windowed or full-screen, the runtime will guarantee the semantics implied by a copy-based Present operation, namely that the operation leaves the content of the back buffer unchanged, instead of replacing it with the content of the front buffer as a flip-based Present operation would.

For a full-screen swap chain, the runtime uses a combination of flip operations and copy operations, supported if necessary by hidden back buffers, to accomplish the Present operation. Accordingly, the presentation is synchronized with the display adapter's vertical retrace and its rate is constrained by the chosen presentation interval. A swap chain specified with the D3DPRESENT_INTERVAL_IMMEDIATE flag is the only exception. (Refer to the description of the PresentationIntervals member of the D3DPRESENT_PARAMETERS structure.) In this case, a Present operation copies the back buffer content directly to the front buffer without waiting for the vertical retrace.

D3DSWAPEFFECT_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The state of the back buffer after a call to Present is well-defined by each of these swap effects, and whether the Microsoft Direct3D device was created with a full-screen swap chain or a windowed swap chain has no effect on this state. In particular, the D3DSWAPEFFECT_FLIP swap effect operates the same whether windowed or full-screen, and the Direct3D runtime guarantees this by creating extra buffers. As a result, it is recommended that applications use D3DSWAPEFFECT_DISCARD whenever possible to avoid any such penalties. This is because this swap effect will always be the most efficient in terms of memory consumption and performance.

Applications that use D3DSWAPEFFECT_FLIP or D3DSWAPEFFECT_DISCARD should not expect full-screen destination alpha to work. This means that the D3DRS_DESTBLEND render state will not work as expected because full-screen swap chains with these swap effects do not have an explicit pixel format from the driver's point of view. The driver infers that they should take on the display format, which does not have an alpha channel. To work around this, take the following steps:

  • Use D3DSWAPEFFECT_COPY.
  • Check the D3DCAPS3_ALPHA_FULLSCREEN_FLIP_OR_DISCARD flag in the Caps3 member of the D3DCAPS9 structure. This flag indicates whether the driver can do alpha blending when D3DSWAPEFFECT_FLIP or D3DSWAPEFFECT_DISCARD is used.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::Reset, D3DPRESENT_PARAMETERS


D3DTEXTUREADDRESS Enumerated Type

Defines constants that describe the supported texture-addressing modes.

Syntax

typedef enum _D3DTEXTUREADDRESS {
    D3DTADDRESS_WRAP = 1,
    D3DTADDRESS_MIRROR = 2,
    D3DTADDRESS_CLAMP = 3,
    D3DTADDRESS_BORDER = 4,
    D3DTADDRESS_MIRRORONCE = 5,
    D3DTADDRESS_FORCE_DWORD = 0x7fffffff
} D3DTEXTUREADDRESS;

Constants

D3DTADDRESS_WRAP

Tile the texture at every integer junction. For example, for u values between 0 and 3, the texture is repeated three times; no mirroring is performed.

D3DTADDRESS_MIRROR

Similar to D3DTADDRESS_WRAP, except that the texture is flipped at every integer junction. For u values between 0 and 1, for example, the texture is addressed normally; between 1 and 2, the texture is flipped (mirrored); between 2 and 3, the texture is normal again, and so on.

D3DTADDRESS_CLAMP

Texture coordinates outside the range [0.0, 1.0] are set to the texture color at 0.0 or 1.0, respectively.

D3DTADDRESS_BORDER

Texture coordinates outside the range [0.0, 1.0] are set to the border color.

D3DTADDRESS_MIRRORONCE

Similar to D3DTADDRESS_MIRROR and D3DTADDRESS_CLAMP. Takes the absolute value of the texture coordinate (thus, mirroring around 0), and then clamps to the maximum value. The most common usage is for volume textures, where support for the full D3DTADDRESS_MIRRORONCE texture-addressing mode is not necessary, but the data is symmetric around the one axis.

D3DTADDRESS_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DSAMPLERSTATETYPE


D3DTEXTUREFILTERTYPE Enumerated Type

Defines texture filtering modes for a texture stage.

Syntax

typedef enum _D3DTEXTUREFILTERTYPE {
    D3DTEXF_NONE = 0,
    D3DTEXF_POINT = 1,
    D3DTEXF_LINEAR = 2,
    D3DTEXF_ANISOTROPIC = 3,
    D3DTEXF_PYRAMIDALQUAD = 6,
    D3DTEXF_GAUSSIANQUAD = 7,
    D3DTEXF_FORCE_DWORD = 0x7fffffff
} D3DTEXTUREFILTERTYPE;

Constants

D3DTEXF_NONE

Mipmapping disabled. The rasterizer should use the magnification filter instead.

D3DTEXF_POINT

Point filtering used as a texture magnification or minification filter. The texel with coordinates nearest to the desired pixel value is used. The texture filter to be used between mipmap levels is nearest-point mipmap filtering. The rasterizer uses the color from the texel of the nearest mipmap texture.

D3DTEXF_LINEAR

Bilinear interpolation filtering used as a texture magnification or minification filter. A weighted average of a 2x2 area of texels surrounding the desired pixel is used. The texture filter to use between mipmap levels is trilinear mipmap interpolation. The rasterizer linearly interpolates pixel color, using the texels of the two nearest mipmap textures.

D3DTEXF_ANISOTROPIC

Anisotropic texture filtering used as a texture magnification or minification filter. Compensates for distortion caused by the difference in angle between the texture polygon and the plane of the screen.

D3DTEXF_PYRAMIDALQUAD

A 4-sample tent filter used as a texture magnification or minification filter.

D3DTEXF_GAUSSIANQUAD

A 4-sample Gaussian filter used as a texture magnification or minification filter.

D3DTEXF_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

To check if a format supports texture filter types other than D3DTEXF_POINT (which is always supported), call IDirect3D9::CheckDeviceFormat with D3DUSAGE_QUERY_FILTER.

Set a texture stage's magnification filter by calling IDirect3DDevice9::SetSamplerState with the D3DSAMP_MAGFILTER value as the second parameter and one member of this enumeration as the third parameter.

Set a texture stage's minification filter by calling IDirect3DDevice9::SetSamplerState with the D3DSAMP_MINFILTER value as the second parameter and one member of this enumeration as the third parameter.

Set the texture filter to use between-mipmap levels by calling IDirect3DDevice9::SetSamplerState with the D3DSAMP_MIPFILTER value as the second parameter and one member of this enumeration as the third parameter.

Not all valid filtering modes for a device will apply to volume maps. In general, D3DTEXF_POINT and D3DTEXF_LINEAR magnification filters will be supported for volume maps. If D3DPTEXTURECAPS_MIPVOLUMEMAP is set, then the D3DTEXF_POINT mipmap filter and D3DTEXF_POINT and D3DTEXF_LINEAR minification filters will be supported for volume maps. The device may or may not support the D3DTEXF_LINEAR mipmap filter for volume maps. Devices that support anisotropic filtering for 2-D maps do not necessarily support anisotropic filtering for volume maps. However, applications that enable anisotropic filtering will receive the best available filtering (probably linear) if anisotropic filtering is not supported.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

ID3DXPatchMesh::GetDisplaceParam, ID3DXPatchMesh::SetDisplaceParam, D3DSAMPLERSTATETYPE


D3DTEXTUREOP Enumerated Type

Defines per-stage texture-blending operations.

Syntax

typedef enum _D3DTEXTUREOP {
    D3DTOP_DISABLE = 1,
    D3DTOP_SELECTARG1 = 2,
    D3DTOP_SELECTARG2 = 3,
    D3DTOP_MODULATE = 4,
    D3DTOP_MODULATE2X = 5,
    D3DTOP_MODULATE4X = 6,
    D3DTOP_ADD = 7,
    D3DTOP_ADDSIGNED = 8,
    D3DTOP_ADDSIGNED2X = 9,
    D3DTOP_SUBTRACT = 10,
    D3DTOP_ADDSMOOTH = 11,
    D3DTOP_BLENDDIFFUSEALPHA = 12,
    D3DTOP_BLENDTEXTUREALPHA = 13,
    D3DTOP_BLENDFACTORALPHA = 14,
    D3DTOP_BLENDTEXTUREALPHAPM = 15,
    D3DTOP_BLENDCURRENTALPHA = 16,
    D3DTOP_PREMODULATE = 17,
    D3DTOP_MODULATEALPHA_ADDCOLOR = 18,
    D3DTOP_MODULATECOLOR_ADDALPHA = 19,
    D3DTOP_MODULATEINVALPHA_ADDCOLOR = 20,
    D3DTOP_MODULATEINVCOLOR_ADDALPHA = 21,
    D3DTOP_BUMPENVMAP = 22,
    D3DTOP_BUMPENVMAPLUMINANCE = 23,
    D3DTOP_DOTPRODUCT3 = 24,
    D3DTOP_MULTIPLYADD = 25,
    D3DTOP_LERP = 26,
    D3DTOP_FORCE_DWORD = 0x7fffffff
} D3DTEXTUREOP;

Constants

D3DTOP_DISABLE

Disables output from this texture stage and all stages with a higher index. To disable texture mapping, set this as the color operation for the first texture stage (stage 0). Alpha operations cannot be disabled when color operations are enabled. Setting the alpha operation to D3DTOP_DISABLE when color blending is enabled causes undefined behavior.

D3DTOP_SELECTARG1

Use this texture stage's first color or alpha argument, unmodified, as the output. This operation affects the color argument when used with the D3DTSS_COLOROP texture-stage state, and the alpha argument when used with D3DTSS_ALPHAOP.

D3DTOP_SELECTARG2

Use this texture stage's second color or alpha argument, unmodified, as the output. This operation affects the color argument when used with the D3DTSS_COLOROP texture stage state, and the alpha argument when used with D3DTSS_ALPHAOP.

D3DTOP_MODULATE

Multiply the components of the arguments.

D3DTOP_MODULATE2X

Multiply the components of the arguments, and shift the products to the left 1 bit (effectively multiplying them by 2) for brightening.

D3DTOP_MODULATE4X

Multiply the components of the arguments, and shift the products to the left 2 bits (effectively multiplying them by 4) for brightening.

D3DTOP_ADD

Add the components of the arguments.

D3DTOP_ADDSIGNED

Add the components of the arguments with a –0.5 bias, making the effective range of values from –0.5 through 0.5.

D3DTOP_ADDSIGNED2X

Add the components of the arguments with a –0.5 bias, and shift the products to the left 1 bit.

D3DTOP_SUBTRACT

Subtract the components of the second argument from those of the first argument.

D3DTOP_ADDSMOOTH

Add the first and second arguments; then subtract their product from the sum.

D3DTOP_BLENDDIFFUSEALPHA

Linearly blend this texture stage, using the interpolated alpha from each vertex.

D3DTOP_BLENDTEXTUREALPHA

Linearly blend this texture stage, using the alpha from this stage's texture.

D3DTOP_BLENDFACTORALPHA

Linearly blend this texture stage, using a scalar alpha set with the D3DRS_TEXTUREFACTOR render state.

D3DTOP_BLENDTEXTUREALPHAPM

Linearly blend a texture stage that uses a premultiplied alpha.

D3DTOP_BLENDCURRENTALPHA

Linearly blend this texture stage, using the alpha taken from the previous texture stage.

D3DTOP_PREMODULATE

D3DTOP_PREMODULATE is set in stage n. The output of stage n is arg1. Additionally, if there is a texture in stage n+1, any D3DTA_CURRENT in stage n+1 is premultiplied by texture in stage n+1.

D3DTOP_MODULATEALPHA_ADDCOLOR

Modulate the color of the second argument, using the alpha of the first argument; then add the result to argument one. This operation is supported only for color operations (D3DTSS_COLOROP).

D3DTOP_MODULATECOLOR_ADDALPHA

Modulate the arguments; then add the alpha of the first argument. This operation is supported only for color operations (D3DTSS_COLOROP).

D3DTOP_MODULATEINVALPHA_ADDCOLOR

Similar to D3DTOP_MODULATEALPHA_ADDCOLOR, but use the inverse of the alpha of the first argument. This operation is supported only for color operations (D3DTSS_COLOROP).

D3DTOP_MODULATEINVCOLOR_ADDALPHA

Similar to D3DTOP_MODULATECOLOR_ADDALPHA, but use the inverse of the color of the first argument. This operation is supported only for color operations (D3DTSS_COLOROP).

D3DTOP_BUMPENVMAP

Perform per-pixel bump mapping, using the environment map in the next texture stage, without luminance. This operation is supported only for color operations (D3DTSS_COLOROP).

D3DTOP_BUMPENVMAPLUMINANCE

Perform per-pixel bump mapping, using the environment map in the next texture stage, with luminance. This operation is supported only for color operations (D3DTSS_COLOROP).

D3DTOP_DOTPRODUCT3

Modulate the components of each argument as signed components, add their products; then replicate the sum to all color channels, including alpha. This operation is supported for color and alpha operations.

In Microsoft DirectX 6.0 and DirectX 7.0 multitexture operations the above inputs are all shifted down by half (y = x - 0.5) before use to simulate signed data, and the scalar result is automatically clamped to positive values and replicated to all three output channels. Also, note that as a color operation this does not updated the alpha it just updates the rgb components.

However, in DirectX 8.1 shaders you can specify that the output be routed to the .rgb or the .a components or both (the default). You can also specify a separate scalar operation on the alpha channel.

D3DTOP_MULTIPLYADD

Performs a multiply-accumulate operation. It takes the last two arguments, multiplies them together, and adds them to the remaining input/source argument, and places that into the result.

SRGBA = Arg1 + Arg2 * Arg3

D3DTOP_LERP

Linearly interpolates between the 2nd and 3rd source arguments by a proportion specified in the 1st source argument.

SRGBA = (Arg1) * Arg2 + (1- Arg1) * Arg3.

D3DTOP_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The members of this type are used when setting color or alpha operations by using the D3DTSS_COLOROP or D3DTSS_ALPHAOP values with the IDirect3DDevice9::SetTextureStageState method.

In the above formulas, SRGBA is the RGBA color produced by a texture operation, and Arg1, Arg2, and Arg3 represent the complete RGBA color of the texture arguments. Individual components of an argument are shown with subscripts. For example, the alpha component for argument 1 would be shown as Arg1A.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DTEXTURESTAGESTATETYPE


D3DTEXTURESTAGESTATETYPE Enumerated Type

Texture stage states define multi-blender texture operations. Some sampler states set-up vertex processing, and some set-up pixel processing. Texture stage states can be saved and restored using stateblocks (see State Blocks Save and Restore State).

Syntax

typedef enum _D3DTEXTURESTAGESTATETYPE {
    D3DTSS_COLOROP = 1,
    D3DTSS_COLORARG1 = 2,
    D3DTSS_COLORARG2 = 3,
    D3DTSS_ALPHAOP = 4,
    D3DTSS_ALPHAARG1 = 5,
    D3DTSS_ALPHAARG2 = 6,
    D3DTSS_BUMPENVMAT00 = 7,
    D3DTSS_BUMPENVMAT01 = 8,
    D3DTSS_BUMPENVMAT10 = 9,
    D3DTSS_BUMPENVMAT11 = 10,
    D3DTSS_TEXCOORDINDEX = 11,
    D3DTSS_BUMPENVLSCALE = 22,
    D3DTSS_BUMPENVLOFFSET = 23,
    D3DTSS_TEXTURETRANSFORMFLAGS = 24,
    D3DTSS_COLORARG0 = 26,
    D3DTSS_ALPHAARG0 = 27,
    D3DTSS_RESULTARG = 28,
    D3DTSS_CONSTANT = 32,
    D3DTSS_FORCE_DWORD = 0x7fffffff
} D3DTEXTURESTAGESTATETYPE;

Constants

D3DTSS_COLOROP

Texture-stage state is a texture color blending operation identified by one member of the D3DTEXTUREOP enumerated type. The default value for the first texture stage (stage 0) is D3DTOP_MODULATE; for all other stages the default is D3DTOP_DISABLE.

D3DTSS_COLORARG1

Texture-stage state is the first color argument for the stage, identified by one of the D3DTA. The default argument is D3DTA_TEXTURE.

Specify D3DTA_TEMP to select a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default value for the register is (0.0, 0.0, 0.0, 0.0).

D3DTSS_COLORARG2

Texture-stage state is the second color argument for the stage, identified by D3DTA. The default argument is D3DTA_CURRENT. Specify D3DTA_TEMP to select a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default value for the register is (0.0, 0.0, 0.0, 0.0)

D3DTSS_ALPHAOP

Texture-stage state is a texture alpha blending operation identified by one member of the D3DTEXTUREOP enumerated type. The default value for the first texture stage (stage 0) is D3DTOP_SELECTARG1, and for all other stages the default is D3DTOP_DISABLE.

D3DTSS_ALPHAARG1

Texture-stage state is the first alpha argument for the stage, identified by by D3DTA. The default argument is D3DTA_TEXTURE. If no texture is set for this stage, the default argument is D3DTA_DIFFUSE. Specify D3DTA_TEMP to select a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default value for the register is (0.0, 0.0, 0.0, 0.0).

D3DTSS_ALPHAARG2

Texture-stage state is the second alpha argument for the stage, identified by by D3DTA. The default argument is D3DTA_CURRENT. Specify D3DTA_TEMP to select a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default value for the register is (0.0, 0.0, 0.0, 0.0).

D3DTSS_BUMPENVMAT00

Texture-stage state is a floating-point value for the [0][0] coefficient in a bump-mapping matrix. The default value is 0.0.

D3DTSS_BUMPENVMAT01

Texture-stage state is a floating-point value for the [0][1] coefficient in a bump-mapping matrix. The default value is 0.0.

D3DTSS_BUMPENVMAT10

Texture-stage state is a floating-point value for the [1][0] coefficient in a bump-mapping matrix. The default value is 0.0.

D3DTSS_BUMPENVMAT11

Texture-stage state is a floating-point value for the [1][1] coefficient in a bump-mapping matrix. The default value is 0.0.

D3DTSS_TEXCOORDINDEX

Index of the texture coordinate set to use with this texture stage. You can specify up to eight sets of texture coordinates per vertex. If a vertex does not include a set of texture coordinates at the specified index, the system defaults to the u and v coordinates (0,0).

When rendering using vertex shaders, each stage's texture coordinate index must be set to its default value. The default index for each stage is equal to the stage index. Set this state to the zero-based index of the coordinate set for each vertex that this texture stage uses.

Additionally, applications can include, as logical OR with the index being set, one of the constants to request that Microsoft Direct3D automatically generate the input texture coordinates for a texture transformation. For a list of all the constants, see D3DTSS.

With the exception of D3DTSS_TCI_PASSTHRU, which resolves to zero, if any of the following values is included with the index being set, the system uses the index strictly to determine texture wrapping mode. These flags are most useful when performing environment mapping.

D3DTSS_BUMPENVLSCALE

Floating-point scale value for bump-map luminance. The default value is 0.0.

D3DTSS_BUMPENVLOFFSET

Floating-point offset value for bump-map luminance. The default value is 0.0.

D3DTSS_TEXTURETRANSFORMFLAGS

Member of the D3DTEXTURETRANSFORMFLAGS enumerated type that controls the transformation of texture coordinates for this texture stage. The default value is D3DTTFF_DISABLE.

D3DTSS_COLORARG0

Settings for the third color operand for triadic operations (multiply, add, and linearly interpolate), identified by D3DTA. This setting is supported if the D3DTEXOPCAPS_MULTIPLYADD or D3DTEXOPCAPS_LERP device capabilities are present. The default argument is D3DTA_CURRENT. Specify D3DTA_TEMP to select a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default value for the register is (0.0, 0.0, 0.0, 0.0).

D3DTSS_ALPHAARG0

Settings for the alpha channel selector operand for triadic operations (multiply, add, and linearly interpolate), identified by D3DTA. This setting is supported if the D3DTEXOPCAPS_MULTIPLYADD or D3DTEXOPCAPS_LERP device capabilities are present. The default argument is D3DTA_CURRENT. Specify D3DTA_TEMP to select a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default argument is (0.0, 0.0, 0.0, 0.0).

D3DTSS_RESULTARG

Setting to select destination register for the result of this stage, identified by D3DTA. This value can be set to D3DTA_CURRENT (the default value) or to D3DTA_TEMP, which is a single temporary register that can be read into subsequent stages as an input argument. The final color passed to the fog blender and frame buffer is taken from D3DTA_CURRENT, so the last active texture stage state must be set to write to current. This setting is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present.

D3DTSS_CONSTANT

Per-stage constant color. To see if a device supports a per-stage constant color, see the D3DPMISCCAPS_PERSTAGECONSTANT constant in D3DPMISCCAPS. D3DTSS_CONSTANT is used by D3DTA_CONSTANT. See D3DTA.

D3DTSS_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Members of this enumerated type are used with the IDirect3DDevice9::GetTextureStageState and IDirect3DDevice9::SetTextureStageState methods to retrieve and set texture state values.

The valid range of values for the D3DTSS_BUMPENVMAT00, D3DTSS_BUMPENVMAT01, D3DTSS_BUMPENVMAT10, and D3DTSS_BUMPENVMAT11 bump-mapping matrix coefficients is greater than or equal to -8.0 and less than 8.0. This range, expressed in mathematical notation is (-8.0,8.0).

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::GetTextureStageState, IDirect3DDevice9::SetTextureStageState


D3DTEXTURETRANSFORMFLAGS Enumerated Type

Defines texture coordinate transformation values.

Syntax

typedef enum _D3DTEXTURETRANSFORMFLAGS {
    D3DTTFF_DISABLE = 0,
    D3DTTFF_COUNT1 = 1,
    D3DTTFF_COUNT2 = 2,
    D3DTTFF_COUNT3 = 3,
    D3DTTFF_COUNT4 = 4,
    D3DTTFF_PROJECTED = 256,
    D3DTTFF_FORCE_DWORD = 0x7fffffff
} D3DTEXTURETRANSFORMFLAGS;

Constants

D3DTTFF_DISABLE

Texture coordinates are passed directly to the rasterizer.

D3DTTFF_COUNT1

The rasterizer should expect 1-D texture coordinates. This value is used by fixed function vertex processing; it should be set to 0 when using a programmable vertex shader.

D3DTTFF_COUNT2

The rasterizer should expect 2-D texture coordinates. This value is used by fixed function vertex processing; it should be set to 0 when using a programmable vertex shader.

D3DTTFF_COUNT3

The rasterizer should expect 3-D texture coordinates. This value is used by fixed function vertex processing; it should be set to 0 when using a programmable vertex shader.

D3DTTFF_COUNT4

The rasterizer should expect 4-D texture coordinates. This value is used by fixed function vertex processing; it should be set to 0 when using a programmable vertex shader.

D3DTTFF_PROJECTED

This flag is honored by the fixed function pixel pipeline, as well as the programmable pixel pipeline in versions ps_1_1 to ps_1_3. When texture projection is enabled for a texture stage, all four floating point values must be written to the corresponding texture register. Each texture coordinate is divided by the last element before being passed to the rasterizer. For example, if this flag is specified with the D3DTTFF_COUNT3 flag, the first and second texture coordinates are divided by the third coordinate before being passed to the rasterizer.

D3DTTFF_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Texture coordinates can be transformed using a 4x4 matrix before the results are passed to the rasterizer. The texture coordinate transforms are set by calling IDirect3DDevice9::SetTextureStageState, and by passing in the D3DTSS_TEXTURETRANSFORMFLAGS texture stage state and one of the values from D3DTEXTURETRANSFORMFLAGS. For more information about texture transforms, see Texture Coordinate Transformations.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DTEXTURESTAGESTATETYPE


D3DTRANSFORMSTATETYPE Enumerated Type

Defines constants that describe transformation state values.

Syntax

typedef enum _D3DTRANSFORMSTATETYPE {
    D3DTS_VIEW = 2,
    D3DTS_PROJECTION = 3,
    D3DTS_TEXTURE0 = 16,
    D3DTS_TEXTURE1 = 17,
    D3DTS_TEXTURE2 = 18,
    D3DTS_TEXTURE3 = 19,
    D3DTS_TEXTURE4 = 20,
    D3DTS_TEXTURE5 = 21,
    D3DTS_TEXTURE6 = 22,
    D3DTS_TEXTURE7 = 23,
    D3DTS_FORCE_DWORD = 0x7fffffff
} D3DTRANSFORMSTATETYPE;

Constants

D3DTS_VIEW

Identifies the transformation matrix being set as the view transformation matrix. The default value is NULL (the identity matrix).

D3DTS_PROJECTION

Identifies the transformation matrix being set as the projection transformation matrix. The default value is NULL (the identity matrix).

D3DTS_TEXTURE0

Identifies the transformation matrix being set for the specified texture stage.

D3DTS_TEXTURE1

Identifies the transformation matrix being set for the specified texture stage.

D3DTS_TEXTURE2

Identifies the transformation matrix being set for the specified texture stage.

D3DTS_TEXTURE3

Identifies the transformation matrix being set for the specified texture stage.

D3DTS_TEXTURE4

Identifies the transformation matrix being set for the specified texture stage.

D3DTS_TEXTURE5

Identifies the transformation matrix being set for the specified texture stage.

D3DTS_TEXTURE6

Identifies the transformation matrix being set for the specified texture stage.

D3DTS_TEXTURE7

Identifies the transformation matrix being set for the specified texture stage.

D3DTS_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The transform states in the range 256 through 511 are reserved to store up to 256 world matrices that can be indexed using the D3DTS_WORLDMATRIX and D3DTS_WORLD macros.

Macros
D3DTS_WORLD | Equivalent to D3DTS_WORLDMATRIX(0).
D3DTS_WORLDMATRIX(index) | Identifies the transform matrix to set for the world matrix at index. Multiple world matrices are used only for Vertex Blending. Otherwise only D3DTS_WORLD is used.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

IDirect3DDevice9::GetTransform, IDirect3DDevice9::MultiplyTransform, IDirect3DDevice9::SetTransform, D3DTS_WORLD, D3DTS_WORLDn, D3DTS_WORLDMATRIX


D3DVERTEXBLENDFLAGS Enumerated Type

Defines flags used to control the number or matrices that the system applies when performing multimatrix vertex blending.

Syntax

typedef enum _D3DVERTEXBLENDFLAGS {
    D3DVBF_DISABLE = 0,
    D3DVBF_1WEIGHTS = 1,
    D3DVBF_2WEIGHTS = 2,
    D3DVBF_3WEIGHTS = 3,
    D3DVBF_TWEENING = 255,
    D3DVBF_0WEIGHTS = 256
} D3DVERTEXBLENDFLAGS;

Constants

D3DVBF_DISABLE

Disable vertex blending; apply only the world matrix set by the D3DTS_WORLDMATRIX macro, where the index value for the transformation state is 0.

D3DVBF_1WEIGHTS

Enable vertex blending between the two matrices set by the D3DTS_WORLDMATRIX macro, where the index value for the transformation states are 0 and 1.

D3DVBF_2WEIGHTS

Enable vertex blending between the three matrices set by the D3DTS_WORLDMATRIX macro, where the index value for the transformation states are 0, 1, and 2.

D3DVBF_3WEIGHTS

Enable vertex blending between the four matrices set by the D3DTS_WORLDMATRIX macro, where the index value for the transformation states are 0, 1, 2, and 3.

D3DVBF_TWEENING

Vertex blending is done by using the value assigned to D3DRS_TWEENFACTOR.

D3DVBF_0WEIGHTS

Use a single matrix with a weight of 1.0.

Remarks

Members of this type are used with the D3DRS_VERTEXBLEND render state.

Geometry blending (multimatrix vertex blending) requires that your application use a vertex format that has blending (beta) weights for each vertex.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DRENDERSTATETYPE, D3DTS_WORLD, D3DTS_WORLDn, D3DTS_WORLDMATRIX


D3DZBUFFERTYPE Enumerated Type

Defines constants that describe depth-buffer formats.

Syntax

typedef enum _D3DZBUFFERTYPE {
    D3DZB_FALSE = 0,
    D3DZB_TRUE = 1,
    D3DZB_USEW = 2,
    D3DZB_FORCE_DWORD = 0x7fffffff
} D3DZBUFFERTYPE;

Constants

D3DZB_FALSE

Disable depth buffering.

D3DZB_TRUE

Enable z-buffering.

D3DZB_USEW

Enable w-buffering.

D3DZB_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Members of this enumerated type are used with the D3DRS_ZENABLE render state.

Enumerated Type Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DRENDERSTATETYPE


Constants
Microsoft DirectX 9.0 SDK Update (October 2004)

Constants

This section contains reference information for the constants defined in Microsoft Direct3D.

  • D3DADAPTER_DEFAULT - Primary display adapter constant
  • D3DCAPS2 - Driver capability flags
  • D3DCAPS3 - Driver capability flags
  • D3DCLEAR - Stencil clear constants
  • D3DCREATE - Device creation constants
  • D3DCURSORCAPS - Device cursor constants
  • D3DDEVCAPS2 - Driver capability constants
  • D3DDTCAPS - Vertex data constants
  • D3DENUM - Enumeration constants
  • D3DFVF - Flexible vertex format constants
  • D3DLOCK - Locking constants
  • D3DPMISCCAPS - Driver primitive constants
  • D3DPRESENT - Presentation timing constants
  • D3DPRESENTFLAG - Presentation constants
  • D3DPS20CAPS - Pixel shader "2_0 Extended" constants
  • D3DPTFILTERCAPS - Texture filtering constants
  • D3DSTENCILCAPS - Driver stencil capability flags
  • D3DTA - Texture argument constants
  • D3DTSS - Texture coordinate constants
  • D3DUSAGE - Resource usage constants
  • D3DUSAGE_QUERY - Resource query usage constants
  • D3DVS20CAPS - Vertex shader "2_0 Extended" constants
  • D3DVERTEXTEXTURESAMPLER - Vertex shader samplers
  • D3DVTXPCAPS - Device create constants
  • Other Direct3D Constants - Other constants


D3DADAPTER_DEFAULT
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DADAPTER_DEFAULT

Specifies the primary display adapter.

#define | Value | Description
D3DADAPTER_DEFAULT | 0 | Used to specify the primary display adapter.

Constant Information

Header | d3d9.h
Minimum operating system | Windows 98


D3DCAPS2
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DCAPS2

Driver capability flags.

#define | Value | Description
D3DCAPS2_CANAUTOGENMIPMAP | 0x40000000L | The driver is capable of automatically generating mipmaps. For more information, see Automatic Generation of Mipmaps.
D3DCAPS2_CANCALIBRATEGAMMA | 0x00100000L | The system has a calibrator installed that can automatically adjust the gamma ramp so that the result is identical on all systems that have a calibrator. To invoke the calibrator when setting new gamma levels, use the D3DSGR_CALIBRATE flag when calling IDirect3DDevice9::SetGammaRamp. Calibrating gamma ramps incurs some processing overhead and should not be used frequently.
D3DCAPS2_CANMANAGERESOURCE | 0x10000000L | The driver is capable of managing resources. On such drivers, D3DPOOL_MANAGED resources will be managed by the driver. To have Microsoft Direct3D override the driver so that Direct3D manages resources, use the D3DCREATE_DISABLE_DRIVER_MANAGEMENT flag when calling IDirect3D9::CreateDevice.
D3DCAPS2_DYNAMICTEXTURES | 0x20000000L | The driver supports dynamic textures.
D3DCAPS2_FULLSCREENGAMMA | 0x00020000L | The driver supports dynamic gamma ramp adjustment in full-screen mode.
D3DCAPS2_RESERVED | 0x02000000L | Reserved; not used.

These constants are used by the D3CAPS2 member of D3DCAPS9.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98


D3DCAPS3
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DCAPS3

Driver capability flags.

#define | Value | Description
D3DCAPS3_ALPHA_FULLSCREEN_FLIP_OR_DISCARD 0x00000020L Indicates that the device can respect the D3DRS_ALPHABLENDENABLE render state in full-screen mode while using the FLIP or DISCARD swap effect. This only applies when the D3DRS_SRCBLEND or D3DRS_DESTBLEND states are set to one of the following:
  • D3DBLEND_DESTALPHA
  • D3DBLEND_INVDESTALPHA
  • D3DBLEND_DESTCOLOR
  • D3DBLEND_INVDESTCOLOR
D3DCAPS3_COPY_TO_VIDMEM | 0x00000100L | Device can accelerate a memory copy from system memory to local video memory. This cap guarantees that IDirect3DDevice9::UpdateSurface and IDirect3DDevice9::UpdateTexture calls will be hardware accelerated. If this cap is absent, these calls will succeed but will be slower.
D3DCAPS3_COPY_TO_SYSTEMMEM | 0x00000200L | Device can accelerate a memory copy from local video memory to system memory. This cap guarantees that IDirect3DDevice9::GetRenderTargetData calls will be hardware accelerated. If this cap is absent, this call will succeed but will be slower.
D3DCAPS3_LINEAR_TO_SRGB_PRESENTATION | 0x00000080L | Indicates that the device can perform gamma correction from a windowed back buffer (containing linear content) to an sRGB desktop.
D3DCAPS3_RESERVED | 0x8000001fL | Reserved; not used.

These constants are used by the D3CAPS3 member of D3DCAPS9.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98


D3DCLEAR
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DCLEAR

These flags identify a surface to reset when calling IDirect3DDevice9::Clear.

#define | Description
D3DCLEAR_STENCIL | Clear the stencil buffer.
D3DCLEAR_TARGET | Clear a render target, or all targets in a multiple render target. See Multiple Render Targets.
D3DCLEAR_ZBUFFER | Clear the depth buffer.

Constant Information

Header | d3d9types.h
Minimum operating system | Windows 98


D3DCREATE
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DCREATE

A combination of one or more flags that control the device create behavior.

#define | Description
D3DCREATE_ADAPTERGROUP_DEVICE | Application asks the device to drive all the heads that this master adapter owns. The flag is illegal on nonmaster adapters. If this flag is set, the presentation parameters passed to IDirect3D9::CreateDevice should point to an array of D3DPRESENT_PARAMETERS. The number of elements in D3DPRESENT_PARAMETERS should equal the number of adapters defined by the NumberOfAdaptersInGroup member of the D3DCAPS9 structure. The Microsoft DirectX runtime will assign each element to each head in the numerical order specified by the AdapterOrdinalInGroup member of D3DCAPS9.
D3DCREATE_DISABLE_DRIVER_MANAGEMENT | Microsoft Direct3D will manage resources instead of the driver. Direct3D calls will not fail for resource errors such as insufficient video memory.
D3DCREATE_DISABLE_DRIVER_MANAGEMENT_EX | Like D3DCREATE_DISABLE_DRIVER_MANAGEMENT, Direct3D will manage resources instead of the driver. Unlike D3DCREATE_DISABLE_DRIVER_MANAGEMENT, D3DCREATE_DISABLE_DRIVER_MANAGEMENT_EX will return errors for conditions such as insufficient video memory.
D3DCREATE_FPU_PRESERVE | Indicates that the application needs either double-precision floating-point unit (FPU) or FPU exceptions enabled. Direct3D sets the FPU state each time it is called. By default, the pipeline uses single precision. Be sure to use this flag to get double precision. Setting the flag will reduce Direct3D performance.
D3DCREATE_HARDWARE_VERTEXPROCESSING | Specifies hardware vertex processing.
D3DCREATE_MIXED_VERTEXPROCESSING | Specifies mixed (both software and hardware) vertex processing.
D3DCREATE_MULTITHREADED | Indicates that the application requests Direct3D to be multithread safe. This makes a Direct3D thread take ownership of its global critical section World Wide Web link more frequently, which can degrade performance.
D3DCREATE_NOWINDOWCHANGES | Indicates that Direct3D must not alter the focus window in any way. Warning If this flag is set, the application must fully support all focus management events, such as ALT+TAB and mouse click events.
D3DCREATE_PUREDEVICE | Specifies that Direct3D does not support Get* calls for anything that can be stored in state blocks. It also tells Direct3D not to provide any emulation services for vertex processing. This means that if the device does not support vertex processing, then the application can use only post-transformed vertices.
D3DCREATE_SOFTWARE_VERTEXPROCESSING | Specifies software vertex processing.

D3DCREATE_HARDWARE_VERTEXPROCESSING, D3DCREATE_MIXED_VERTEXPROCESSING, and D3DCREATE_SOFTWARE_VERTEXPROCESSING are mutually exclusive flags. At least one of these vertex processing flags must be specified when calling IDirect3D9::CreateDevice.

Constant Information

Header | d3d9.h
Minimum operating system | Windows 98


D3DCURSORCAPS
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DCURSORCAPS

Driver cursor capability flags.

#define | Value | Description
D3DCURSORCAPS_COLOR | 0x00000001L | The driver supports hardware color cursor in at least high resolution modes (height >= 400).
D3DCURSORCAPS_LOWRES | 0x00000002L | The driver supports hardware color cursor in low resolution modes (height < 400).

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98


D3DDEVCAPS2
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DDEVCAPS2

D3DDEVCAPS2 driver capability flags.

#define | Description
D3DDEVCAPS2_ADAPTIVETESSRTPATCH | Device supports adaptive tessellation of RT-patches
D3DDEVCAPS2_ADAPTIVETESSNPATCH | Device supports adaptive tessellation of N-patches.
D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES | Device supports IDirect3DDevice9::StretchRect using a texture as the source.
D3DDEVCAPS2_DMAPNPATCH | Device supports displacement maps for N-patches.
D3DDEVCAPS2_PRESAMPLEDDMAPNPATCH | Device supports presampled displacement maps for N-patches. For more information about displacement mapping, see Displacement Mapping.
D3DDEVCAPS2_STREAMOFFSET | Device supports stream offsets.
D3DDEVCAPS2_VERTEXELEMENTSCANSHARESTREAMOFFSET | Multiple vertex elements can share the same offset in a stream if D3DDEVCAPS2_VERTEXELEMENTSCANSHARESTREAMOFFSET is set by the device and the vertex declaration does not have an element with D3DDECLUSAGE_POSITIONT0.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98


D3DDTCAPS
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DDTCAPS

Constants describing the vertex data types supported by a device.

#define | Value | Description
D3DDTCAPS_UBYTE4 | 0x00000001L | 4-D unsigned byte.
D3DDTCAPS_UBYTE4N | 0x00000002L | Normalized, 4-D unsigned byte. Each of the four bytes is normalized by dividing to 255.0.
D3DDTCAPS_SHORT2N | 0x00000004L | Normalized, 2-D signed short, expanded to (first byte/32767.0, second byte/32767.0, 0, 1).
D3DDTCAPS_SHORT4N | 0x00000008L | Normalized, 4-D signed short, expanded to (first byte/32767.0, second byte/32767.0, third byte/32767.0, fourth byte/32767.0).
D3DDTCAPS_USHORT2N | 0x00000010L | Normalized, 2-D unsigned short, expanded to (first byte/65535.0, second byte/65535.0, 0, 1).
D3DDTCAPS_USHORT4N | 0x00000020L | Normalized 4-D unsigned short, expanded to (first byte/65535.0, second byte/65535.0, third byte/65535.0, fourth byte/65535.0).
D3DDTCAPS_UDEC3 | 0x00000040L | 3-D unsigned 10 10 10 format expanded to (value, value, value, 1).
D3DDTCAPS_DEC3N | 0x00000080L | 3-D signed 10 10 10 format normalized and expanded to (v[0]/511.0, v[1]/511.0, v[2]/511.0, 1).
D3DDTCAPS_FLOAT16_2 | 0x00000100L | 2-D 16-bit floating point numbers.
D3DDTCAPS_FLOAT16_4 | 0x00000200L | 4-D 16-bit floating point numbers.

These constants are used by the DeclTypes member of D3DCAPS9.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98


D3DENUM
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DENUM

Driver capability flag.

#define | Value | Description
D3DENUM_WHQL_LEVEL | 0x00000002L | Microsoft Windows Hardware Quality Labs (WHQL) driver testing. This is a time-consuming test requiring a one-second or two-second time penalty. This constant is used by the WHQLLevel member of D3DADAPTER_IDENTIFIER9.

Constant Information

Header | d3d9.h
Minimum operating system | Windows 98


D3DFVF
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DFVF

Flexible Vertex Format Constants, or flexible vertex format (FVF) codes, are used to describe the contents of vertices interleaved in a single data stream that will be processed by the fixed-function pipeline.

Vertex Data Flags

The following flags describe a vertex format. For information regarding vertex formats, see Fixed Function FVF Codes.

#define | Description | Data order and type
D3DFVF_DIFFUSE | Vertex format includes a diffuse color component. | DWORD in ARGB order. See D3DCOLOR_ARGB.
D3DFVF_NORMAL | Vertex format includes a vertex normal vector. This flag cannot be used with the D3DFVF_XYZRHW flag. | float, float, float
D3DFVF_PSIZE | Vertex format specified in point size. This size is expressed in camera space units for vertices that are not transformed and lit, and in device-space units for transformed and lit vertices. | float
D3DFVF_SPECULAR | Vertex format includes a specular color component. | DWORD in ARGB order. See D3DCOLOR_ARGB.
D3DFVF_XYZ | Vertex format includes the position of an untransformed vertex. This flag cannot be used with the D3DFVF_XYZRHW flag. | float, float, float
D3DFVF_XYZRHW | Vertex format includes the position of a transformed vertex. This flag cannot be used with the D3DFVF_XYZ or D3DFVF_NORMAL flags. | float, float, float
D3DFVF_XYZB1 through D3DFVF_XYZB5 | Vertex format contains position data, and a corresponding number of weighting (beta) values to use for multimatrix vertex blending operations. Currently, Microsoft Direct3D can blend with up to three weighting values and four blending matrices. For more information about using blending matrices, see Indexed Vertex Blending. | 1, 2, or 3 floats. When D3DFVF_LASTBETA_UBYTE4 is used, the last blending weight is treated as a DWORD.
D3DFVF_XYZW | Vertex format contains transformed and clipped (x, y, z, w) data. ProcessVertices does not invoke the clipper, instead outputting data in clip coordinates. This constant is designed for, and can only be used with, the programmable vertex pipeline. | float, float, float, float

Texture Flags

The following flags describe texture flags used by the fixed-function pipeline.

#define | Description
D3DFVF_TEX0 - D3DFVF_TEX8 | Number of texture coordinate sets for this vertex. The actual values for these flags are not sequential.
D3DFVF_TEXCOORDSIZEn(coordIndex) | Define a texture coordinate data set. n indicates the dimension of the texture coordinates. coordIndex indicates texture coordinate index number. See D3DFVF_TEXCOORDSIZEn and Texture_coordinates_and_Texture_Stages.

Mask Flags

The following flags describe mask flags used by the fixed-function pipeline.

#define | Description
D3DFVF_POSITION_MASK | Mask for position bits.
D3DFVF_RESERVED0, D3DFVF_RESERVED2 | Mask values for reserved bits in the FVF. Do not use.
D3DFVF_TEXCOUNT_MASK | Mask value for texture flag bits.

Miscellaneous Flags

The following flags describe a variety of flags used by the fixed-function pipeline.

#define | Description
D3DFVF_LASTBETA_D3DCOLOR | The last beta field in the vertex position data will be of type D3DCOLOR. The data in the beta fields are used with matrix palette skinning to specify matrix indices.
D3DFVF_LASTBETA_UBYTE4 The last beta field in the vertex position data will be of type UBYTE4. The data in the beta fields are used with matrix palette skinning to specify matrix indices.
// Given the following vertex data definition:
struct VERTEXPOSITION
{
   float pos[3];
   union
   {
      float beta[5];
      struct
      {
         float weights[4];
         DWORD MatrixIndices;  // Used as UBYTEs
      }
   }
};

Given the FVF is declared as: D3DFVF_XYZB5 | D3DFVF_LASTBETA_UBYTE4. Weight and MatrixIndices are included in beta[], where D3DFVF_LASTBETA_UBYTE4 says to interpret the last DWORD (beta[5]) as type UBYTE4.

D3DFVF_TEXCOUNT_SHIFT The number of bits by which to shift an integer value that identifies the number of texture coordinates for a vertex. This value might be used as shown below.
DWORD dwNumTextures = 1;  // Vertex has only one set of coordinates.

// Shift the value for use when creating a
//   flexible vertex format (FVF) combination.
dwFVF = dwNumTextures << D3DFVF_TEXCOUNT_SHIFT;

// Now, create an FVF combination using the shifted value.

Examples

The following examples show other common flag combinations.

// Untransformed vertex for lit, untextured, Gouraud-shaded content.
dwFVF = ( D3DFVF_XYZ | D3DFVF_DIFFUSE );

// Untransformed vertex for unlit, untextured, Gouraud-shaded
//   content with diffuse material color specified per vertex.
dwFVF = ( D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE );

// Untransformed vertex for light-map-based lighting.
dwFVF = ( D3DFVF_XYZ | D3DFVF_TEX2 );

// Transformed vertex for light-map-based lighting with shared rhw.
dwFVF = ( D3DFVF_XYZRHW | D3DFVF_TEX2 );

// Heavyweight vertex for unlit, colored content with two
//   sets of texture coordinates.
dwFVF = ( D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE |
          D3DFVF_SPECULAR | D3DFVF_TEX2 );

Constant Information

Header | d3d9types.h
Minimum operating system | Windows 98

Related Topics

  • Fixed Function FVF Codes
  • Geometry Blending


D3DLOCK
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DLOCK

A combination of zero or more locking options that describe the type of lock to perform.

#define | Description
D3DLOCK_DISCARD The application overwrites (with a write-only operation) every location within the locked surface. This is a valid option when using dynamic textures, dynamic vertex buffers, and dynamic index buffers. You may not use this option to update a portion of a surface.

For vertex and index buffers, the application discards the entire buffer. A pointer to a new memory area is returned so that the direct memory access (DMA) and rendering from the previous area do not stall.

For textures, the application overwrites (with a write-only operation) every location within the region being locked.

D3DLOCK_DONOTWAIT | Allows an application to gain back CPU cycles if the driver cannot lock the surface immediately. If this flag is set and the driver cannot lock the surface immediately, the lock call will return D3DERR_WASSTILLDRAWING. This flag can only be used when locking a surface created using IDirect3DDevice9::CreateOffscreenPlainSurface, IDirect3DDevice9::CreateRenderTarget, or IDirect3DDevice9::CreateDepthStencilSurface. This flag can also be used with a back buffer.
D3DLOCK_NO_DIRTY_UPDATE | By default, a lock on a resource adds a dirty region to that resource. This option prevents any changes to the dirty state of the resource. Applications should use this option when they have additional information about the set of regions changed during the lock operation.
D3DLOCK_NOOVERWRITE | The application promises not to overwrite any data in the vertex and index buffers. Specifying this flag allows the driver to return immediately and continue rendering, using this buffer. If this flag is not used, the driver must finish rendering before returning from locking.
D3DLOCK_NOSYSLOCK

The default behavior of a video memory lock is to reserve a system-wide critical section, guaranteeing that no display mode changes will occur for the duration of the lock. This option causes the system-wide critical section not to be held for the duration of the lock.

The lock operation is time consuming, but can enable the system to perform other duties, such as moving the mouse cursor. This option is useful for long-duration locks, such as the lock of the back buffer for software rendering that would otherwise adversely affect system responsiveness.

D3DLOCK_READONLY | The application will not write to the buffer. This enables resources stored in non-native formats to save the recompression step when unlocking.

Constant Information

Header | d3d9types.h
Minimum operating system | Windows 98

Related Topics

  • IDirect3DCubeTexture9::LockRect
  • IDirect3DIndexBuffer9::Lock
  • IDirect3DSurface9::LockRect
  • IDirect3DTexture9::LockRect
  • IDirect3DVertexBuffer9::Lock
  • IDirect3DVolume9::LockBox
  • IDirect3DVolumeTexture9::LockBox
  • ID3DXBaseMesh::LockIndexBuffer
  • ID3DXBaseMesh::LockVertexBuffer
  • ID3DXMesh::LockAttributeBuffer
  • ID3DXPatchMesh::LockAttributeBuffer
  • ID3DXPatchMesh::LockIndexBuffer
  • ID3DXPatchMesh::LockVertexBuffer


D3DPMISCCAPS
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DPMISCCAPS

Miscellaneous driver primitive capability flags.

#define | Value | Description
D3DPMISCCAPS_MASKZ | 0x00000002L | Device can enable and disable modification of the depth buffer on pixel operations.
D3DPMISCCAPS_CULLNONE | 0x00000010L | The driver does not perform triangle culling. This corresponds to the D3DCULL_NONE member of the D3DCULL enumerated type.
D3DPMISCCAPS_CULLCW | 0x00000020L | The driver supports clockwise triangle culling through the D3DRS_CULLMODE state. (This applies only to triangle primitives.) This flag corresponds to the D3DCULL_CW member of the D3DCULL enumerated type.
D3DPMISCCAPS_CULLCCW | 0x00000040L | The driver supports counterclockwise culling through the D3DRS_CULLMODE state. (This applies only to triangle primitives.) This flag corresponds to the D3DCULL_CCW member of the D3DCULL enumerated type.
D3DPMISCCAPS_COLORWRITEENABLE | 0x00000100L | Device supports per-channel writes for the render-target color buffer through the D3DRS_COLORWRITEENABLE state.
D3DPMISCCAPS_CLIPPLANESCALEDPOINTS | 0x00000200L | Device correctly clips scaled points of size greater than 1.0 to user-defined clipping planes.
D3DPMISCCAPS_CLIPTLVERTS | 0x00000200L | Device clips post-transformed vertex primitives. Specify D3DUSAGE_DONOTCLIP when the pipeline should not do any clipping. For this case, additional software clipping may need to be performed at draw time, requiring the vertex buffer to be in system memory.
D3DPMISCCAPS_TSSARGTEMP | 0x00000400L | Device supports D3DTA for temporary register.
D3DPMISCCAPS_BLENDOP | 0x00000800L | Device supports alpha-blending operations other than D3DBLENDOP_ADD.
D3DPMISCCAPS_NULLREFERENCE | 0x00000100L | A reference device that does not render.
D3DPMISCCAPS_INDEPENDENTWRITEMASKS | 0x00004000L | Device supports independent write masks for multiple element textures or multiple render targets.
D3DPMISCCAPS_PERSTAGECONSTANT | 0x00008000L | Device supports per-stage constants. See D3DTSS_CONSTANT in D3DTEXTURESTAGESTATETYPE.
D3DPMISCCAPS_FOGANDSPECULARALPHA | 0x00010000L | Device supports separate fog and specular alpha. Many devices use the specular alpha channel to store the fog factor.
D3DPMISCCAPS_SEPARATEALPHABLEND | 0x00020000L | Device supports separate blend settings for the alpha channel.
D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS | 0x00040000L | Device supports different bit depths for multiple render targets.
D3DPMISCCAPS_MRTPOSTPIXELSHADERBLENDING | 0x00080000L | Device supports post-pixel shader operations for multiple render targets.
D3DPMISCCAPS_FOGVERTEXCLAMPED | 0x00100000L | Device clamps fog blend factor per vertex.

These constants are used by the PrimitiveMiscCaps member of D3DCAPS9.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98


D3DPRESENT
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DPRESENT

Describes the relationship between the adapter refresh rate and the rate at which IDirect3DDevice9::Present or IDirect3DSwapChain9::Present operations are completed. These values also serve as flag values for the PresentationIntervals field of D3DCAPS9.

#define | Description
D3DPRESENT_DONOTWAIT | A presentation cannot be scheduled by a hardware abstraction layer (HAL) device. If this flag is set in a call to IDirect3DSwapChain9::Present, and the hardware is busy processing or waiting for a vertical sync interval, then Present will return D3DERR_WASSTILLDRAWING to indicate that the blit operation is incomplete.
D3DPRESENT_INTERVAL_DEFAULT | This is nearly equivalent to D3DPRESENT_INTERVAL_ONE. See Remarks.
D3DPRESENT_INTERVAL_ONE | The driver will wait for the vertical retrace period (the runtime will "beam follow" to prevent tearing). IDirect3DDevice9::Present operations will not be affected more frequently than the screen refresh; the runtime will complete at most one IDirect3DDevice9::Present operation per adapter refresh period. This is equivalent to using D3DSWAPEFFECT_COPYVSYNC in Microsoft DirectX 8.1. This option is always available for both windowed and full-screen swap chains. See Remarks.
D3DPRESENT_INTERVAL_TWO | The driver will wait for the vertical retrace period. IDirect3DDevice9::Present operations will not be affected more frequently than every second screen refresh. Check the PresentationIntervals cap in D3DCAPS9 to see if D3DPRESENT_INTERVAL_TWO is supported by the driver.
D3DPRESENT_INTERVAL_THREE | The driver will wait for the vertical retrace period. IDirect3DDevice9::Present operations will not be affected more frequently than every third screen refresh. Check the PresentationIntervals cap in D3DCAPS9 to see if D3DPRESENT_INTERVAL_THREE is supported by the driver.
D3DPRESENT_INTERVAL_FOUR | The driver will wait for the vertical retrace period. IDirect3DDevice9::Present operations will not be affected more frequently than every fourth screen refresh. Check the PresentationIntervals member in D3DCAPS9 to see if D3DPRESENT_INTERVAL_FOUR is supported by the driver.
D3DPRESENT_INTERVAL_IMMEDIATE | The runtime updates the window client area immediately and might do so more than once during the adapter refresh period. This is equivalent to using D3DSWAPEFFECT_COPY in DirectX 8.0. IDirect3DDevice9::Present operations might be affected immediately. This option is always available for both windowed and full-screen swap chains. See Remarks.
D3DPRESENT_LINEAR_CONTENT The content of the back buffer to be presented is in the linear color space.
  • The presentation will implicitly convert from linear space to sRGB (gamma = 2.2). This is the only conversion that is supported.
  • Because this flag represents a property of the content of the back buffer, the flag can be specified during an IDirect3DSwapChain9::Present call. In other words, an application can present linear content in one frame, and then switch to corrected content in the next.
  • This flag is ignored when the swap chain is full screen. (Note that this flag is available only on the explicit swap chain version of IDirect3DSwapChain9::Present. The IDirect3DSwapChain9::Present method does not take a flags parameter.)
  • This flag is always accepted, but will only take effect when the driver exposes D3DCAPS3_LINEAR_TO_SRGB_PRESENTATION.
  • The only back buffer format supported is X8R8G8B8.
See Windowed Swap Chains.

Remarks

Windowed mode supports D3DPRESENT_INTERVAL_DEFAULT, D3DPRESENT_INTERVAL_IMMEDIATE, and D3DPRESENT_INTERVAL_ONE. D3DPRESENT_INTERVAL_DEFAULT and the D3DPRESENT_INTERVAL_ONE are nearly equivalent (see the information regarding timer resolution below). They perform similarly to COPY_VSYNC in that there is only one present per frame, and they prevent tearing with beam-following. In contrast, D3DPRESENT_INTERVAL_IMMEDIATE will attempt to provide an unlimited presentation rate.

Full-screen mode supports similar usage as windowed mode by supporting D3DPRESENT_INTERVAL_IMMEDIATE regardless of the refresh rate or swap effect. D3DPRESENT_INTERVAL_DEFAULT uses the default system timer resolution whereas the D3DPRESENT_INTERVAL_ONE calls timeBeginPeriod World Wide Web link to enhance system timer resolution. This improves the quality of vertical sync, but consumes slightly more processing time. Both parameters attempt to synchronize vertically.

Constant Information

Header | d3d9.h
Minimum operating system | Windows 98


D3DPRESENTFLAG
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DPRESENTFLAG

Constants used by D3DPRESENT_PARAMETERS.

#define | Value | Description
D3DPRESENTFLAG_LOCKABLE_BACKBUFFER 0x00000001 Set this flag if the application requires the ability to lock the back buffer directly. Note that back buffers are not lockable unless the application specifies D3DPRESENTFLAG_LOCKABLE_BACKBUFFER when calling IDirect3D9::CreateDevice or IDirect3DDevice9::Reset. Lockable back buffers incur a performance cost on some graphics hardware configurations.

Performing a lock operation (or using IDirect3DDevice9::UpdateSurface to write) on the lockable back buffer decreases performance on many cards. In this case, consider using textured triangles to move data to the back buffer.

D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL 0x00000002 Set this flag when the device or swap chain is created to enable z-buffer discarding. If this flag is set, the contents of the depth stencil buffer will be invalid after calling either IDirect3DDevice9::Present, or IDirect3DDevice9::SetDepthStencilSurface with a different depth surface.

Discarding z-buffer data can increase performance and is driver dependent. The debug runtime will enforce discarding by clearing the z-buffer to some constant value after calling either IDirect3DDevice9::Present, or IDirect3DDevice9::SetDepthStencilSurface with a different depth surface.

Discarding z-buffer data is illegal for all lockable formats, D3DFMT_D16_LOCKABLE and D3DFMT_D32F_LOCKABLE. Any use of IDirect3D9::CreateDevice specifying a lockable format and z-buffer discarding will fail. For more information about formats, see D3DFORMAT.

D3DPRESENTFLAG_DEVICECLIP | 0x00000004 | Clip a windowed IDirect3DDevice9::Present blit into the window client area, within the monitor screen area of the video adapter that created the Microsoft Direct3D device. This constant works on Microsoft Windows 2000 and Windows XP only.
D3DPRESENTFLAG_VIDEO | 0x00000010 | This is a hint to the driver that the back buffers will contain video data.

These constants are used by D3DPRESENT_PARAMETERS.

Constant Information

Header | d3d9types.h
Minimum operating system | Windows 98


D3DPS20CAPS
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DPS20CAPS

Pixel shader capability flags.

#define | Value | Description
D3DPS20CAPS_ARBITRARYSWIZZLE | (1 << 0) | Arbitrary swizzling is supported.
D3DPS20CAPS_GRADIENTINSTRUCTIONS | (1 << 1) | Gradient instructions are supported.
D3DPS20CAPS_PREDICATION | (1 << 2) | Instruction predication is supported. See setp_comp - ps.
D3DPS20CAPS_NODEPENDENTREADLIMIT | (1 << 3) | There is no limit on the number of dependent reads per instruction.
D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT | (1 << 4) | There is no limit on the number of tex instructions.
D3DPS20_MAX_DYNAMICFLOWCONTROLDEPTH | 24 | The maximum level of nesting of dynamic flow control instructions (break, breakc, ifc).
D3DPS20_MIN_DYNAMICFLOWCONTROLDEPTH | 0 | The minimum level of nesting of dynamic flow control instructions (break, breakc, ifc).
D3DPS20_MAX_NUMTEMPS | 32 | The driver will support at most this many temporary register.
D3DPS20_MIN_NUMTEMPS | 12 | The driver will support at least this many temporary register.
D3DPS20_MAX_STATICFLOWCONTROLDEPTH | 4 | The maximum depth of nesting of the loop/rep and call/callnz bool instructions.
D3DPS20_MIN_STATICFLOWCONTROLDEPTH | 0 | The minimum depth of nesting of the loop/rep and call/callnz bool instructions.
D3DPS20_MAX_NUMINSTRUCTIONSLOTS | 512 | The driver will support at most this many instructions.
D3DPS20_MIN_NUMINSTRUCTIONSLOTS | 96 | The driver will support at least this many instructions.

These constants are used by the PS20Caps member of D3DCAPS9.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98

Related Topics

  • D3DPSHADERCAPS2_0


D3DPTFILTERCAPS
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DPTFILTERCAPS

Texture filtering constants.

#define | Description
D3DPTFILTERCAPS_MAGFPOINT | Device supports per-stage point-sample filtering for magnifying textures. The point-sample magnification filter is represented by the D3DTEXF_POINT member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MAGFLINEAR | Device supports per-stage bilinear interpolation filtering for magnifying mipmaps. The bilinear interpolation mipmapping filter is represented by the D3DTEXF_LINEAR member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MAGFANISOTROPIC | Device supports per-stage anisotropic filtering for magnifying textures. The anisotropic magnification filter is represented by the D3DTEXF_ANISOTROPIC member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MAGFPYRAMIDALQUAD | Device supports per-stage pyramidal sample filtering for magnifying textures. The pyramidal magnifying filter is represented by the D3DTEXF_PYRAMIDALQUAD member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MAGFGAUSSIANQUAD | Device supports per-stage Gaussian quad filtering for magnifying textures.
D3DPTFILTERCAPS_MINFPOINT | Device supports per-stage point-sample filtering for minifying textures. The point-sample minification filter is represented by the D3DTEXF_POINT member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MINFLINEAR | Device supports per-stage linear filtering for minifying textures. The linear minification filter is represented by the D3DTEXF_LINEAR member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MINFANISOTROPIC | Device supports per-stage anisotropic filtering for minifying textures. The anisotropic minification filter is represented by the D3DTEXF_ANISOTROPIC member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MINFPYRAMIDALQUAD | Device supports per-stage pyramidal sample filtering for minifying textures.
D3DPTFILTERCAPS_MINFGAUSSIANQUAD | Device supports per-stage Gaussian quad filtering for minifying textures.
D3DPTFILTERCAPS_MIPFPOINT | Device supports per-stage point-sample filtering for mipmaps. The point-sample mipmapping filter is represented by the D3DTEXF_POINT member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MIPFLINEAR | Device supports per-stage bilinear interpolation filtering for mipmaps. The bilinear interpolation mipmapping filter is represented by the D3DTEXF_LINEAR member of the D3DTEXTUREFILTERTYPE enumerated type.

These constants are used by TextureFilterCaps, CubeTextureFilterCaps, VolumeTextureFilterCaps, and VertexTextureFilterCaps members of D3DCAPS9.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98


D3DSTENCILCAPS
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DSTENCILCAPS

Driver stencil capability flags.

#define | Value | Description
D3DSTENCILCAPS_KEEP | 0x00000001L | Do not update the entry in the stencil buffer. This is the default value.
D3DSTENCILCAPS_ZERO | 0x00000002L | Set the stencil-buffer entry to 0.
D3DSTENCILCAPS_REPLACE | 0x00000004L | Replace the stencil-buffer entry with reference value.
D3DSTENCILCAPS_INCRSAT | 0x00000008L | Increment the stencil-buffer entry, clamping to the maximum value.
D3DSTENCILCAPS_DECRSAT | 0x00000010L | Decrement the stencil-buffer entry, clamping to zero.
D3DSTENCILCAPS_INVERT | 0x00000020L | Invert the bits in the stencil-buffer entry.
D3DSTENCILCAPS_INCR | 0x00000040L | Increment the stencil-buffer entry, wrapping to zero if the new value exceeds the maximum value.
D3DSTENCILCAPS_DECR | 0x00000080L | Decrement the stencil-buffer entry, wrapping to the maximum value if the new value is less than zero.
D3DSTENCILCAPS_TWOSIDED | 0x00000100L | The device supports two-sided stencil.

Stencil-buffer entries are integer values ranging from 0 through 2n - 1, where n is the bit depth of the stencil buffer.

These constants are used by the StencilCaps member of D3DCAPS9.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98


D3DTA
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DTA

Texture argument constants are used as values for the following members of the D3DTEXTURESTAGESTATETYPE enumerated type:

  • D3DTSS_ALPHAARG0
  • D3DTSS_ALPHAARG1
  • D3DTSS_ALPHAARG2
  • D3DTSS_COLORARG0
  • D3DTSS_COLORARG1
  • D3DTSS_COLORARG2
  • D3DTSS_RESULTARG

Set and retrieve texture arguments by calling the IDirect3DDevice9::SetTextureStageState and IDirect3DDevice9::GetTextureStageState methods.

Argument flags

You can combine an argument flag with a modifier, but two argument flags cannot be combined.

#define | Description
D3DTA_CONSTANT | Select a constant from a texture stage. The default value is 0xffffffff.
D3DTA_CURRENT | The texture argument is the result of the previous blending stage. In the first texture stage (stage 0), this argument is equivalent to D3DTA_DIFFUSE. If the previous blending stage uses a bump-map texture (the D3DTOP_BUMPENVMAP operation), the system chooses the texture from the stage before the bump-map texture. If s represents the current texture stage and s - 1 contains a bump-map texture, this argument becomes the result output by texture stage s - 2. Permissions are read/write.
D3DTA_DIFFUSE | The texture argument is the diffuse color interpolated from vertex components during Gouraud shading. If the vertex does not contain a diffuse color, the default color is 0xffffffff. Permissions are read-only.
D3DTA_SELECTMASK | Mask value for all arguments; not used when setting texture arguments.
D3DTA_SPECULAR | The texture argument is the specular color interpolated from vertex components during Gouraud shading. If the vertex does not contain a specular color, the default color is 0xffffffff. Permissions are read-only.
D3DTA_TEMP | The texture argument is a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default value for the register is (0.0, 0.0, 0.0, 0.0). Permissions are read/write.
D3DTA_TEXTURE | The texture argument is the texture color for this texture stage. Permissions are read-only.
D3DTA_TFACTOR | The texture argument is the texture factor set in a previous call to the IDirect3DDevice9::SetRenderState with the D3DRS_TEXTUREFACTOR render-state value. Permissions are read-only.

Modifier flags

An argument flag may be combined with one of the following modifier flags.

#define | Description
D3DTA_ALPHAREPLICATE | Replicate the alpha information to all color channels before the operation completes. This is a read modifier.
D3DTA_COMPLEMENT | Take the complement of the argument x, (1.0 - x). This is a read modifier.

Constant Information

Header | d3d9types.h
Minimum operating system | Windows 98


D3DTSS_TCI
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DTSS_TCI

Driver texture coordinate capability flags.

#define | Value | Description
D3DTSS_TCI_PASSTHRU | 0x00000000L | Use the specified texture coordinates contained within the vertex format. This value resolves to zero.
D3DTSS_TCI_CAMERASPACENORMAL | 0x00010000L | Use the vertex normal, transformed to camera space, as the input texture coordinates for this stage's texture transformation.
D3DTSS_TCI_CAMERASPACEPOSITION | 0x00020000L | Use the vertex position, transformed to camera space, as the input texture coordinates for this stage's texture transformation.
D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR | 0x00030000L | Use the reflection vector, transformed to camera space, as the input texture coordinate for this stage's texture transformation. The reflection vector is computed from the input vertex position and normal vector.
D3DTSS_TCI_SPHEREMAP | 0x00040000L | Use the specified texture coordinates for sphere mapping.

These constants are used by D3DTSS_TEXCOORDINDEX.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98


D3DUSAGE
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DUSAGE

Usage options that identify how resources are to be used.

Usages

The following table summarizes the available usage options.

#define | Description
D3DUSAGE_AUTOGENMIPMAP The resource will automatically generate mipmaps. See Automatic Generation of Mipmaps. Automatic generation of mipmaps is not supported for volume textures and depth stencil surfaces/textures.

This usage is not valid for a resource in system memory (D3DPOOL_SYSTEMMEM).
D3DUSAGE_DEPTHSTENCIL | The resource will be a depth stencil buffer. D3DUSAGE_DEPTHSTENCIL can only be used with D3DPOOL_DEFAULT.
D3DUSAGE_DMAP | The resource will be a displacement map.
D3DUSAGE_DONOTCLIP | Set to indicate that the vertex buffer content will never require clipping. When rendering with buffers that have this flag set, the D3DRS_CLIPPING render state must be set to false.
D3DUSAGE_DYNAMIC Set to indicate that the vertex buffer requires dynamic memory use. This is useful for drivers because it enables them to decide where to place the buffer. In general, static vertex buffers are placed in video memory and dynamic vertex buffers are placed in accelerated graphics port (AGP) memory. Note that there is no separate static use. If you do not specify D3DUSAGE_DYNAMIC, the vertex buffer is made static. D3DUSAGE_DYNAMIC is strictly enforced through the D3DLOCK_DISCARD and D3DLOCK_NOOVERWRITE locking flags. As a result, D3DLOCK_DISCARD and D3DLOCK_NOOVERWRITE are valid only on vertex buffers created with D3DUSAGE_DYNAMIC. They are not valid flags on static vertex buffers. For more information, see Managing Resources.

For more information about using dynamic vertex buffers, see Performance Optimizations.

D3DUSAGE_DYNAMIC and D3DPOOL_MANAGED are incompatible and should not be used together. See D3DPOOL.

Textures can specify D3DUSAGE_DYNAMIC. However, managed textures cannot use D3DUSAGE_DYNAMIC. For more information about dynamic textures, see Using Dynamic Textures.
D3DUSAGE_NPATCHES | Set to indicate that the vertex buffer is to be used for drawing N-patches.
D3DUSAGE_POINTS | Set to indicate that the vertex or index buffer will be used for drawing point sprites. The buffer will be loaded in system memory if software vertex processing is needed to emulate point sprites.
D3DUSAGE_RENDERTARGET | The resource will be a render target. D3DUSAGE_RENDERTARGET can only be used with D3DPOOL_DEFAULT.
D3DUSAGE_RTPATCHES | Set to indicate that the vertex buffer is to be used for drawing high-order primitives.
D3DUSAGE_SOFTWAREPROCESSING If this flag is used, vertex processing is done in software. If this flag is not used, vertex processing is done in hardware.

The D3DUSAGE_SOFTWAREPROCESSING flag can be set when mixed-mode or software vertex processing (D3DCREATE_MIXED_VERTEXPROCESSING / D3DCREATE_SOFTWARE_VERTEXPROCESSING) is enabled for that device. D3DUSAGE_SOFTWAREPROCESSING must be set for buffers to be used with software vertex processing in mixed mode, but it should not be set for the best possible performance when using hardware index processing in mixed mode (D3DCREATE_HARDWARE_VERTEXPROCESSING). However, setting D3DUSAGE_SOFTWAREPROCESSING is the only option when a single buffer is used with both hardware and software vertex processing. D3DUSAGE_SOFTWAREPROCESSING is allowed for mixed and software devices.

D3DUSAGE_SOFTWAREPROCESSING is used with IDirect3D9::CheckDeviceFormat to find out if a particular texture format can be used as a vertex texture during software vertex processing. If it can, the texture must be created in D3DPOOL_SCRATCH.
D3DUSAGE_WRITEONLY | Informs the system that the application writes only to the vertex buffer. Using this flag enables the driver to choose the best memory location for efficient write operations and rendering. Attempts to read from a vertex buffer that is created with this capability will fail. Buffers created with D3DPOOL_DEFAULT that do not specify D3DUSAGE_WRITEONLY might suffer a severe performance penalty.

Usage and Resource Combinations

Usages are either specified when a resource is created, or specified with IDirect3D9::CheckDeviceType to test the capability of an existing resource. The following table identifies which usages can be applied to which resource types.

Usage | Vertex buffer create | Index buffer create | Texture create | Cube texture create | Volume texture create | Surface create | Check device format
D3DUSAGE_AUTOGENMIPMAP |  |  | x | x |  |  | x
D3DUSAGE_DEPTHSTENCIL |  |  | x | x |  | x | x
D3DUSAGE_DMAP |  |  | x |  |  |  | x
D3DUSAGE_DONOTCLIP | x | x |  |  |  |  |
D3DUSAGE_DYNAMIC | x | x | x | x | x |  | x
D3DUSAGE_NPATCHES | x | x |  |  |  |  |
D3DUSAGE_POINTS | x | x |  |  |  |  |
D3DUSAGE_RTPATCHES | x | x |  |  |  |  |
D3DUSAGE_RENDERTARGET |  |  | x | x |  | x | x
D3DUSAGE_SOFTWAREPROCESSING | x | x | x | x | x |  | x
D3DUSAGE_WRITEONLY | x | x |  |  |  |  |

Use IDirect3D9::CheckDeviceFormat to check hardware support for these usages.

Each of the resource creation methods is listed here.

  • IDirect3DDevice9::CreateCubeTexture
  • IDirect3DDevice9::CreateDepthStencilSurface
  • IDirect3DDevice9::CreateIndexBuffer
  • IDirect3DDevice9::CreateOffscreenPlainSurface
  • IDirect3DDevice9::CreateRenderTarget
  • IDirect3DDevice9::CreateTexture
  • IDirect3DDevice9::CreateVertexBuffer
  • IDirect3DDevice9::CreateVolumeTexture

The D3DXCreatexxx texturing functions also use some of these constant values for resource creation.

For more information about pool types and their restrictions with certain usages, see D3DPOOL.

Constant Information

Header | d3d9types.h
Minimum operating system | Windows 98

Related Topics

  • D3DUSAGE_QUERY
  • D3DDECLUSAGE
  • D3DPOOL


D3DUSAGE_QUERY
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DUSAGE_QUERY

These options identify query resource types.

#define | Description
D3DUSAGE_QUERY_FILTER | Query the resource format to see if it supports texture filter types other than D3DTEXF_POINT (which is always supported).
D3DUSAGE_QUERY_LEGACYBUMPMAP | Query the resource about a legacy bump map.
D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING | Query the resource to verify support for post pixel shader blending support. If IDirect3D9::CheckDeviceFormat fails with D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, post pixel blending operations are not supported. These include alpha test, pixel fog, render-target blending, color write enable, and dithering.
D3DUSAGE_QUERY_SRGBREAD | Query the resource to verify if a texture supports gamma correction during a read operation.
D3DUSAGE_QUERY_SRGBWRITE | Query the resource to verify if a texture supports gamma correction during a write operation.
D3DUSAGE_QUERY_VERTEXTEXTURE | Query the resource to verify support for vertex shader texture sampling.
D3DUSAGE_QUERY_WRAPANDMIP | Query the resource to verify support for texture wrapping and mip-mapping.

Use IDirect3D9::CheckDeviceFormat to query hardware support for these usages, and some other usages listed in D3DUSAGE.

Constant Information

Header | d3d9types.h
Minimum operating system | Windows 98

Related Topics

    © 2004 Microsoft Corporation. All rights reserved.
    Feedback? Please provide us with your comments on this topic.
    For more help, visit the DirectX Developer Center.


D3DVS20CAPS
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DVS20CAPS

Vertex shader capability constants.

#define | Value | Description
D3DVS20CAPS_PREDICATION | (1 << 0) | Instruction predication is supported. See setp_comp.
D3DVS20_MAX_DYNAMICFLOWCONTROLDEPTH | 24 | The maximum level of nesting of dynamic flow control instructions (break, breakc, ifc).
D3DVS20_MIN_DYNAMICFLOWCONTROLDEPTH | 0 | The minimum level of nesting of dynamic flow control instructions (break, breakc, ifc).
D3DVS20_MAX_NUMTEMPS | 32 | The maximum number of temporary registers supported.
D3DVS20_MIN_NUMTEMPS | 12 | The minimum number of temporary registers supported.
D3DVS20_MAX_STATICFLOWCONTROLDEPTH | 4 | The maximum depth of nesting of the loop/rep and call/callnz bool instructions.
D3DVS20_MIN_STATICFLOWCONTROLDEPTH | 1 | The minimum depth of nesting of the loop/rep and call/callnz bool instructions.

These constants are used by the VS20Caps member of D3DCAPS9.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98

Related Topics

  • D3DVSHADERCAPS2_0


D3DVERTEXTEXTURESAMPLER
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DVERTEXTEXTURESAMPLER

Vertex texture sampler constants.

These constants identify the texture samplers used by vertex shaders.

#define | Description
D3DVERTEXTEXTURESAMPLER0 | (D3DDMAPSAMPLER+1)
D3DVERTEXTEXTURESAMPLER1 | (D3DDMAPSAMPLER+2)
D3DVERTEXTEXTURESAMPLER2 | (D3DDMAPSAMPLER+3)
D3DVERTEXTEXTURESAMPLER3 | (D3DDMAPSAMPLER+4)

D3DDMAPSAMPLER

This is an internal constant used by the texture sampler in the tessellator.

#define | Description
D3DDMAPSAMPLER | 256, which is the maximum number of texture samplers.

Constant Information

Header | d3d9types.h
Minimum operating system | Windows 98


D3DVTXPCAPS
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DVTXPCAPS

A combination of one or more flags that control the device create behavior.

#define | Description
D3DVTXPCAPS_DIRECTIONALLIGHTS | Device can do directional lights.
D3DVTXPCAPS_LOCALVIEWER | Device can do local viewer.
D3DVTXPCAPS_MATERIALSOURCE7 | When this cap is set, the device supports the color material states: D3DRS_AMBIENTMATERIALSOURCE, D3DRS_DIFFUSEMATERIALSOURCE, D3DRS_EMISSIVEMATERIALSOURCE, and D3DRS_SPECULARMATERIALSOURCE.
D3DVTXPCAPS_NO_TEXGEN_NONLOCALVIEWER | Device does not support texture generation in non-local viewer mode.
D3DVTXPCAPS_POSITIONALLIGHTS | Device can do positional lights (includes point and spot).
D3DVTXPCAPS_TEXGEN | Device can do texgen.
D3DVTXPCAPS_TEXGEN_SPHEREMAP | Device supports D3DTSS_TCI_SPHEREMAP.
D3DVTXPCAPS_TWEENING | Device can do vertex tweening.

Constant Information

Header | d3d9caps.h
Minimum operating system | Windows 98


Other Direct3D Constants
Microsoft DirectX 9.0 SDK Update (October 2004)

Other Direct3D Constants

Process Vertices Constant

The following constant is used in the IDirect3DDevice9::ProcessVertices method.

#define | Value
D3DPV_DONOTCOPYDATA | (1 << 0)

These #defines are declared in D3d9types.h.

SetStreamSourceFreq Constants

Either of these constants is designed to be logically combined with the StreamNumber parameter in IDirect3DDevice9::SetStreamSourceFreq to draw one or more instances of the same geometry. For more information, see Drawing Multiple Instances of Geometry Efficiently.

#define | Value
D3DSTREAMSOURCE_INDEXEDDATA | (1 << 30)
D3DSTREAMSOURCE_INSTANCEDATA | (2 << 30)

These #defines are declared in D3d9types.h.

Internal Use Constants

The following table lists Microsoft Direct3D constants that are used internally.

#define | Value
D3D_MAX_SIMULTANEOUS_RENDERTARGETS | 4
D3DDMAPSAMPLER | 256
D3DDP_MAXTEXCOORD | 8
D3DPRESENT_BACK_BUFFERS_MAX | 3L
D3DPRESENT_RATE_DEFAULT | 0x00000000
D3DRTYPECOUNT | (D3DRTYPE_INDEXBUFFER+1)
MAXD3DDECLLENGTH | 64 (does not include "end" marker vertex element)
MAXD3DDECLMETHOD | D3DDECLMETHOD_LOOKUPPRESAMPLED
MAXD3DDECLTYPE | D3DDECLTYPE_UNUSED
MAXD3DDECLUSAGE | D3DDECLUSAGE_SAMPLE
MAXD3DDECLUSAGEINDEX | 15

These #defines are declared in D3d9types.h.

#define | Value
D3D_SDK_VERSION | (32 | 0x80000000)
D3D9b_SDK_VERSION | (31 | 0x80000000)

These #defines are declared in D3d9.h.

Constant Information

Minimum operating system Windows 98


D3DX Reference
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DX Reference

This section contains reference information for the application programming interface (API) elements provided by the D3DX utility library. Reference material is divided into the following categories.

  • Interfaces
  • Functions
  • Callback Functions
  • Macros
  • Structures
  • Enumerated Types
  • Constants


Interfaces
Microsoft DirectX 9.0 SDK Update (October 2004)

Interfaces

This section contains reference information for the Component Object Model (COM) interfaces provided by the D3DX utility library. The following interfaces are used with the D3DX utility library.

Interfaces

  • ID3DXAllocateHierarchy
  • ID3DXAnimationCallbackHandler
  • ID3DXAnimationController
  • ID3DXAnimationSet
  • ID3DXBaseEffect
  • ID3DXBaseMesh
  • ID3DXBuffer
  • ID3DXCompressedAnimationSet
  • ID3DXConstantTable
  • ID3DXEffect
  • ID3DXEffectCompiler
  • ID3DXEffectPool
  • ID3DXEffectStateManager
  • ID3DXFont
  • ID3DXFragmentLinker
  • ID3DXInclude
  • ID3DXKeyframedAnimationSet
  • ID3DXLine
  • ID3DXLoadUserData
  • ID3DXMatrixStack
  • ID3DXMesh
  • ID3DXPatchMesh
  • ID3DXPMesh
  • ID3DXPRTBuffer
  • ID3DXPRTCompBuffer
  • ID3DXPRTEngine
  • ID3DXRenderToEnvMap
  • ID3DXRenderToSurface
  • ID3DXSaveUserData
  • ID3DXSkinInfo
  • ID3DXSPMesh
  • ID3DXSprite
  • ID3DXTextureGutterHelper
  • ID3DXTextureShader


ID3DXAllocateHierarchy Interface

This interface is implemented by the application to allocate or free frame and mesh container objects. Methods on this are called during loading and destroying frame hierarchies.

ID3DXAllocateHierarchy Members

CreateFrame | Requests allocation of a frame object.
CreateMeshContainer | Requests allocation of a mesh container object.
DestroyFrame | Requests deallocation of a frame object.
DestroyMeshContainer | Requests deallocation of a mesh container object.

Remarks

The LPD3DXALLOCATEHIERARCHY type is defined as a pointer to this interface.

typedef interface ID3DXAllocateHierarchy ID3DXAllocateHierarchy;
typedef interface ID3DXAllocateHierarchy *LPD3DXALLOCATEHIERARCHY;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXAllocateHierarchy::CreateFrame Method

Requests allocation of a frame object.

Syntax

HRESULT CreateFrame(

    LPCSTR Name,
    LPD3DXFRAME *ppNewFrame
);

Parameters

Name
[in] Name of the frame to be created.
ppNewFrame
[out, retval] Returns the created frame object.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.


ID3DXAllocateHierarchy::CreateMeshContainer Method

Requests allocation of a mesh container object.

Syntax

HRESULT CreateMeshContainer(

    LPCSTR Name,
    const D3DXMESHDATA *pMeshData,
    const D3DXMATERIAL *pMaterials,
    const D3DXEFFECTINSTANCE *pEffectInstances,
    DWORD NumMaterials,
    const DWORD *pAdjacency,
    LPD3DXSKININFO pSkinInfo,
    LPD3DXMESHCONTAINER *ppNewMeshContainer
);

Parameters

Name
[in] Name of the mesh.
pMeshData
[in] Pointer to the mesh data structure. See D3DXMESHDATA.
pMaterials
[in] Array of materials used in the mesh.
pEffectInstances
[in] Array of effect instances used in the mesh. See D3DXEFFECTINSTANCE.
NumMaterials
[in] Number of materials in the materials array.
pAdjacency
[in] Adjacency array for the mesh.
pSkinInfo
[in] Pointer to the skin mesh object if skin data is found. See ID3DXSkinInfo.
ppNewMeshContainer
[out, retval] Returns the created mesh container. See D3DXMESHCONTAINER.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.


ID3DXAllocateHierarchy::DestroyFrame Method

Requests deallocation of a frame object.

Syntax

HRESULT DestroyFrame(

    LPD3DXFRAME pFrameToFree
);

Parameters

pFrameToFree
[in] Pointer to the frame to be deallocated.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.


ID3DXAllocateHierarchy::DestroyMeshContainer Method

Requests deallocation of a mesh container object.

Syntax

HRESULT DestroyMeshContainer(

    LPD3DXMESHCONTAINER pMeshContainerToFree
);

Parameters

pMeshContainerToFree
[in] Pointer to the mesh container object to be deallocated.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.


ID3DXAnimationCallbackHandler Interface

An application implements this interface to handle callbacks in animation sets generated by calls to ID3DXAnimationController::AdvanceTime.

ID3DXAnimationCallbackHandler Members

HandleCallback The application implements this method. This method is called when a callback occurs for an animation set in one of the tracks during a call to ID3DXAnimationController::AdvanceTime.

Remarks

The LPD3DXANIMATIONCALLBACKHANDLER type is defined as a pointer to this interface.

typedef interface ID3DXAnimationCallbackHandler ID3DXAnimationCallbackHandler;
typedef interface ID3DXAnimationCallbackHandler *LPD3DXANIMATIONCALLBACKHANDLER;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXAnimationCallbackHandler::HandleCallback Method

The application implements this method. This method is called when a callback occurs for an animation set in one of the tracks during a call to ID3DXAnimationController::AdvanceTime.

Syntax

HRESULT HandleCallback(

    UINT Track,
    LPVOID pCallbackData
);

Parameters

Track
[in] Identifier of the track on which the callback occurs.
pCallbackData
[in] Pointer to user-owned callback data.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR.


ID3DXAnimationController Interface

This interface is used to control animation functionality, connecting animation sets with the transformation frames that are being animated. The interface has methods to mix multiple animations and to modify blending parameters over time to enable smooth transitions and other effects.

ID3DXAnimationController Members

AdvanceTime | Animates the mesh and advances the global animation time by a specified amount.
CloneAnimationController | Clones, or copies, an animation controller.
GetAnimationSet | Gets an animation set.
GetAnimationSetByName | Gets an animation set, given its name.
GetCurrentPriorityBlend | Returns an event handle to a priority blend event that is currently running.
GetCurrentTrackEvent | Returns an event handle to the event currently running on the specified animation track.
GetEventDesc | Gets a description of a specified animation event.
GetMaxNumAnimationOutputs | Get the maximum number of animation outputs the animation controller can support.
GetMaxNumAnimationSets | Gets the maximum number of animation sets the animation controller can support.
GetMaxNumEvents | Gets the maximum number of events the animation controller can support.
GetMaxNumTracks | Gets the maximum number of tracks in the animation controller.
GetNumAnimationSets | Returns the number of animation sets currently registered in the animation controller.
GetPriorityBlend | Gets the current priority blending weight used by the animation controller.
GetTime | Gets the global animation time.
GetTrackAnimationSet | Gets the animation set for the given track.
GetTrackDesc | Gets the track description.
GetUpcomingPriorityBlend | Returns an event handle to the next priority blend event scheduled to occur after a specified event.
GetUpcomingTrackEvent | Returns an event handle to the next event scheduled to occur after a specified event on an animation track.
KeyPriorityBlend | Sets blending event keys for the specified animation track.
KeyTrackEnable | Sets an event key that enables or disables an animation track.
KeyTrackPosition | Sets an event key that changes the local time of an animation track.
KeyTrackSpeed | Sets an event key that changes the rate of play of an animation track.
KeyTrackWeight | Sets an event key that changes the weight of an animation track. The weight is used as a multiplier when combining multiple tracks together.
RegisterAnimationOutput | Adds an animation output to the animation controller and registers pointers for scale, rotate, and translate (SRT) transformations.
RegisterAnimationSet | Adds an animation set to the animation controller.
ResetTime | Resets the global animation time to zero. Any pending events will retain their original schedules, but in the new timeframe.
SetPriorityBlend | Sets the priority blending weight used by the animation controller.
SetTrackAnimationSet | Applies the animation set to the specified track.
SetTrackDesc | Sets the track description.
SetTrackEnable | Enables or disables a track in the animation controller.
SetTrackPosition | Sets the track to the specified local animation time.
SetTrackPriority | Sets the priority blending weight for the specified animation track.
SetTrackSpeed | Sets the track speed. The track speed is similar to a multiplier that is used to speed up or slow down the playback of the track.
SetTrackWeight | Sets the track weight. The weight is used to determine how to blend multiple tracks together.
UnkeyAllPriorityBlends | Removes all scheduled priority blend events from the animation controller.
UnkeyAllTrackEvents | Removes all events from a specified animation track.
UnkeyEvent | Removes a specified event from an animation track, preventing the execution of the event.
UnregisterAnimationSet | Removes an animation set from the animation controller.
ValidateEvent | Checks whether a specified event handle is valid and the animation event has not yet completed.

Remarks

Create an animation controller object with D3DXCreateAnimationController.

The LPD3DXANIMATIONCONTROLLER type is defined as a pointer to the ID3DXAnimationController interface.

typedef interface ID3DXAnimationController ID3DXAnimationController;
typedef interface ID3DXAnimationController *LPD3DXANIMATIONCONTROLLER;

The D3DXEVENTHANDLE type is defined as an event handle to animation controller events.

typedef DWORD D3DXEVENTHANDLE;

The LPD3DXEVENTHANDLE type is defined as a pointer to an event handle to animation controller events.

typedef D3DXEVENTHANDLE *LPD3DXEVENTHANDLE;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXAnimationController::AdvanceTime Method

Animates the mesh and advances the global animation time by a specified amount.

Syntax

HRESULT AdvanceTime(

    DOUBLE TimeDelta,
    LPD3DXANIMATIONCALLBACKHANDLER pCallbackHandler
);

Parameters

TimeDelta
[in] Amount, in seconds, by which to advance the global animation time. TimeDelta value must be non-negative or zero.
pCallbackHandler
[in] Pointer to a user-defined animation callback handler interface, ID3DXAnimationCallbackHandler.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXAnimationController::CloneAnimationController Method

Clones, or copies, an animation controller.

Syntax

HRESULT CloneAnimationController(

    UINT MaxNumAnimationOutputs,
    UINT MaxNumAnimationSets,
    UINT MaxNumTracks,
    UINT MaxNumEvents,
    LPD3DXANIMATIONCONTROLLER *ppAnimController
);

Parameters

MaxNumAnimationOutputs
[in] Maximum number of animation outputs the controller can support.
MaxNumAnimationSets
[in] Maximum number of animation sets the controller can support.
MaxNumTracks
[in] Maximum number of tracks the controller can support.
MaxNumEvents
[in] Maximum number of events the controller can support.
ppAnimController
[in] Address of a pointer to the cloned ID3DXAnimationController animation controller.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXAnimationController::GetAnimationSet Method

Gets an animation set.

Syntax

HRESULT GetAnimationSet(

    UINT Index,
    LPD3DXANIMATIONSET *ppAnimSet
);

Parameters

Index
[in] Index of the animation set.
ppAnimSet
[out] Pointer to the ID3DXAnimationSet animation set.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The animation controller contains an array of animation sets. This method returns one of them at the given index.


ID3DXAnimationController::GetAnimationSetByName Method

Gets an animation set, given its name.

Syntax

HRESULT GetAnimationSetByName(

    LPCSTR pName,
    LPD3DXANIMATIONSET *ppAnimSet
);

Parameters

pName
[in] String containing the name of the animation set.
ppAnimSet
[out] Pointer to the ID3DXAnimationSet animation set.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned:

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The animation controller contains an array of animation sets. This method returns an animation set that has the given name.


ID3DXAnimationController::GetCurrentPriorityBlend Method

Returns an event handle to a priority blend event that is currently running.

Syntax

D3DXEVENTHANDLE GetCurrentPriorityBlend(VOID);

Return Value

Event handle to the currently running priority blend event. NULL is returned if no priority blend event is currently running.


ID3DXAnimationController::GetCurrentTrackEvent Method

Returns an event handle to the event currently running on the specified animation track.

Syntax

D3DXEVENTHANDLE GetCurrentTrackEvent(

    UINT Track,
    D3DXEVENT_TYPE EventType
);

Parameters

Track
[in] Track identifier.
EventType
[in] Type of event to query.

Return Value

Event handle to the event currently running on the specified track. NULL is returned if no event is running on the specified track.


ID3DXAnimationController::GetEventDesc Method

Gets a description of a specified animation event.

Syntax

HRESULT GetEventDesc(

    D3DXEVENTHANDLE hEvent,
    LPD3DXEVENT_DESC pDesc
);

Parameters

hEvent
[in] Event handle to an animation event to describe.
pDesc
[out] Pointer to a D3DXEVENT_DESC structure that contains a description of the animation event.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXAnimationController::GetMaxNumAnimationOutputs Method

Get the maximum number of animation outputs the animation controller can support.

Syntax

UINT GetMaxNumAnimationOutputs(VOID);

Return Value

The maximum number of animation outputs the controller can manage.


ID3DXAnimationController::GetMaxNumAnimationSets Method

Gets the maximum number of animation sets the animation controller can support.

Syntax

UINT GetMaxNumAnimationSets(VOID);

Return Value

The maximum number of animation sets the controller can manage.


ID3DXAnimationController::GetMaxNumEvents Method

Gets the maximum number of events the animation controller can support.

Syntax

UINT GetMaxNumEvents(VOID);

Return Value

The maximum number of events the controller can manage.


ID3DXAnimationController::GetMaxNumTracks Method

Gets the maximum number of tracks in the animation controller.

Syntax

UINT GetMaxNumTracks(VOID);

Return Value

Number of tracks.

Remarks

The maximum number of tracks the controller can manage.


ID3DXAnimationController::GetNumAnimationSets Method

Returns the number of animation sets currently registered in the animation controller.

Syntax

UINT GetNumAnimationSets(VOID);

Return Value

Number of animation sets.

Remarks

The controller contains any number of animations sets and tracks. Animation sets can be registered with ID3DXAnimationController::RegisterAnimationOutput. An animation controller created by a call to D3DXLoadMeshHierarchyFromX will automatically register loaded animation sets.


ID3DXAnimationController::GetPriorityBlend Method

Gets the current priority blending weight used by the animation controller.

Syntax

FLOAT GetPriorityBlend(VOID);

Return Value

Returns the current priority blending weight.

Remarks

The priority blending weight is used to blend high and low priority tracks together.

See Also

ID3DXAnimationController::SetPriorityBlend


ID3DXAnimationController::GetTime Method

Gets the global animation time.

Syntax

DOUBLE GetTime(VOID);

Return Value

Returns the global animation time.

Remarks

Animations are designed using a local animation time and mixed into global time with ID3DXAnimationController::AdvanceTime.


ID3DXAnimationController::GetTrackAnimationSet Method

Gets the animation set for the given track.

Syntax

HRESULT GetTrackAnimationSet(

    UINT Track,
    LPD3DXANIMATIONSET *ppAnimSet
);

Parameters

Track
[in] Track identifier.
ppAnimSet
[out] Pointer to the ID3DXAnimationSet animation set for the given track.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXAnimationController::GetTrackDesc Method

Gets the track description.

Syntax

HRESULT GetTrackDesc(

    UINT Track,
    LPD3DXTRACK_DESC pDesc
);

Parameters

Track
[in] Track identifier.
pDesc
[out] Pointer to the track description. See D3DXTRACK_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXAnimationController::GetUpcomingPriorityBlend Method

Returns an event handle to the next priority blend event scheduled to occur after a specified event.

Syntax

D3DXEVENTHANDLE GetUpcomingPriorityBlend(

    D3DXEVENTHANDLE hEvent
);

Parameters

hEvent
[in] Event handle to a specified event after which to search for a following priority blend event. If set to NULL, then the method will return the next scheduled priority blend event.

Return Value

Event handle to the next scheduled priority blend event.

NULL is returned if no new priority blend event is scheduled.

Remarks

This method can be used iteratively to locate a desired priority blend event by repeatedly passing in NULL for hEvent.

Note Do not iterate further after the method has returned NULL.


ID3DXAnimationController::GetUpcomingTrackEvent Method

Returns an event handle to the next event scheduled to occur after a specified event on an animation track.

Syntax

D3DXEVENTHANDLE GetUpcomingTrackEvent(

    UINT Track,
    D3DXEVENTHANDLE hEvent
);

Parameters

Track
[in] Track identifier.
hEvent
[in] Event handle to a specified event after which to search for a following event. If set to NULL, then the method will return the next scheduled event.

Return Value

Event handle to the next event scheduled to run on the specified track.

NULL is returned if no new event is scheduled.

Remarks

This method can be used iteratively to locate a desired event by repeatedly passing in NULL for hEvent.

Note Do not iterate further after the method has returned NULL.


ID3DXAnimationController::KeyPriorityBlend Method

Sets blending event keys for the specified animation track.

Syntax

D3DXEVENTHANDLE KeyPriorityBlend(

    FLOAT NewBlendWeight,
    DOUBLE StartTime,
    DOUBLE Duration,
    D3DXTRANSITION_TYPE Transition
);

Parameters

NewBlendWeight
[in] Number between 0 and 1 that is used to blend tracks together.
StartTime
[in] Global time to start the blend.
Duration
[in] Global time duration of the blend.
Transition
[in] Specifies the transition type used for the duration of the blend. See D3DXTRANSITION_TYPE.

Return Value

Event handle to the priority blend event.

NULL is returned if one or more of the input parameters is invalid, or no free event is available.

Remarks

The animation controller blends in three phases: low priority tracks are blended first, high priority tracks are blended second, and then the results of both are blended.

See Also

ID3DXAnimationController::SetPriorityBlend


ID3DXAnimationController::KeyTrackEnable Method

Sets an event key that enables or disables an animation track.

Syntax

D3DXEVENTHANDLE KeyTrackEnable(

    UINT Track,
    BOOL NewEnable,
    DOUBLE StartTime
);

Parameters

Track
[in] Identifier of the animation track to modify.
NewEnable
[in] Enable flag. Set this to TRUE to enable the animation track, or to FALSE to disable the track.
StartTime
[in] Global time key. Specifies the global time when the change will take place.

Return Value

Event handle to the priority blend event.

NULL is returned if Track is invalid.


ID3DXAnimationController::KeyTrackPosition Method

Sets an event key that changes the local time of an animation track.

Syntax

D3DXEVENTHANDLE KeyTrackPosition(

    UINT Track,
    DOUBLE NewPosition,
    DOUBLE StartTime
);

Parameters

Track
[in] Identifier of the track to modify.
NewPosition
[in] New local time of the animation track.
StartTime
[in] Global time key. Specifies the global time when the change will take place.

Return Value

Event handle to the priority blend event.

NULL is returned if Track is invalid, or if no free event is available.


ID3DXAnimationController::KeyTrackSpeed Method

Sets an event key that changes the rate of play of an animation track.

Syntax

D3DXEVENTHANDLE KeyTrackSpeed(

    UINT Track,
    FLOAT NewSpeed,
    DOUBLE StartTime,
    DOUBLE Duration,
    D3DXTRANSITION_TYPE Transition
);

Parameters

Track
[in] Identifier of the track to modify.
NewSpeed
[in] New speed of the animation track.
StartTime
[in] Global time key. Specifies the global time when the change will take place.
Duration
[in] Transition time, which specifies how long the smooth transition will take to complete.
Transition
[in] Specifies the transition type used for transitioning between speeds. See D3DXTRANSITION_TYPE.

Return Value

Event handle to the priority blend event.

NULL is returned if one or more of the input parameters is invalid, or no free event is available.


ID3DXAnimationController::KeyTrackWeight Method

Sets an event key that changes the weight of an animation track. The weight is used as a multiplier when combining multiple tracks together.

Syntax

D3DXEVENTHANDLE KeyTrackWeight(

    UINT Track,
    FLOAT NewWeight,
    DOUBLE StartTime,
    DOUBLE Duration,
    D3DXTRANSITION_TYPE Transition
);

Parameters

Track
[in] Identifier of the track to modify.
NewWeight
[in] New weight of the track.
StartTime
[in] Global time key. Specifies the global time when the change will take place.
Duration
[in] Transition time, which specifies how long the smooth transition will take to complete.
Transition
[in] Specifies the transition type used for transitioning between weights. See D3DXTRANSITION_TYPE.

Return Value

Event handle to the priority blend event.

NULL is returned if one or more of the input parameters is invalid, or no free event is available.

Remarks

The weight is used like a multiplier to determine how much of this track to blend together with other tracks.


ID3DXAnimationController::RegisterAnimationOutput Method

Adds an animation output to the animation controller and registers pointers for scale, rotate, and translate (SRT) transformations.

Syntax

HRESULT RegisterAnimationOutput(

    LPCSTR Name,
    D3DXMATRIX *pMatrix,
    D3DXVECTOR3 *pScale,
    D3DXQUATERNION *pRotation,
    D3DXVECTOR3 *pTranslation
);

Parameters

Name
[in] Name of the animation output.
pMatrix
[in] Pointer to a D3DXMATRIX structure containing SRT transformation data. Can be NULL.
pScale
[in] Pointer to a D3DXVECTOR3 vector that describes the scale of the animation set. Can be NULL.
pRotation
[in] Pointer to a D3DXQUATERNION quaternion that describes the rotation of the animation set. Can be NULL.
pTranslation
[in] Pointer to a D3DXVECTOR3 vector that describes the translation of the animation set. Can be NULL.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

If the animation output is already registered, pMatrix will be filled with the input transformation data.

Animation sets created with D3DXLoadMeshHierarchyFromX automatically register all loaded animation sets.


ID3DXAnimationController::RegisterAnimationSet Method

Adds an animation set to the animation controller.

Syntax

HRESULT RegisterAnimationSet(

    LPD3DXANIMATIONSET pAnimSet
);

Parameters

pAnimSet
[in] Pointer to the ID3DXAnimationSet animation set to add.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXAnimationController::ResetTime Method

Resets the global animation time to zero. Any pending events will retain their original schedules, but in the new timeframe.

Syntax

HRESULT ResetTime(VOID);

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This method is typically used when the global animation time value is nearing the maximum precision of DOUBLE storage, or 264 - 1.


ID3DXAnimationController::SetPriorityBlend Method

Sets the priority blending weight used by the animation controller.

Syntax

HRESULT SetPriorityBlend(

    FLOAT BlendWeight
);

Parameters

BlendWeight
[in] Priority blending weight used by the animation controller.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The blend weight is used to blend high and low priority tracks together.

See Also

ID3DXAnimationController::GetPriorityBlend


ID3DXAnimationController::SetTrackAnimationSet Method

Applies the animation set to the specified track.

Syntax

HRESULT SetTrackAnimationSet(

    UINT Track,
    LPD3DXANIMATIONSET pAnimSet
);

Parameters

Track
[in] Identifier of the track to which the animation set is applied.
pAnimSet
[in] Pointer to the ID3DXAnimationSet animation set to be added to the track.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

This method sets the animation set to the specified track for mixing. The animation set for each track is blended according to the track weight and speed when ID3DXAnimationController::AdvanceTime is called.


ID3DXAnimationController::SetTrackDesc Method

Sets the track description.

Syntax

HRESULT SetTrackDesc(

    UINT Track,
    LPD3DXTRACK_DESC pDesc
);

Parameters

Track
[in] Identifier of the track to modify.
pDesc
[in] Description of the track.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXAnimationController::SetTrackEnable Method

Enables or disables a track in the animation controller.

Syntax

HRESULT SetTrackEnable(

    UINT Track,
    BOOL Enable
);

Parameters

Track
[in] Identifier of the track to be mixed.
Enable
[in] Enable value. Set to TRUE to enable this track in the controller, or to FALSE to prevent it from being mixed.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

To mix a track with other tracks, the Enable flag must be set to TRUE. Conversely, setting the flag to FALSE will prevent the track from being mixed with other tracks.


ID3DXAnimationController::SetTrackPosition Method

Sets the track to the specified local animation time.

Syntax

HRESULT SetTrackPosition(

    UINT Track,
    DOUBLE Position
);

Parameters

Track
[in] Track identifier.
Position
[in] Local animation time value to assign to the track.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXAnimationController::SetTrackPriority Method

Sets the priority blending weight for the specified animation track.

Syntax

HRESULT SetTrackPriority(

    UINT Track,
    D3DXPRIORITY_TYPE Priority
);

Parameters

Track
[in] Track identifier.
Priority
[in] Track priority. This parameter should be set to one of the constants from D3DXPRIORITY_TYPE.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXAnimationController::SetTrackSpeed Method

Sets the track speed. The track speed is similar to a multiplier that is used to speed up or slow down the playback of the track.

Syntax

HRESULT SetTrackSpeed(

    UINT Track,
    FLOAT Speed
);

Parameters

Track
[in] Identifier of the track to set the speed on.
Speed
[in] New speed.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXAnimationController::SetTrackWeight Method

Sets the track weight. The weight is used to determine how to blend multiple tracks together.

Syntax

HRESULT SetTrackWeight(

    UINT Track,
    FLOAT Weight
);

Parameters

Track
[in] Identifier of the track to set the weight on.
Weight
[in] Weight value.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXAnimationController::UnkeyAllPriorityBlends Method

Removes all scheduled priority blend events from the animation controller.

Syntax

HRESULT UnkeyAllPriorityBlends(VOID);

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXAnimationController::UnkeyAllTrackEvents Method

Removes all events from a specified animation track.

Syntax

HRESULT UnkeyAllTrackEvents(

    UINT Track
);

Parameters

Track
[in] Identifier of the track on which all events should be removed.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This method prevents the execution of all events previously scheduled on the track, and discards all data associated with those events.


ID3DXAnimationController::UnkeyEvent Method

Removes a specified event from an animation track, preventing the execution of the event.

Syntax

HRESULT UnkeyEvent(

    D3DXEVENTHANDLE hEvent
);

Parameters

hEvent
[in] Event handle to the event to be removed from the animation track.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXAnimationController::UnregisterAnimationSet Method

Removes an animation set from the animation controller.

Syntax

HRESULT UnregisterAnimationSet(

    LPD3DXANIMATIONSET pAnimSet
);

Parameters

pAnimSet
[in] Pointer to the ID3DXAnimationSet animation set to remove.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTFOUND | The requested item was not found.


ID3DXAnimationController::ValidateEvent Method

Checks whether a specified event handle is valid and the animation event has not yet completed.

Syntax

HRESULT ValidateEvent(

    D3DXEVENTHANDLE hEvent
);

Parameters

hEvent
[in] Event handle to an animation event.

Return Value

Returns S_OK if the event handle is valid and the event has not yet completed.

Returns E_FAIL if the event handle is invalid and/or the event has completed.

Remarks

The method will indicate that an event handle is valid even if the event is running but has not yet completed.


ID3DXAnimationSet Interface

This interface encapsulates the minimum functionality required of an animation set by an animation controller. Advanced users might want to implement this interface themselves to suit their specialized needs; for most users, however, the derived ID3DXCompressedAnimationSet and ID3DXKeyframedAnimationSet interfaces should suffice.

ID3DXAnimationSet Members

GetAnimationIndexByName | Gets the index of an animation, given its name.
GetAnimationNameByIndex | Gets the name of an animation, given its index.
GetCallback | Gets information about a specific callback in the animation set.
GetName | Gets the animation set name.
GetNumAnimations | Gets the number of animations in the animation set.
GetPeriod | Gets the period of the animation set.
GetPeriodicPosition | Returns time position in the local timeframe of an animation set.
GetSRT | Gets the scale, rotation, and translation values of the animation set.

Remarks

An animation set consists of animations for many nodes for the same animation.

The LPD3DXANIMATIONSET type is defined as a pointer to this interface.

typedef interface ID3DXAnimationSet ID3DXAnimationSet;
typedef interface ID3DXAnimationSet *LPD3DXANIMATIONSET;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXAnimationSet::GetAnimationIndexByName Method

Gets the index of an animation, given its name.

Syntax

HRESULT GetAnimationIndexByName(

    LPCSTR pName,
    UINT *pIndex
);

Parameters

pName
[in] Name of the animation.
pIndex
[out] Pointer to the animation index.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR.


ID3DXAnimationSet::GetAnimationNameByIndex Method

Gets the name of an animation, given its index.

Syntax

HRESULT GetAnimationNameByIndex(

    UINT Index,
    LPCSTR *ppName
);

Parameters

Index
[in] Index of the animation.
ppName
[out] Address of a pointer to a string that receives the animation name.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR.


ID3DXAnimationSet::GetCallback Method

Gets information about a specific callback in the animation set.

Syntax

HRESULT GetCallback(

    DOUBLE Position,
    DWORD Flags,
    DOUBLE *pCallbackPosition,
    LPVOID *ppCallbackData
);

Parameters

Position
[in] Position from which to find callbacks.
Flags
[in] Callback search flags. This parameter can be set to a combination of one or more flags from D3DXCALLBACK_SEARCH_FLAGS.
pCallbackPosition
[out] Pointer to the position of the callback.
ppCallbackData
[out] Address of the callback data pointer.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR.


ID3DXAnimationSet::GetName Method

Gets the animation set name.

Syntax

LPCSTR GetName(VOID);

Return Value

Name of the animation set.


ID3DXAnimationSet::GetNumAnimations Method

Gets the number of animations in the animation set.

Syntax

UINT GetNumAnimations(VOID);

Return Value

Number of animations in the animation set.


ID3DXAnimationSet::GetPeriod Method

Gets the period of the animation set.

Syntax

DOUBLE GetPeriod(VOID);

Return Value

Period of the animation set.

Remarks

The period is the range of time that the animation key frames are valid. For looping animations, this is the period of the loop. The time units that the key frames are specified in (for example, seconds) is determined by the application.


ID3DXAnimationSet::GetPeriodicPosition Method

Returns time position in the local timeframe of an animation set.

Syntax

DOUBLE GetPeriodicPosition(

    DOUBLE Position
);

Parameters

Position
[in] Local time of the animation set.

Return Value

Time position as measured in the timeframe of the animation set. This value will be bounded by the period of the animation set.

Remarks

The time position returned by this method can be used as the PeriodicPosition parameter of ID3DXAnimationSet::GetSRT.


ID3DXAnimationSet::GetSRT Method

Gets the scale, rotation, and translation values of the animation set.

Syntax

HRESULT GetSRT(

    DOUBLE PeriodicPosition,
    UINT Animation,
    D3DXVECTOR3 *pScale,
    D3DXQUATERNION *pRotation,
    D3DXVECTOR3 *pTranslation
);

Parameters

PeriodicPosition
[in] Position of the animation set. The position can be obtained by calling ID3DXAnimationSet::GetPeriodicPosition.
Animation
[in] Animation index.
pScale
[out] Pointer to the D3DXVECTOR3 vector that describes the scale of the animation set.
pRotation
[out] Pointer to the D3DXQUATERNION quaternion that describes the rotation of the animation set.
pTranslation
[out] Pointer to the D3DXVECTOR3 vector that describes the translation of the animation set.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR.


ID3DXBaseMesh Interface

Applications use the methods of the ID3DXBaseMesh interface to manipulate and query mesh and progressive mesh objects.

ID3DXBaseMesh Members

CloneMesh | Clones a mesh using a declarator.
CloneMeshFVF | Clones a mesh using a flexible vertex format (FVF) code.
ConvertAdjacencyToPointReps | Converts mesh adjacency information to an array of point representatives.
ConvertPointRepsToAdjacency | Converts point representative data to mesh adjacency information.
DrawSubset | Draws a subset of a mesh.
GenerateAdjacency | Generate a list of mesh edges and the faces that share each edge.
GetAttributeTable | Retrieves either an attribute table for a mesh, or the number of entries stored in an attribute table for a mesh.
GetDeclaration | Retrieves a declaration describing the vertices in the mesh.
GetDevice | Retrieves the device associated with the mesh.
GetFVF | Gets the fixed function vertex value.
GetIndexBuffer | Retrieves the data in an index buffer.
GetNumBytesPerVertex | Gets the number of bytes per vertex.
GetNumFaces | Retrieves the number of faces in the mesh.
GetNumVertices | Retrieves the number of vertices in the mesh.
GetOptions | Retrieves the mesh options enabled for this mesh at creation time.
GetVertexBuffer | Retrieves the data in a vertex buffer.
LockIndexBuffer | Locks an index buffer and obtains a pointer to the index buffer memory.
LockVertexBuffer | Locks a vertex buffer and obtains a pointer to the vertex buffer memory.
UnlockIndexBuffer | Unlocks an index buffer.
UnlockVertexBuffer | Unlocks a vertex buffer.
UpdateSemantics | This method allows the user to change the mesh declaration without changing the data layout of the vertex buffer. The call is valid only if the old and new declaration formats have the same vertex size.

Remarks

A mesh is an object made up of a set of polygonal faces. A mesh defines a set of vertices and a set of faces (the faces are defined in terms of the vertices and normals of the mesh).

The LPD3DXBASEMESH type is defined as a pointer to the ID3DXBaseMesh interface.

typedef struct ID3DXBaseMesh *LPD3DXBASEMESH;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

ID3DXMesh, ID3DXPMesh


ID3DXBaseMesh::CloneMesh Method

Clones a mesh using a declarator.

Syntax

HRESULT CloneMesh(

    DWORD Options,
    const D3DVERTEXELEMENT9 *pDeclaration,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXMESH *ppCloneMesh
);

Parameters

Options
[in] A combination of one or more D3DXMESH flags specifying creation options for the mesh.
pDeclaration
[in] An array of D3DVERTEXELEMENT9 elements, which specify the vertex format for the vertices in the output mesh.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device object associated with the mesh.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXMesh interface, representing the cloned mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

ID3DXBaseMesh::CloneMesh is used to reformat and change the vertex data layout. This is done by creating a new mesh object. For example, use it to add space for normals, texture coordinates, colors, weights, etc. that were not present before.

ID3DXBaseMesh::UpdateSemantics updates the vertex declaration with different semantic information without changing the layout of the vertex buffer. This method does not modify the contents of the vertex buffer. For example, use it to relabel a 3-D texture coordinate as a binormal or tangent or vice versa.

See Also

ID3DXBaseMesh::CloneMeshFVF, ID3DXBaseMesh::GetDeclaration, ID3DXMesh::GetDeclaration, ID3DXPMesh::GetDeclaration, D3DXDeclaratorFromFVF


ID3DXBaseMesh::CloneMeshFVF Method

Clones a mesh using a flexible vertex format (FVF) code.

Syntax

HRESULT CloneMeshFVF(

    DWORD Options,
    DWORD FVF,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXMESH *ppCloneMesh
);

Parameters

Options
[in] A combination of one or more D3DXMESH flags specifying creation options for the mesh.
FVF
[in] Combination of FVF codes, which specifies the vertex format for the vertices in the output mesh. For the values of the codes, see D3DFVF.
pDevice
[in] Pointer to an IDirect3DDevice9 interface representing the device object associated with the mesh.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXMesh interface, representing the cloned mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

ID3DXBaseMesh::CloneMeshFVF is used to reformat and change the vertex data layout. This is done by creating a new mesh object. For example, use it to to add space for normals, texture coordinates, colors, weights, etc. that were not present before.

ID3DXBaseMesh::UpdateSemantics updates the vertex declaration with different semantic information without changing the layout of the vertex buffer. This method does not modify the contents of the vertex buffer. For example, use it to relabel a 3-D texture coordinate as a binormal or tangent or vice versa.

See Also

ID3DXBaseMesh::CloneMesh, ID3DXBaseMesh::GetFVF, ID3DXMesh::GetFVF, ID3DXPMesh::GetFVF, D3DXFVFFromDeclarator


ID3DXBaseMesh::ConvertAdjacencyToPointReps Method

Converts mesh adjacency information to an array of point representatives.

Syntax

HRESULT ConvertAdjacencyToPointReps(

    CONST DWORD* pAdjacency,
    DWORD* pPRep
);

Parameters

pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh. The number of bytes in this array must be at least 3 * ID3DXBaseMesh::GetNumFaces * sizeof(DWORD).
pPRep
[in, out] Pointer to an array of one DWORD per vertex of the mesh that will be filled with point representative data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

See Also

ID3DXBaseMesh::ConvertPointRepsToAdjacency, ID3DXMesh::ConvertPointRepsToAdjacency, ID3DXPMesh::ConvertPointRepsToAdjacency


ID3DXBaseMesh::ConvertPointRepsToAdjacency Method

Converts point representative data to mesh adjacency information.

Syntax

HRESULT ConvertPointRepsToAdjacency(

    CONST DWORD* pPRep,
    DWORD* pAdjacency
);

Parameters

pPRep
[in] Pointer to an array of one DWORD per vertex of the mesh that contains point representative data. This parameter is optional. Supplying a NULL value will cause this parameter to be interpreted as an "identity" array.
pAdjacency
[in, out] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh. The number of bytes in this array must be at least 3 * ID3DXBaseMesh::GetNumFaces * sizeof(DWORD).

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

See Also

ID3DXBaseMesh::ConvertAdjacencyToPointReps, ID3DXMesh::ConvertAdjacencyToPointReps, ID3DXPMesh::ConvertAdjacencyToPointReps


ID3DXBaseMesh::DrawSubset Method

Draws a subset of a mesh.

Syntax

HRESULT DrawSubset(

    DWORD AttribId
);

Parameters

AttribId
[in] DWORD that specifies which subset of the mesh to draw. This value is used to differentiate faces in a mesh as belonging to one or more attribute groups.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

An attribute table is used to identify areas of the mesh that need to be drawn with different textures, render states, materials, and so on. In addition, the application can use the attribute table to hide portions of a mesh by not drawing a given attribute identifier (AttribId) when drawing the frame.

See Also

ID3DXBaseMesh::GetAttributeTable, ID3DXMesh::GetAttributeTable, ID3DXPMesh::GetAttributeTable


ID3DXBaseMesh::GenerateAdjacency Method

Generate a list of mesh edges and the faces that share each edge.

Syntax

HRESULT GenerateAdjacency(

    FLOAT Epsilon,
    DWORD *pAdjacency
);

Parameters

Epsilon
[in] Specifies that vertices that differ in position by less than epsilon should be treated as coincident.
pAdjacency
[in] Pointer to an array of three DWORDs per face to be filled with adjacent face indices. The number of bytes in this array must be at least 3 * ID3DXBaseMesh::GetNumFaces * sizeof(DWORD).

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

After an application generates adjacency information for a mesh, the mesh data can be optimized for better drawing performance.

See Also

ID3DXMesh::Optimize, ID3DXMesh::OptimizeInplace


ID3DXBaseMesh::GetAttributeTable Method

Retrieves either an attribute table for a mesh, or the number of entries stored in an attribute table for a mesh.

Syntax

HRESULT GetAttributeTable(

    D3DXATTRIBUTERANGE *pAttribTable,
    DWORD *pAttribTableSize
);

Parameters

pAttribTable
[in, out] Pointer to an array of D3DXATTRIBUTERANGE structures, representing the entries in the mesh's attribute table. Specify NULL to retrieve the value for pAttribTableSize.
pAttribTableSize
[in, out] Pointer to either the number of entries stored in pAttribTable or a value to be filled in with the number of entries stored in the attribute table for the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

An attribute table is created by ID3DXMesh::Optimize and passing D3DXMESHOPT_ATTRSORT for the Flags parameter.

An attribute table is used to identify areas of the mesh that need to be drawn with different textures, render states, materials, and so on. In addition, the application can use the attribute table to hide portions of a mesh by not drawing a given attribute identifier when drawing the frame.


ID3DXBaseMesh::GetDeclaration Method

Retrieves a declaration describing the vertices in the mesh.

Syntax

HRESULT GetDeclaration(

    D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

Declaration
[in, out] Array of D3DVERTEXELEMENT9 elements describing the vertex format of the mesh vertices. The upper limit of this declarator array is MAX_FVF_DECL_SIZE. The vertex element array ends with the D3DDECL_END macro.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The array of elements includes the D3DDECL_END macro, which ends the declaration.

See Also

ID3DXBaseMesh::GetFVF, ID3DXMesh::GetFVF, ID3DXPMesh::GetFVF


ID3DXBaseMesh::GetDevice Method

Retrieves the device associated with the mesh.

Syntax

HRESULT GetDevice(

    LPDIRECT3DDEVICE9 *ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface, representing the Microsoft Direct3D device object associated with the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Be sure to call IUnknown::Release when you are done using this IDirect3DDevice9 interface or you will have a memory leak.


ID3DXBaseMesh::GetFVF Method

Gets the fixed function vertex value.

Syntax

DWORD GetFVF(VOID);

Return Value

Returns the flexible vertex format (FVF) codes.

Remarks

This method can return 0 if the vertex format cannot be mapped directly to an FVF code. This will occur for a mesh created from a vertex declaration that doesn't have the same order and elements supported by the FVF codes.


ID3DXBaseMesh::GetIndexBuffer Method

Retrieves the data in an index buffer.

Syntax

HRESULT GetIndexBuffer(

    LPDIRECT3DINDEXBUFFER9 *ppIB
);

Parameters

ppIB
[out, retval] Address of a pointer to an IDirect3DIndexBuffer9 interface, representing the index buffer object associated with the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXBaseMesh::GetNumBytesPerVertex Method

Gets the number of bytes per vertex.

Syntax

DWORD GetNumBytesPerVertex(VOID);

Return Value

Returns the number of bytes per vertex.


ID3DXBaseMesh::GetNumFaces Method

Retrieves the number of faces in the mesh.

Syntax

DWORD GetNumFaces(VOID);

Return Value

Returns the number of faces in the mesh.


ID3DXBaseMesh::GetNumVertices Method

Retrieves the number of vertices in the mesh.

Syntax

DWORD GetNumVertices(VOID);

Return Value

Returns the number of vertices in the mesh.


ID3DXBaseMesh::GetOptions Method

Retrieves the mesh options enabled for this mesh at creation time.

Syntax

DWORD GetOptions(VOID);

Return Value

Returns a combination of one or more of the following flags, indicating the options enabled for this mesh at creation time.

D3DXMESH_32BIT | Use 32-bit indices.
D3DXMESH_DONOTCLIP | Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC | Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES | Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES | Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft Direct3D.
D3DXMESH_MANAGED | Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS | Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC | Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED | Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM | Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY | Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM | Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC | Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED | Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SYSTEMMEM | Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY | Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY | Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.


ID3DXBaseMesh::GetVertexBuffer Method

Retrieves the data in a vertex buffer.

Syntax

HRESULT GetVertexBuffer(

    LPDIRECT3DVERTEXBUFFER9 *ppVB
);

Parameters

ppVB
[out, retval] Address of a pointer to an IDirect3DVertexBuffer9 interface, representing the vertex buffer object associated with the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXBaseMesh::LockIndexBuffer Method

Locks an index buffer and obtains a pointer to the index buffer memory.

Syntax

HRESULT LockIndexBuffer(

    DWORD Flags,
    LPVOID *ppData
);

Parameters

Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY

For a description of the flags, see D3DLOCK.

ppData
[out, retval] VOID* pointer to a buffer containing the index data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When working with index buffers, you are allowed to make multiple lock calls. However, you must ensure that the number of lock calls match the number of unlock calls. DrawPrimitive calls will not succeed with any outstanding lock count on any currently set index buffer.

See Also

ID3DXBaseMesh::UnlockIndexBuffer, ID3DXMesh::UnlockIndexBuffer, ID3DXPMesh::UnlockIndexBuffer


ID3DXBaseMesh::LockVertexBuffer Method

Locks a vertex buffer and obtains a pointer to the vertex buffer memory.

Syntax

HRESULT LockVertexBuffer(

    DWORD Flags,
    LPVOID *ppData
);

Parameters

Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY
  • D3DLOCK_NOOVERWRITE

For a description of the flags, see D3DLOCK.

ppData
[out, retval] VOID* pointer to a buffer containing the vertex data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When working with vertex buffers, you are allowed to make multiple lock calls; however, you must ensure that the number of lock calls match the number of unlock calls. DrawPrimitive calls will not succeed with any outstanding lock count on any currently set vertex buffer.

See Also

ID3DXBaseMesh::UnlockVertexBuffer, ID3DXMesh::UnlockVertexBuffer, ID3DXPMesh::UnlockVertexBuffer


ID3DXBaseMesh::UnlockIndexBuffer Method

Unlocks an index buffer.

Syntax

HRESULT UnlockIndexBuffer(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseMesh::LockIndexBuffer, ID3DXMesh::LockIndexBuffer, ID3DXPMesh::LockIndexBuffer


ID3DXBaseMesh::UnlockVertexBuffer Method

Unlocks a vertex buffer.

Syntax

HRESULT UnlockVertexBuffer(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseMesh::LockVertexBuffer, ID3DXMesh::LockVertexBuffer, ID3DXPMesh::LockVertexBuffer


ID3DXBaseMesh::UpdateSemantics Method

This method allows the user to change the mesh declaration without changing the data layout of the vertex buffer. The call is valid only if the old and new declaration formats have the same vertex size.

Syntax

HRESULT UpdateSemantics(

    D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

Declaration
[in, out] An array of D3DVERTEXELEMENT9 elements, describing the vertex format of the mesh vertices. The upper limit of this declarator array is MAX_FVF_DECL_SIZE.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

ID3DXBaseMesh::CloneMesh is used to reformat and change the vertex data layout. For example, use it to to add space for normals, texture coordinates, colors, weights, etc. that were not present before.

ID3DXBaseMesh::UpdateSemantics is a method for updating the vertex declaration with different semantic information, without changing the layout of the vertex buffer. For example, use it to relabel a 3-D texture coordinate as a binormal or tangent, or vice versa.

See Also

ID3DXBaseMesh::CloneMeshFVF, ID3DXBaseMesh::CloneMesh, ID3DXBaseMesh::GetDeclaration, ID3DXMesh::GetDeclaration, ID3DXPMesh::GetDeclaration, D3DXDeclaratorFromFVF


ID3DXBuffer Interface

The ID3DXBuffer interface is used as a data buffer, storing vertex, adjacency, and material information during mesh optimization and loading operations. The buffer object is used to return arbitrary length data. Also, buffer objects are used to return object code and error messages in methods that assemble vertex and pixel shaders.

ID3DXBuffer Members

GetBufferPointer | Retrieves a pointer to the data in the buffer.
GetBufferSize | Retrieves the total size of the data in the buffer.

Remarks

The ID3DXBuffer interface is obtained by calling the D3DXCreateBuffer function.

The LPD3DXBUFFER type is defined as a pointer to the ID3DXBuffer interface.

typedef interface ID3DXBuffer ID3DXBuffer;
typedef interface ID3DXBuffer *LPD3DXBUFFER;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXBuffer::GetBufferPointer Method

Retrieves a pointer to the data in the buffer.

Syntax

LPVOID GetBufferPointer(VOID);

Return Value

Returns a pointer to the data in the buffer.


ID3DXBuffer::GetBufferSize Method

Retrieves the total size of the data in the buffer.

Syntax

DWORD GetBufferSize(VOID);

Return Value

Returns the total size of the data in the buffer, in bytes.


ID3DXCompressedAnimationSet Interface

An application uses the methods of this interface to implement a key frame animation set stored in a compressed data format.

ID3DXCompressedAnimationSet Members

GetAnimationIndexByName | Gets the index of an animation, given its name.
GetAnimationNameByIndex | Gets the name of an animation, given its index.
GetCallback | Gets information about a specific callback in the animation set.
GetCallbackKeys | Fills an array with callback key data used for key frame animation.
GetCompressedData | Gets the data buffer that stores compressed key frame animation data.
GetName | Gets the animation set name.
GetNumAnimations | Gets the number of animations in the animation set.
GetNumCallbackKeys | Gets the number of callback keys in the animation set.
GetPeriod | Gets the period of the animation set.
GetPeriodicPosition | Returns time position in the local timeframe of an animation set.
GetPlaybackType | Gets the type of the animation set playback loop.
GetSourceTicksPerSecond | Gets the number of animation key frame ticks that occur per second.
GetSRT | Gets the scale, rotation, and translation values of the animation set.

Remarks

Create a compressed-format key frame animation set with D3DXCreateCompressedAnimationSet.

The LPD3DXCOMPRESSEDANIMATIONSET type is defined as a pointer to this interface.

typedef interface ID3DXCompressedAnimationSet ID3DXCompressedAnimationSet;
typedef interface ID3DXCompressedAnimationSet *LPD3DXCOMPRESSEDANIMATIONSET;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | ID3DXAnimationSet
Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXCompressedAnimationSet::GetCallbackKeys Method

Fills an array with callback key data used for key frame animation.

Syntax

HRESULT GetCallbackKeys(

    LPD3DXKEY_CALLBACK pCallbackKeys
);

Parameters

pCallbackKeys
[out] Pointer to a user-allocated array of D3DXKEY_CALLBACK structures that the method is to fill with callback data.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

See Also

ID3DXCompressedAnimationSet::GetNumCallbackKeys


ID3DXCompressedAnimationSet::GetCompressedData Method

Gets the data buffer that stores compressed key frame animation data.

Syntax

HRESULT GetCompressedData(

    LPD3DXBUFFER *ppCompressedData
);

Parameters

ppCompressedData
[out] Address of a pointer to the ID3DXBuffer data buffer that receives compressed key frame animation data.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXCompressedAnimationSet::GetNumCallbackKeys Method

Gets the number of callback keys in the animation set.

Syntax

UINT GetNumCallbackKeys(VOID);

Return Value

Number of callback keys in the animation set.


ID3DXCompressedAnimationSet::GetPlaybackType Method

Gets the type of the animation set playback loop.

Syntax

D3DXPLAYBACK_TYPE GetPlaybackType(VOID);

Return Value

Type of the animation set playback loop. See D3DXPLAYBACK_TYPE.


ID3DXCompressedAnimationSet::GetSourceTicksPerSecond Method

Gets the number of animation key frame ticks that occur per second.

Syntax

DOUBLE GetSourceTicksPerSecond(VOID);

Return Value

Number of animation key frame ticks that occur per second.


ID3DXConstantTable Interface

The ID3DXConstantTable interface is used to access the constant table. This table contains the variables that are used by high-level language shaders and effects.

ID3DXConstantTable Members

GetBufferPointer | Gets a pointer to the buffer that contains the constant table.
GetBufferSize | Gets the buffer size of the constant table.
GetConstant | Gets a constant by looking up its index.
GetConstantByName | Gets a constant by looking up its name.
GetConstantDesc | Gets a pointer to an array of constant descriptions in the constant table.
GetConstantElement | Gets a constant from an array of constants. An array is made up of elements.
GetDesc | Gets a description of the constant table.
GetSamplerIndex | Returns the sampler index.
SetBool | Sets a Boolean value.
SetBoolArray | Sets an array of Boolean values.
SetDefaults | Sets the constants to their default values. The default values are declared in the variable declarations in the shader.
SetFloat | Sets a floating-point number.
SetFloatArray | Sets an array of floating-point numbers.
SetInt | Sets an integer value.
SetIntArray | Sets an array of integers.
SetMatrix | Sets a nontransposed matrix.
SetMatrixArray | Sets an array of nontransposed matrices.
SetMatrixPointerArray | Sets an array of pointers to nontransposed matrices.
SetMatrixTranspose | Sets a transposed matrix.
SetMatrixTransposeArray | Sets an array of transposed matrices.
SetMatrixTransposePointerArray | Sets an array of pointers to transposed matrices.
SetValue | Sets the contents of the buffer to the constant table.
SetVector | Sets a 4-D vector.
SetVectorArray | Sets an array of 4-D vectors.

Remarks

The LPD3DXCONSTANTTABLE type is defined as a pointer to the ID3DXConstantTable interface.

typedef interface ID3DXConstantTable ID3DXConstantTable;
typedef interface ID3DXConstantTable *LPD3DXCONSTANTTABLE;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXConstantTable::GetBufferPointer Method

Gets a pointer to the buffer that contains the constant table.

Syntax

LPVOID GetBufferPointer(VOID);

Return Value

Returns a pointer the buffer.

See Also

ID3DXConstantTable::GetBufferSize


ID3DXConstantTable::GetBufferSize Method

Gets the buffer size of the constant table.

Syntax

DWORD GetBufferSize(VOID);

Return Value

Returns the size of the buffer, in bytes.


ID3DXConstantTable::GetConstant Method

Gets a constant by looking up its index.

Syntax

D3DXHANDLE GetConstant(

    D3DXHANDLE hConstant,
    UINT Index
);

Parameters

hConstant
[in] Unique identifier to the parent data structure. If the constant is a top-level parameter (there is no parent data structure), use NULL.
Index
[in] Zero-based index of the constant.

Return Value

Returns a unique identifier to the constant.

Remarks

To get a constant from an array of constants, use ID3DXConstantTable::GetConstantElement.


ID3DXConstantTable::GetConstantByName Method

Gets a constant by looking up its name.

Syntax

D3DXHANDLE GetConstantByName(

    D3DXHANDLE hConstant,
    LPCSTR pName
);

Parameters

hConstant
[in] Unique identifier to the parent data structure. If the constant is a top-level parameter (there is no parent data structure), use NULL.
pName
[in] Name of the constant.

Return Value

Returns a unique identifier to the constant.


ID3DXConstantTable::GetConstantDesc Method

Gets a pointer to an array of constant descriptions in the constant table.

Syntax

HRESULT GetConstantDesc(

    D3DXHANDLE hConstant,
    D3DXCONSTANT_DESC *pDesc,
    UINT *pCount
);

Parameters

hConstant
[in] Unique identifier to a constant. See D3DXHANDLE.
pDesc
[in, out] Returns a pointer to an array of descriptions. See D3DXCONSTANT_DESC.
pCount
[in, out] The input supplied must be the maximum size of the array. The output is the number of elements that are filled in the array when the function returns.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

ID3DXConstantTable::GetConstantDesc will sometimes return a D3DXCONSTANT_DESC with a Register_Count of 0. This will happen with a constant appears in more than one Register_Set but does not have space in that register set allocated.

Because a sampler can appear more than once in a constant table, this method can return an array of descriptions, each one with a different register index.

See Also

ID3DXConstantTable::GetDesc


ID3DXConstantTable::GetConstantElement Method

Gets a constant from an array of constants. An array is made up of elements.

Syntax

D3DXHANDLE GetConstantElement(

    D3DXHANDLE hConstant,
    UINT Index
);

Parameters

hConstant
[in] Unique identifier to the array of constants. This value may not be NULL.
Index
[in] Zero-based index of the element in the array.

Return Value

Returns a unique identifier to the element constant.

Remarks

To get a constant that is not part of an array, use ID3DXConstantTable::GetConstant or ID3DXConstantTable::GetConstantByName.


ID3DXConstantTable::GetDesc Method

Gets a description of the constant table.

Syntax

HRESULT GetDesc(

    D3DXCONSTANTTABLE_DESC* pDesc
);

Parameters

pDesc
[in] Description of the constant table. See D3DXCONSTANTTABLE_DESC.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

See Also

ID3DXConstantTable::GetConstantDesc


ID3DXConstantTable::GetSamplerIndex Method

Returns the sampler index.

Syntax

UINT GetSamplerIndex(

    D3DXHANDLE hConstant
);

Parameters

hConstant
[out] The sampler handle.

Return Value

Returns the sampler index number from the constant table.


ID3DXConstantTable::SetBool Method

Sets a Boolean value.

Syntax

HRESULT SetBool(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    BOOL b
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the constant. See D3DXHANDLE.
b
[in] Boolean value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXConstantTable::SetBoolArray Method

Sets an array of Boolean values.

Syntax

HRESULT SetBoolArray(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    CONST BOOL* pB,
    UINT Count
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the array of constants. See D3DXHANDLE.
pB
[in] Array of Boolean values.
Count
[in] Number of Boolean values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXConstantTable::SetDefaults Method

Sets the constants to their default values. The default values are declared in the variable declarations in the shader.

Syntax

HRESULT SetDefaults(

    LPDIRECT3DDEVICE9 pDevice
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXConstantTable::SetFloat Method

Sets a floating-point number.

Syntax

HRESULT SetFloat(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    FLOAT f
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the constant. See D3DXHANDLE.
f
[in] Floating-point number.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXConstantTable::SetFloatArray Method

Sets an array of floating-point numbers.

Syntax

HRESULT SetFloatArray(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    CONST FLOAT* pf,
    UINT Count
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the array of constants. See D3DXHANDLE.
pf
[in] Array of floating-point numbers.
Count
[in] Number of floating-point values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXConstantTable::SetInt Method

Sets an integer value.

Syntax

HRESULT SetInt(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    INT n
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the constant. See D3DXHANDLE.
n
[in] Integer.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXConstantTable::SetIntArray Method

Sets an array of integers.

Syntax

HRESULT SetIntArray(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    CONST INT* pn,
    UINT Count
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the array of constants. See D3DXHANDLE.
pn
[in] Array of integers.
Count
[in] Number of integers in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXConstantTable::SetMatrix Method

Sets a nontransposed matrix.

Syntax

HRESULT SetMatrix(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    CONST D3DXMATRIX* pMatrix
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the matrix of constants. See D3DXHANDLE.
pMatrix
[in] Pointer to a nontransposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXConstantTable::SetMatrixArray Method

Sets an array of nontransposed matrices.

Syntax

HRESULT SetMatrixArray(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    CONST D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the array of constant matrices. See D3DXHANDLE.
pMatrix
[in] Array of nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXConstantTable::SetMatrixPointerArray Method

Sets an array of pointers to nontransposed matrices.

Syntax

HRESULT SetMatrixPointerArray(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    const D3DXMATRIX **ppMatrix,
    UINT Count
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to an array of constant matrices. See D3DXHANDLE.
ppMatrix
[in] Array of pointers to nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.


ID3DXConstantTable::SetMatrixTranspose Method

Sets a transposed matrix.

Syntax

HRESULT SetMatrixTranspose(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    CONST D3DXMATRIX* pMatrix
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the matrix of constants. See D3DXHANDLE.
pMatrix
[in] Pointer to a transposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXConstantTable::SetMatrixTransposeArray Method

Sets an array of transposed matrices.

Syntax

HRESULT SetMatrixTransposeArray(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    CONST D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the array of matrix constants. See D3DXHANDLE.
pMatrix
[in] Array of transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXConstantTable::SetMatrixTransposePointerArray Method

Sets an array of pointers to transposed matrices.

Syntax

HRESULT SetMatrixTransposePointerArray(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    CONST D3DXMATRIX** ppMatrix,
    UINT Count
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the array of matrix constants. See D3DXHANDLE.
ppMatrix
[in] Array of pointers to transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.


ID3DXConstantTable::SetValue Method

Sets the contents of the buffer to the constant table.

Syntax

HRESULT SetValue(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    LPCVOID pData,
    UINT Bytes
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to a constant. See D3DXHANDLE.
pData
[in] Buffer containing data.
Bytes
[in] Size of the buffer, in bytes.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXConstantTable::SetVector Method

Sets a 4-D vector.

Syntax

HRESULT SetVector(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    CONST D3DXVECTOR4* pVector
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the vector constant. See D3DXHANDLE.
pVector
[in] Pointer to a 4-D vector.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXConstantTable::SetVectorArray Method

Sets an array of 4-D vectors.

Syntax

HRESULT SetVectorArray(

    LPDIRECT3DDEVICE9 pDevice,
    D3DXHANDLE hConstant,
    CONST D3DXVECTOR4* pVector,
    UINT Count
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the constant table.
hConstant
[in] Unique identifier to the array of vector constants. See D3DXHANDLE.
pVector
[in] Array of 4-D vectors.
Count
[in] Number of vectors in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXFont Interface

The ID3DXFont interface encapsulates the textures and resources needed to render a specific font on a specific device.

ID3DXFont Members

DrawText | Draws formatted text. This method supports ANSI and Unicode strings.
GetDC | Returns a handle to a display device context (DC) that has the font set.
GetDesc | Gets a description of the current font object. GetDescW and GetDescA are identical to this method, except that a pointer is returned to a D3DXFONT_DESCW or D3DXFONT_DESCA structure, respectively.
GetDevice | Retrieves the Microsoft Direct3D device associated with the font object.
GetGlyphData | Returns information about the placement and orientation of a glyph in a character cell.
GetTextMetrics | Retrieves font characteristics that are identified in a TEXTMETRIC World Wide Web link structure. This method supports ANSI and Unicode compiler settings.
OnLostDevice | Releases all references to video memory resources and deletes all stateblocks.
OnResetDevice | Should be called after the device has been reset.
PreloadCharacters | Loads a series of characters into video memory to improve the efficiency of rendering to the device.
PreloadGlyphs | Loads a series of glyphs into video memory to improve the efficiency of rendering to the device.
PreloadText | Loads formatted text into video memory to improve the efficiency of rendering to the device. This method supports ANSI and Unicode strings.

Remarks

The ID3DXFont interface is obtained by calling D3DXCreateFont or D3DXCreateFontIndirect.

The LPD3DXFONT type is defined as a pointer to the ID3DXFont interface.

typedef interface ID3DXFont ID3DXFont;
typedef interface ID3DXFont *LPD3DXFONT;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXFont::DrawText Method

Draws formatted text. This method supports ANSI and Unicode strings.

Syntax

INT DrawText(

    LPD3DXSPRITE pSprite,
    LPCTSTR pString,
    INT Count,
    LPRECT pRect,
    DWORD Format,
    D3DCOLOR Color
);

Parameters

pSprite
[in] Pointer to an ID3DXSprite object that contains the string. Can be NULL, in which case Microsoft Direct3D will render the string with its own sprite object.

To improve efficiency, a sprite object should be specified if ID3DXFont::DrawText is to be called more than once in a row.
pString
[in] Pointer to a string to draw.

If the Count parameter is -1, the string must be null-terminated.
Count
[in] Specifies the number of characters in the string. If Count is -1, then the pString parameter is assumed to be a pointer to a null-terminated string and ID3DXFont::DrawText computes the character count automatically.
pRect
[in] Pointer to a RECT World Wide Web link structure that contains the rectangle, in logical coordinates, in which the text is to be formatted. As with any RECT object, the coordinate value of the rectangle's right side must be greater than that of its left side. Likewise, the coordinate value of the bottom must be greater than that of the top.
Format
[in] Specifies the method of formatting the text. It can be any combination of the following values:
DT_BOTTOM
Justifies the text to the bottom of the rectangle. This value must be combined with DT_SINGLELINE.
DT_CALCRECT
Determines the width and height of the rectangle. If there are multiple lines of text, ID3DXFont::DrawText uses the width of the rectangle pointed to by the pRect parameter and extends the base of the rectangle to bound the last line of text. If there is only one line of text, ID3DXFont::DrawText modifies the right side of the rectangle so that it bounds the last character in the line. In either case, ID3DXFont::DrawText returns the height of the formatted text but does not draw the text.
DT_CENTER
Centers text horizontally in the rectangle.
DT_EXPANDTABS
Expands tab characters. The default number of characters per tab is eight.
DT_LEFT
Aligns text to the left.
DT_NOCLIP
Draws without clipping. ID3DXFont::DrawText is somewhat faster when DT_NOCLIP is used.
DT_RIGHT
Aligns text to the right.
DT_RTLREADING
Displays text in right-to-left reading order for bidirectional text when a Hebrew or Arabic font is selected. The default reading order for all text is left-to-right.
DT_SINGLELINE
Displays text on a single line only. Carriage returns and line feeds do not break the line.
DT_TOP
Top-justifies text.
DT_VCENTER
Centers text vertically (single line only).
DT_WORDBREAK
Breaks words. Lines are automatically broken between words if a word would extend past the edge of the rectangle specified by the pRect parameter. A carriage return/line feed sequence also breaks the line.
Color
[in] Color of the text. For more information, see D3DCOLOR.

Return Value

If the function succeeds, the return value is the height of the text in logical units. If DT_VCENTER or DT_BOTTOM is specified, the return value is the offset from pRect->top to the bottom of the drawn text.

If the function fails, the return value is zero.

Remarks

The parameters of this method are very similar to those of the Microsoft Windows Graphics Device Interface (GDI) DrawText World Wide Web link function.

This method supports both ANSI and Unicode strings.

This method must be called inside a IDirect3DDevice9::BeginScene ... IDirect3DDevice9::EndScene block. The only exception is when an application calls ID3DXFont::DrawText with DT_CALCRECT to calculate the size of a given block of text.

Unless the DT_NOCLIP format is used, this method clips the text so that it does not appear outside the specified rectangle. All formatting is assumed to have multiple lines unless the DT_SINGLELINE format is specified.

If the selected font is too large for the rectangle, this method does not attempt to substitute a smaller font.

This method supports only fonts whose escapement and orientation are both zero.


ID3DXFont::GetDC Method

Returns a handle to a display device context (DC) that has the font set.

Syntax

HDC GetDC(VOID);

Return Value

Handle to a display DC.


ID3DXFont::GetDesc Method

Gets a description of the current font object. GetDescW and GetDescA are identical to this method, except that a pointer is returned to a D3DXFONT_DESCW or D3DXFONT_DESCA structure, respectively.

Syntax

HRESULT GetDesc(

    D3DXFONT_DESC *pDesc
);

Parameters

pDesc
[out] Pointer to a D3DXFONT_DESC structure that describes the font object.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This method describes Unicode font objects if UNICODE is defined. Otherwise GetDescA is called, which returns a pointer to the D3DXFONT_DESCA structure.


ID3DXFont::GetDevice Method

Retrieves the Microsoft Direct3D device associated with the font object.

Syntax

HRESULT GetDevice(

    LPDIRECT3DDEVICE9 *ppDevice
);

Parameters

ppDevice
[out] Address of a pointer to an IDirect3DDevice9 interface, representing the Direct3D device object associated with the font object.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Be sure to call IUnknown::Release when you are done using this IDirect3DDevice9 interface or you will have a memory leak.


ID3DXFont::GetGlyphData Method

Returns information about the placement and orientation of a glyph in a character cell.

Syntax

HRESULT GetGlyphData(

    UINT Glyph,
    LPDIRECT3DTEXTURE9 *ppTexture,
    RECT *pBlackBox,
    POINT *pCellInc
);

Parameters

Glyph
[in] Glyph identifier.
ppTexture
[out] Address of a pointer to a IDirect3DTexture9 object that contains the glyph.
pBlackBox
[out] Pointer to the smallest rectangle object that completely encloses the glyph (its black box).
pCellInc
[out] Pointer to the two-dimensional vector that connects the origin of the current character cell to the origin of the next character cell.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.


ID3DXFont::GetTextMetrics Method

Retrieves font characteristics that are identified in a TEXTMETRIC World Wide Web link structure. This method supports ANSI and Unicode compiler settings.

Syntax

BOOL GetTextMetrics(

    TEXTMETRIC *pTextMetrics
);

Parameters

pTextMetrics
[out] Pointer to a TEXTMETRIC structure, which contains font properties.

Return Value

Nonzero if the function is successful; otherwise 0.

Remarks

The compiler setting also determines the structure type. If Unicode is defined, the function returns a TEXTMETRICW structure. Otherwise, the function call returns a TEXTMETRICA structure.


ID3DXFont::OnLostDevice Method

Releases all references to video memory resources and deletes all stateblocks.

Syntax

HRESULT OnLostDevice(VOID);

Return Value

This method returns S_OK.

Remarks

This method should be called whenever the device is lost. Before this object can be used again, the device must be reset and the ID3DXFont::OnResetDevice method called.

See Also

ID3DXFont::OnResetDevice


ID3DXFont::OnResetDevice Method

Should be called after the device has been reset.

Syntax

HRESULT OnResetDevice(VOID);

Return Value

This method returns S_OK.

Remarks

This method should be called after the device has been reset, before any other methods are called.

See Also

ID3DXFont::OnLostDevice


ID3DXFont::PreloadCharacters Method

Loads a series of characters into video memory to improve the efficiency of rendering to the device.

Syntax

HRESULT PreloadCharacters(

    UINT First,
    UINT Last
);

Parameters

First
[in] Identifier (ID) of the first character to be loaded into video memory.
Last
[in] ID of the last character to be loaded into video memory.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

This method generates textures containing glyphs that represent the input characters. The glyphs are drawn as a series of triangles.

Characters will not be rendered to the device; ID3DXFont::DrawText must still be called to render the characters. However, by pre-loading characters into video memory, ID3DXFont::DrawText will use substantially fewer CPU resources.

This method internally converts characters to glyphs using the Microsoft Windows Graphics Device Interface (GDI) function GetCharacterPlacement World Wide Web link.


ID3DXFont::PreloadGlyphs Method

Loads a series of glyphs into video memory to improve the efficiency of rendering to the device.

Syntax

HRESULT PreloadGlyphs(

    UINT First,
    UINT Last
);

Parameters

First
[in] Identifier (ID) of the first glyph to be loaded into video memory.
Last
[in] ID of the last glyph to be loaded into video memory.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

This method generates textures that contain the input glyphs. The glyphs are drawn as a series of triangles.

Glyphs will not be rendered to the device; ID3DXFont::DrawText must still be called to render the glyphs. However, by pre-loading glyphs into video memory, ID3DXFont::DrawText will use substantially fewer CPU resources.


ID3DXFont::PreloadText Method

Loads formatted text into video memory to improve the efficiency of rendering to the device. This method supports ANSI and Unicode strings.

Syntax

HRESULT PreloadText(

    LPCTSTR *pString,
    INT Count
);

Parameters

pString
[in] Pointer to a string of characters to be loaded into video memory. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR; otherwise, the data type resolves to LPCSTR. See Remarks.
Count
[in] Number of characters in the text string.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to PreloadTextW. Otherwise, the function call resolves to PreloadTextA because ANSI strings are being used.

This method generates textures that contain glyphs that represent the input text. The glyphs are drawn as a series of triangles.

Text will not be rendered to the device; ID3DXFont::DrawText must still be called to render the text. However, by preloading text into video memory, ID3DXFont::DrawText will use substantially fewer CPU resources.

This method internally converts characters to glyphs using the Microsoft Windows Graphics Device Interface (GDI) function GetCharacterPlacement World Wide Web link.


ID3DXFragmentLinker Interface

The ID3DXFragmentLinker interface is used to link shader fragments at runtime.

ID3DXFragmentLinker Members

AddFragments | Add the fragments from a buffer to the fragment linker.
ClearCache | Clear the fragment linker cache.
GetAllFragments | Allocates a buffer and copies the fragment data into it.
GetDevice | Get the device.
GetFragment | Create a buffer containing a linker fragment. This can be used for saving the fragment to disk.
GetFragmentDesc | Get the D3DXFRAGMENT_DESC structure which describes the named fragment.
GetFragmentHandleByIndex | Get a fragment handle by index.
GetFragmentHandleByName | Get a fragment handle by name.
GetNumberOfFragments | Get the number of fragments in the linker.
LinkPixelShader | Link a compiled pixel shader at run time. This is a very lightweight operation.
LinkShader | Link a compiled shader at run time. This is a very lightweight operation.
LinkVertexShader | Link a compiled vertex shader at run time. This is a very lightweight operation.

Remarks

The LPD3DXFRAGMENTLINKER type is defined as a pointer to the ID3DXFragmentLinker interface.

typedef ID3DXFragmentLinker *LPD3DXFRAGMENTLINKER;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXFragmentLinker::AddFragments Method

Add the fragments from a buffer to the fragment linker.

Syntax

HRESULT AddFragments(

    CONST DWORD* pFragments
);

Parameters

pFragments
[in] Pointer to a buffer containing shader fragments. See D3DXGatherFragments.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DXERR_DUPLICATENAMEDFRAGMENT | Multiple fragments with the same name were found. No fragments were added.
E_FAIL | An undetermined error occurred inside the Microsoft Direct3D subsystem.


ID3DXFragmentLinker::ClearCache Method

Clear the fragment linker cache.

Syntax

HRESULT ClearCache(VOID);

Return Value

This method always returns the value S_OK.


ID3DXFragmentLinker::GetAllFragments Method

Allocates a buffer and copies the fragment data into it.

Syntax

HRESULT GetAllFragments(

    LPD3DXBUFFER* ppBuffer
);

Parameters

ppBuffer
[out] Returns a buffer containing compiled shader fragments. See ID3DXBuffer.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXFragmentLinker::GetDevice Method

Get the device.

Syntax

HRESULT GetDevice(

    LPDIRECT3DDEVICE9* ppDevice
);

Parameters

ppDevice
[out] Get a pointer to the IDirect3DDevice9 object, which represents the device.

Return Value

This method always returns the value S_OK.


ID3DXFragmentLinker::GetFragment Method

Create a buffer containing a linker fragment. This can be used for saving the fragment to disk.

Syntax

HRESULT GetFragment(

    D3DXHANDLE Name,
    LPD3DXBUFFER* ppBuffer
);

Parameters

Name
[in] Unique identifier to the fragment name. See Handles.
ppBuffer
[out] Returns a buffer containing a compiled shader fragment. See ID3DXBuffer.

Return Value

If the method succeeds, the return value is S_OK.

If the arguments are invalid, the method will return D3DERR_INVALIDCALL.

If the method fails, the return value can be E_OUTOFMEMORY.


ID3DXFragmentLinker::GetFragmentDesc Method

Get the D3DXFRAGMENT_DESC structure which describes the named fragment.

Syntax

HRESULT GetFragmentDesc(

    D3DXHANDLE Name,
    LPD3DXFRAGMENT_DESC FragDesc
);

Parameters

Name
[in] Unique identifier to the fragment name. See Handles.
FragDesc
[in] Returns a description of the fragment. See D3DXFRAGMENT_DESC.

Return Value

This method always returns the value S_OK.


ID3DXFragmentLinker::GetFragmentHandleByIndex Method

Get a fragment handle by index.

Syntax

D3DXHANDLE GetFragmentHandleByIndex(

    UINT Index
);

Parameters

Index
[in] Zero-based index for the fragment.

Return Value

Unique identifier to the fragment. See Handles. A return value of (D3DX_HANDLE)0 means that no entry for the index was found.


ID3DXFragmentLinker::GetFragmentHandleByName Method

Get a fragment handle by name.

Syntax

D3DXHANDLE GetFragmentHandleByName(

    LPCSTR Name
);

Parameters

Name
[in] Fragment name.

Return Value

Unique identifier to the fragment. See Handles. A return value of (D3DX_HANDLE)0 means that no entry for the name was found.


ID3DXFragmentLinker::GetNumberOfFragments Method

Get the number of fragments in the linker.

Syntax

UINT GetNumberOfFragments(VOID);

Return Value

Returns the number of fragments.


ID3DXFragmentLinker::LinkPixelShader Method

Link a compiled pixel shader at run time. This is a very lightweight operation.

Syntax

HRESULT LinkPixelShader(

    LPCSTR pProfile,
    DWORD Flags,
    CONST D3DXHANDLE *rgFragmentHandles,
    UINT cFragments,
    LPDIRECT3DPIXELSHADER9 *pPShader,
    LPD3DXBUFFER *ppErrorMsgs
);

Parameters

pProfile
[in] Pointer to a pixel shader profile which detemines the shader instruction set. See D3DXGetPixelShaderProfile for a list of the profiles available.
Flags
[in] Link options. See D3DXSHADER Compile Options.
rgFragmentHandles
[in] An array of pixel shader fragment handles. See Handles.
cFragments
[in] Number of fragments to be linked.
pPShader
[out] Pointer to a pixel shader. See IDirect3DPixelShader9.
ppErrorMsgs
[out, retval] Buffer containing at least the first compile error message that occurred. This includes effect compiler errors and high-level language compile errors. For more information about accessing the buffer, see ID3DXBuffer.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

E_FAIL | An undetermined error occurred inside the Microsoft Direct3D subsystem.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.


ID3DXFragmentLinker::LinkShader Method

Link a compiled shader at run time. This is a very lightweight operation.

Syntax

HRESULT LinkShader(

    LPCSTR pProfile,
    DWORD Flags,
    CONST D3DXHANDLE *rgFragmentHandles,
    UINT cFragments,
    LPD3DXBUFFER* ppBuffer,
    LPD3DXBUFFER *ppErrorMsgs
);

Parameters

pProfile
[in] Pointer to a shader profile which detemines the shader instruction set. See D3DXGetVertexShaderProfile or D3DXGetPixelShaderProfile for a list of the profiles available.
Flags
[in] Link options. See D3DXSHADER Compile Options.
rgFragmentHandles
[in] An array of shader fragment handles. See Handles.
cFragments
[in] Number of fragments to be linked.
ppBuffer
[out] Pointer to a buffer that contains compiled shader code. See ID3DXBuffer.
ppErrorMsgs
[out, retval] Buffer containing at least the first compile error message that occurred. This includes effect compiler errors and high-level language compile errors. For more information about accessing the buffer, see ID3DXBuffer.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

E_FAIL | An undetermined error occurred inside the Microsoft Direct3D subsystem.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.


ID3DXFragmentLinker::LinkVertexShader Method

Link a compiled vertex shader at run time. This is a very lightweight operation.

Syntax

HRESULT LinkVertexShader(

    LPCSTR pProfile,
    DWORD Flags,
    CONST D3DXHANDLE *rgFragmentHandles,
    UINT cFragments,
    LPDIRECT3DVERTEXSHADER9* pVShader,
    LPD3DXBUFFER *ppErrorMsgs
);

Parameters

pProfile
[in] Pointer to a vertex shader profile which detemines the shader instruction set. See D3DXGetVertexShaderProfile for a list of the profiles available.
Flags
[in] Link options. See D3DXSHADER Compile Options.
rgFragmentHandles
[in] An array of vertex shader fragment handles. See Handles.
cFragments
[in] Number of fragments to be linked.
pVShader
[out] Pointer to a vertex shader. See IDirect3DVertexShader9.
ppErrorMsgs
[out, retval] Buffer containing at least the first compile error message that occurred. This includes effect compiler errors and high-level language compile errors. For more information about accessing the buffer, see ID3DXBuffer.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

E_FAIL | An undetermined error occurred inside the Microsoft Direct3D subsystem.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.


ID3DXKeyframedAnimationSet Interface

An application uses the methods of this interface to implement a key frame animation set.

ID3DXKeyframedAnimationSet Members

Compress | Transforms animations in an animation set into a compressed format and returns a pointer to the buffer that stores the compressed data.
GetAnimationIndexByName | Gets the index of an animation, given its name.
GetAnimationNameByIndex | Gets the name of an animation, given its index.
GetCallback | Gets information about a specific callback in the animation set.
GetCallbackKey | Gets information about a specific callback in the animation set.
GetCallbackKeys | Fills an array with callback key data used for key frame animation.
GetName | Gets the animation set name.
GetNumAnimations | Gets the number of animations in the animation set.
GetNumCallbackKeys | Gets the number of callback keys in the animation set.
GetNumRotationKeys | Gets the number of rotation keys in the specified key frame animation.
GetNumScaleKeys | Gets the number of scale keys in the specified key frame animation.
GetNumTranslationKeys | Gets the number of translation keys in the specified key frame animation.
GetPeriod | Gets the period of the animation set.
GetPeriodicPosition | Returns time position in the local timeframe of an animation set.
GetPlaybackType | Gets the type of the animation set playback loop.
GetRotationKey | Get rotation information for a specific key frame in the animation set.
GetRotationKeys | Fills an array with rotational key data used for key frame animation.
GetScaleKey | Get scale information for a specific key frame in the animation set.
GetScaleKeys | Fills an array with scale key data used for key frame animation.
GetSourceTicksPerSecond | Gets the number of animation key frame ticks that occur per second.
GetSRT | Gets the scale, rotation, and translation values of the animation set.
GetTranslationKey | Get translation information for a specific key frame in the animation set.
GetTranslationKeys | Fills an array with translational key data used for key frame animation.
RegisterAnimationSRTKeys | Register the scale, rotate, and translate (SRT) key frame data for an animation.
SetCallbackKey | Sets information about a specific callback in the animation set.
SetRotationKey | Set rotation information for a specific key frame in the animation set.
SetScaleKey | Set scale information for a specific key frame in the animation set.
SetTranslationKey | Set translation information for a specific key frame in the animation set.
UnregisterAnimation | Remove the animation data from the animation set.
UnregisterRotationKey | Removes the rotation data at the specified key frame.
UnregisterScaleKey | Removes the scale data at the specified key frame.
UnregisterTranslationKey | Removes the translation data at the specified key frame.

Remarks

Create a keyframed animation set with D3DXCreateKeyframedAnimationSet.

The LPD3DXKEYFRAMEDANIMATIONSET type is defined as a pointer to this interface.

typedef interface ID3DXKeyframedAnimationSet ID3DXKeyframedAnimationSet;
typedef interface ID3DXKeyframedAnimationSet *LPD3DXKEYFRAMEDANIMATIONSET;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | ID3DXAnimationSet
Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXKeyframedAnimationSet::Compress Method

Transforms animations in an animation set into a compressed format and returns a pointer to the buffer that stores the compressed data.

Syntax

HRESULT Compress(

    DWORD Flags,
    FLOAT Lossiness,
    LPD3DXFRAME pHierarchy,
    LPD3DXBUFFER *ppCompressedData
);

Parameters

Flags
[in] One of the D3DXCOMPRESSION_FLAGS values that define the compression mode used for storing compressed animation set data. D3DXCOMPRESS_DEFAULT is the only value currently supported.
Lossiness
[in] Desired compression loss ratio, in the range from 0 to 1.
pHierarchy
[in] Pointer to a D3DXFRAME transformation frame hierarchy. Can be NULL.
ppCompressedData
[out] Address of a pointer to the ID3DXBuffer compressed animation set.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXKeyframedAnimationSet::GetCallbackKey Method

Gets information about a specific callback in the animation set.

Syntax

HRESULT GetCallbackKey(

    UINT Animation,
    LPD3DXKEY_CALLBACK pCallbackKeys
);

Parameters

Animation
[in] Animation index.
pCallbackKeys
[out] Pointer to the callback function.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXKeyframedAnimationSet::GetCallbackKeys Method

Fills an array with callback key data used for key frame animation.

Syntax

HRESULT GetCallbackKeys(

    LPD3DXKEY_CALLBACK pCallbackKeys
);

Parameters

pCallbackKeys
[out] Pointer to a user-allocated array of D3DXKEY_CALLBACK structures that the method is to fill with callback data.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

See Also

ID3DXKeyframedAnimationSet::GetNumCallbackKeys


ID3DXKeyframedAnimationSet::GetNumCallbackKeys Method

Gets the number of callback keys in the animation set.

Syntax

UINT GetNumCallbackKeys(VOID);

Return Value

Number of callback keys in the animation set.


ID3DXKeyframedAnimationSet::GetNumRotationKeys Method

Gets the number of rotation keys in the specified key frame animation.

Syntax

UINT GetNumRotationKeys(

    UINT Animation
);

Parameters

Animation
[in] Animation index.

Return Value

Number of rotation keys in the specified key frame animation.


ID3DXKeyframedAnimationSet::GetNumScaleKeys Method

Gets the number of scale keys in the specified key frame animation.

Syntax

UINT GetNumScaleKeys(

    UINT Animation
);

Parameters

Animation
[in] Animation index.

Return Value

Number of scale keys in the specified key frame animation.


ID3DXKeyframedAnimationSet::GetNumTranslationKeys Method

Gets the number of translation keys in the specified key frame animation.

Syntax

UINT GetNumTranslationKeys(

    UINT Animation
);

Parameters

Animation
[in] Animation index.

Return Value

Number of translation keys in the specified key frame animation.


ID3DXKeyframedAnimationSet::GetPlaybackType Method

Gets the type of the animation set playback loop.

Syntax

D3DXPLAYBACK_TYPE GetPlaybackType(VOID);

Return Value

Type of the animation set playback loop. See D3DXPLAYBACK_TYPE.


ID3DXKeyframedAnimationSet::GetRotationKey Method

Get rotation information for a specific key frame in the animation set.

Syntax

HRESULT GetRotationKey(

    UINT Animation,
    UINT Key,
    LPD3DXKEY_QUATERNION pRotationKeys
);

Parameters

Animation
[in] Animation index.
Key
[in] Key frame.
pRotationKeys
[in] Pointer to the rotation data. See D3DXKEY_QUATERNION.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXKeyframedAnimationSet::GetRotationKeys Method

Fills an array with rotational key data used for key frame animation.

Syntax

HRESULT GetRotationKeys(

    UINT Animation,
    LPD3DXKEY_QUATERNION pRotationKeys
);

Parameters

Animation
[in] Animation index.
pRotationKeys
[in] Pointer to a user-allocated array of D3DXKEY_QUATERNION quaternions that the method is to fill with animation rotation data.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

See Also

ID3DXKeyframedAnimationSet::GetNumRotationKeys


ID3DXKeyframedAnimationSet::GetScaleKey Method

Get scale information for a specific key frame in the animation set.

Syntax

HRESULT GetScaleKey(

    UINT Animation,
    UINT Key,
    LPD3DXKEY_VECTOR3 pScaleKeys
);

Parameters

Animation
[in] Animation index.
Key
[in] Key frame.
pScaleKeys
[in] Pointer to the scale data. See D3DXKEY_VECTOR3.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXKeyframedAnimationSet::GetScaleKeys Method

Fills an array with scale key data used for key frame animation.

Syntax

HRESULT GetScaleKeys(

    UINT Animation,
    LPD3DXKEY_VECTOR3 pScaleKeys
);

Parameters

Animation
[in] Animation index.
pScaleKeys
[in] Pointer to a user-allocated array of D3DXKEY_VECTOR3 vectors that the method is to fill with animation scale data.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

See Also

ID3DXKeyframedAnimationSet::GetNumScaleKeys


ID3DXKeyframedAnimationSet::GetSourceTicksPerSecond Method

Gets the number of animation key frame ticks that occur per second.

Syntax

DOUBLE GetSourceTicksPerSecond(VOID);

Return Value

Number of animation key frame ticks that occur per second.


ID3DXKeyframedAnimationSet::GetTranslationKey Method

Get translation information for a specific key frame in the animation set.

Syntax

HRESULT GetTranslationKey(

    UINT Animation,
    UINT Key,
    LPD3DXKEY_VECTOR3 pTranslationKey
);

Parameters

Animation
[in] Animation index.
Key
[in] Key Frame.
pTranslationKey
[out] Pointer to the rotation information. See D3DXKEY_VECTOR3.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXKeyframedAnimationSet::GetTranslationKeys Method

Fills an array with translational key data used for key frame animation.

Syntax

HRESULT GetTranslationKeys(

    UINT Animation,
    LPD3DXKEY_VECTOR3 pTranslationKeys
);

Parameters

Animation
[in] Animation index.
pTranslationKeys
[in] Pointer to a user-allocated array of D3DXKEY_VECTOR3 vectors that the method is to fill with animation translation data.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

See Also

ID3DXKeyframedAnimationSet::GetNumTranslationKeys


ID3DXKeyframedAnimationSet::RegisterAnimationSRTKeys Method

Register the scale, rotate, and translate (SRT) key frame data for an animation.

Syntax

HRESULT RegisterAnimationSRTKeys(

    LPCSTR pName,
    UINT NumScaleKeys,
    UINT NumRotationKeys,
    UINT NumTranslationKeys,
    CONST LPD3DXKEY_VECTOR3 *pScaleKeys,
    CONST LPD3DXKEY_QUATERNION *pRotationKeys,
    CONST LPD3DXKEY_VECTOR3 *pTranslationKeys,
    DWORD *pAnimationIndex
);

Parameters

pName
[in] Pointer to the animation name.
NumScaleKeys
[in] Number of scale keys.
NumRotationKeys
[in] Number of rotation keys.
NumTranslationKeys
[in] Number of translation keys.
pScaleKeys
[in] Address of a pointer to a user-allocated array of D3DXKEY_VECTOR3 vectors that the method fills with scale data.
pRotationKeys
[in] Address of a pointer to a user-allocated array of D3DXKEY_QUATERNION quaternions that the method fills with rotation data.
pTranslationKeys
[in] Address of a pointer to a user-allocated array of D3DXKEY_VECTOR3 vectors that the method fills with translation data.
pAnimationIndex
[out] Returns the animation index.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned:

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

See Also

ID3DXKeyframedAnimationSet::GetNumScaleKeys, ID3DXKeyframedAnimationSet::GetNumRotationKeys, ID3DXKeyframedAnimationSet::GetNumTranslationKeys


ID3DXKeyframedAnimationSet::SetCallbackKey Method

Sets information about a specific callback in the animation set.

Syntax

HRESULT SetCallbackKey(

    UINT Animation,
    LPD3DXKEY_CALLBACK pCallbackKeys
);

Parameters

Animation
[in] Animation index.
pCallbackKeys
[out] Pointer to the callback function.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXKeyframedAnimationSet::SetRotationKey Method

Set rotation information for a specific key frame in the animation set.

Syntax

HRESULT SetRotationKey(

    UINT Animation,
    UINT Key,
    LPD3DXKEY_QUATERNION pRotationKeys
);

Parameters

Animation
[in] Animation index.
Key
[in] Key frame.
pRotationKeys
[in] Pointer to the rotation data. See D3DXKEY_VECTOR3.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXKeyframedAnimationSet::SetScaleKey Method

Set scale information for a specific key frame in the animation set.

Syntax

HRESULT SetScaleKey(

    UINT Animation,
    UINT Key,
    LPD3DXKEY_VECTOR3 pScaleKeys
);

Parameters

Animation
[in] Animation index.
Key
[in] Key frame.
pScaleKeys
[in] Pointer to the scale data. See D3DXKEY_VECTOR3.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXKeyframedAnimationSet::SetTranslationKey Method

Set translation information for a specific key frame in the animation set.

Syntax

HRESULT SetTranslationKey(

    UINT Animation,
    UINT Key,
    LPD3DXKEY_VECTOR3 pTranslationKey
);

Parameters

Animation
[in] Animation index.
Key
[in] Key Frame.
pTranslationKey
[in] Pointer to the translation data. See D3DXKEY_VECTOR3.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXKeyframedAnimationSet::UnregisterAnimation Method

Remove the animation data from the animation set.

Syntax

HRESULT UnregisterAnimation(

    UINT Index
);

Parameters

Index
[in] The animation index.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXKeyframedAnimationSet::UnregisterRotationKey Method

Removes the rotation data at the specified key frame.

Syntax

HRESULT UnregisterRotationKey(

    UINT Animation,
    UINT Key
);

Parameters

Animation
[in] Animation identifier.
Key
[in] Key frame.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This method is slow and should not be used after an animation has begun to play.


ID3DXKeyframedAnimationSet::UnregisterScaleKey Method

Removes the scale data at the specified key frame.

Syntax

HRESULT UnregisterScaleKey(

    UINT Animation,
    UINT Key
);

Parameters

Animation
[in] Animation identifier.
Key
[in] Key frame.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This method is slow and should not be used after an animation has begun to play.


ID3DXKeyframedAnimationSet::UnregisterTranslationKey Method

Removes the translation data at the specified key frame.

Syntax

HRESULT UnregisterTranslationKey(

    UINT Animation,
    UINT Key
);

Parameters

Animation
[in] Animation identifier.
Key
[in] Key frame.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This method is slow and should not be used after an animation has begun to play.


ID3DXLine Interface

The ID3DXLine interface implements line drawing using textured triangles.

ID3DXLine Members

Begin | Prepares a device for drawing lines.
Draw | Draws a line strip in screen space. Input is in the form of an array that defines points (of D3DXVECTOR2) on the line strip.
DrawTransform | Draws a line strip in screen space with a specified input transformation matrix.
End | Restores the device state to how it was when ID3DXLine::Begin was called.
GetAntialias | Gets the line antialiasing state.
GetDevice | Retrieves the Microsoft Direct3D device associated with the line object.
GetGLLines | Gets the OpenGL-style line-drawing mode.
GetPattern | Gets the line stipple pattern.
GetPatternScale | Gets the stipple-pattern scale value.
GetWidth | Gets the thickness of the line.
OnLostDevice | Releases all references to video memory resources and deletes all state blocks.
OnResetDevice | Should be called after the device has been reset.
SetAntialias | Toggles line antialiasing.
SetGLLines | Toggles the mode to draw OpenGL-style lines.
SetPattern | Applies a stipple pattern to the line.
SetPatternScale | Stretches the stipple pattern along the line direction.
SetWidth | Specifies the thickness of the line.

Remarks

Create a line drawing object with D3DXCreateLine.

The LPD3DXLINE type is defined as a pointer to the ID3DXLine interface.

typedef interface ID3DXLine ID3DXLine;
typedef interface ID3DXLine *LPD3DXLINE;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXLine::Begin Method

Prepares a device for drawing lines.

Syntax

HRESULT Begin(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

Calling Begin is optional. If called outside of a Begin ... ID3DXLine::End sequence, the draw functions will internally call Begin and End. To avoid extra overhead, this method should be used if more than one draw function will be called successively.

This method must be called from inside an IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene sequence.

Begin cannot be used as a substitute for either IDirect3DDevice9::BeginScene or ID3DXRenderToSurface::BeginScene.


ID3DXLine::Draw Method

Draws a line strip in screen space. Input is in the form of an array that defines points (of D3DXVECTOR2) on the line strip.

Syntax

HRESULT Draw(

    CONST D3DXVECTOR2* pVertexList,
    DWORD dwVertexListCount,
    D3DCOLOR Color
);

Parameters

pVertexList
[in] Array of vertices that make up the line. See D3DXVECTOR2.
dwVertexListCount
[in] Number of vertices in the vertex list.
Color
[in] Color of the line. See D3DCOLOR.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.


ID3DXLine::DrawTransform Method

Draws a line strip in screen space with a specified input transformation matrix.

Syntax

HRESULT DrawTransform(

    CONST D3DXVECTOR3* pVertexList,
    DWORD dwVertexListCount,
    CONST D3DXMATRIX* pTransform,
    D3DCOLOR Color
);

Parameters

pVertexList
[in] Array of vertices that make up the line. See D3DXVECTOR3.
dwVertexListCount
[in] Number of vertices in the vertex list.
pTransform
[in] A scale, rotate, and translate (SRT) matrix for transforming the points. See D3DXMATRIX. If this matrix is a projection matrix, any stippled lines will be drawn with a perspective-correct stippling pattern. Or, you can transform the vertices and use ID3DXLine::Draw to draw the line with a nonperspective-correct stipple pattern.
Color
[in] Color of the line. See D3DCOLOR.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.


ID3DXLine::End Method

Restores the device state to how it was when ID3DXLine::Begin was called.

Syntax

HRESULT End(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

ID3DXLine::End cannot be used as a substitute for either IDirect3DDevice9::EndScene or ID3DXRenderToSurface::EndScene.

See Also

ID3DXLine::Begin


ID3DXLine::GetAntialias Method

Gets the line antialiasing state.

Syntax

BOOL GetAntialias(VOID);

Return Value

Returns the antialiasing switch value. TRUE means antialiasing is on, and FALSE means antialiasing is off.


ID3DXLine::GetDevice Method

Retrieves the Microsoft Direct3D device associated with the line object.

Syntax

HRESULT GetDevice(

    LPDIRECT3DDEVICE9 *ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface, representing the Direct3D device object associated with the line object.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.


ID3DXLine::GetGLLines Method

Gets the OpenGL-style line-drawing mode.

Syntax

BOOL GetGLLines(VOID);

Return Value

Returns TRUE if OpenGL-style lines are enabled, and FALSE if Microsoft Direct3D-style lines are enabled.

See Also

ID3DXLine::SetGLLines


ID3DXLine::GetPattern Method

Gets the line stipple pattern.

Syntax

DWORD GetPattern(VOID);

Return Value

Returns the line stipple pattern: 1 is opaque, 0 is transparent.

See Also

ID3DXLine::SetPattern


ID3DXLine::GetPatternScale Method

Gets the stipple-pattern scale value.

Syntax

FLOAT GetPatternScale(VOID);

Return Value

Returns the value used to scale the stipple-pattern. 1.0f is the default value and represents no scaling. A value less than 1.0f shrinks the pattern, and a value greater than 1.0 stretches the pattern.

See Also

ID3DXLine::SetPatternScale


ID3DXLine::GetWidth Method

Gets the thickness of the line.

Syntax

FLOAT GetWidth(VOID);

Return Value

The line thickness.

See Also

ID3DXLine::SetWidth


ID3DXLine::OnLostDevice Method

Releases all references to video memory resources and deletes all state blocks.

Syntax

HRESULT OnLostDevice(VOID);

Return Value

This method returns S_OK.

Remarks

This method should be called whenever the device is lost. Before this object can be used again, the device must be reset and the ID3DXLine::OnResetDevice method called.


ID3DXLine::OnResetDevice Method

Should be called after the device has been reset.

Syntax

HRESULT OnResetDevice(VOID);

Return Value

This method returns S_OK.

Remarks

This method should be called after the device has been reset, before any other methods are called.


ID3DXLine::SetAntialias Method

Toggles line antialiasing.

Syntax

HRESULT SetAntialias(

    BOOL bAntiAlias
);

Parameters

bAntiAlias
[in] Toggles antialiasing on and off. TRUE turns antialiasing on, and FALSE turns antialiasing off.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

See Also

ID3DXLine::GetAntialias


ID3DXLine::SetGLLines Method

Toggles the mode to draw OpenGL-style lines.

Syntax

HRESULT SetGLLines(

    BOOL bGLLines
);

Parameters

bGLLines
[in] Toggles OpenGL-style line drawing. TRUE enables OpenGL-style lines, and FALSE enables Microsoft Direct3D-style lines.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.


ID3DXLine::SetPattern Method

Applies a stipple pattern to the line.

Syntax

HRESULT SetPattern(

    DWORD dwPattern
);

Parameters

dwPattern
[in] Describes the stipple pattern: 1 is opaque, 0 is transparent.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.


ID3DXLine::SetPatternScale Method

Stretches the stipple pattern along the line direction.

Syntax

HRESULT SetPatternScale(

    FLOAT fPatternScale
);

Parameters

fPatternScale
[in] Stipple pattern scaling value. 1.0f is the default value and represents no scaling. A value less than 1.0f shrinks the pattern, and a value greater than 1.0 stretches the pattern.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.


ID3DXLine::SetWidth Method

Specifies the thickness of the line.

Syntax

HRESULT SetWidth(

    FLOAT fWidth
);

Parameters

fWidth
[in] Describes the line width.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.


ID3DXLoadUserData Interface

This interface is implemented by the application to save any additional user data embedded in .x files. An instance of this interface is passed to D3DXLoadMeshHierarchyFromX, and D3DX calls the appropriate method on this interface every time the appropriate data is encountered. For example, for each frame object in the .x file, ID3DXLoadUserData::LoadFrameChildData is called and passed the child data.

ID3DXLoadUserData Members

LoadFrameChildData | Load frame child data from a .x file.
LoadMeshChildData | Load mesh child data from a .x file.
LoadTopLevelData | Load top level data from a .x file.

Remarks

The LPD3DXLOADUSERDATA type is defined as a pointer to this interface.

typedef interface ID3DXLoadUserData ID3DXLoadUserData;
typedef interface ID3DXLoadUserData *LPD3DXLOADUSERDATA;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | Nothing
Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXLoadUserData::LoadFrameChildData Method

Load frame child data from a .x file.

Syntax

HRESULT LoadFrameChildData(

    LPD3DXFRAME pFrame,
    LPD3DXFILEDATA pXofChildData
);

Parameters

pFrame
[in] Pointer to a mesh container. See D3DXFRAME.
pXofChildData
[in] Pointer to a .x file data structure. This is defined in Dxfile.h.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.


ID3DXLoadUserData::LoadMeshChildData Method

Load mesh child data from a .x file.

Syntax

HRESULT LoadMeshChildData(

    LPD3DXMESHCONTAINER pMeshContainer,
    LPD3DXFILEDATA pXofChildData
);

Parameters

pMeshContainer
[in] Pointer to a mesh container. See D3DXMESHCONTAINER.
pXofChildData
[in] Pointer to a .x file data structure. This is defined in Dxfile.h.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.


ID3DXLoadUserData::LoadTopLevelData Method

Load top level data from a .x file.

Syntax

HRESULT LoadTopLevelData(

    LPD3DXFILEDATA pXofChildData
);

Parameters

pXofChildData
[in] Pointer to a .x file data structure. This is defined in Dxfile.h.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.


ID3DXMatrixStack Interface

Applications use the methods of the ID3DXMatrixStack interface to manipulate a matrix stack.

ID3DXMatrixStack Members

GetTop | Retrieves the current matrix at the top of the stack.
LoadIdentity | Loads identity in the current matrix.
LoadMatrix | Loads the given matrix into the current matrix.
MultMatrix | Determines the product of the current matrix and the given matrix.
MultMatrixLocal | Determines the product of the given matrix and the current matrix.
Pop | Removes the current matrix from the top of the stack.
Push | Adds a matrix to the stack.
RotateAxis | Rotates (relative to world coordinate space) around an arbitrary axis.
RotateAxisLocal | Rotates (relative to the object's local coordinate space) around an arbitrary axis.
RotateYawPitchRoll | Rotates (relative to world coordinate space) around an arbitrary axis.
RotateYawPitchRollLocal | Rotates (relative to the object's local coordinate space) around an arbitrary axis.
Scale | Scale the current matrix about the world coordinate origin.
ScaleLocal | Scale the current matrix about the object origin.
Translate | Determines the product of the current matrix and the computed translation matrix determined by the given factors (x, y, and z).
TranslateLocal | Determines the product of the computed translation matrix determined by the given factors (x, y, and z) and the current matrix.

Remarks

The ID3DXMatrixStack interface is obtained by calling the D3DXCreateMatrixStack function.

The LPD3DXMATRIXSTACK type is defined as a pointer to the ID3DXMatrixStack interface.

typedef interface ID3DXMatrixStack ID3DXMatrixStack;
typedef interface ID3DXMatrixStack *LPD3DXMATRIXSTACK;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXMatrixStack::GetTop Method

Retrieves the current matrix at the top of the stack.

Syntax

D3DXMATRIX *GetTop(VOID);

Return Value

This method returns a pointer to a D3DXMATRIX structure representing the current matrix.

Remarks

The D3DXMATRIX pointer returned by this method is not guaranteed to be valid after subsequent stack operations.

Note that this method does not remove the current matrix from the top of the stack; rather, it just returns the current matrix.

See Also

ID3DXMatrixStack::Pop, ID3DXMatrixStack::Push


ID3DXMatrixStack::LoadIdentity Method

Loads identity in the current matrix.

Syntax

HRESULT LoadIdentity(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The identity matrix is a matrix in which all coefficients are 0.0 except the [1,1][2,2][3,3][4,4] coefficients, which are set to 1.0. The identity matrix is special in that when it is applied to vertices, they are unchanged. The identity matrix is used as the starting point for matrices that will modify vertex values to create rotations, translations, and any other transformations that can be represented by a 4×4 matrix.

See Also

ID3DXMatrixStack::LoadMatrix


ID3DXMatrixStack::LoadMatrix Method

Loads the given matrix into the current matrix.

Syntax

HRESULT LoadMatrix(

    CONST D3DXMATRIX *pMat
);

Parameters

pMat
[in] Pointer to the D3DXMATRIX structure loaded into the current matrix.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Note that this method does not add an item to the stack; rather, it replaces the current matrix with the supplied matrix.

See Also

ID3DXMatrixStack::LoadIdentity


ID3DXMatrixStack::MultMatrix Method

Determines the product of the current matrix and the given matrix.

Syntax

HRESULT MultMatrix(

    CONST D3DXMATRIX *pMat
);

Parameters

pMat
[in] Pointer to the D3DXMATRIX structure to be multiplied with the current matrix.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method right-multiplies the given matrix to the current matrix (transformation is about the current world origin).

m_pstack[m_currentPos] = m_pstack[m_currentPos] * (*pMat);

This method does not add an item to the stack, it replaces the current matrix with the product of the current matrix and the given matrix.

See Also

ID3DXMatrixStack::MultMatrixLocal


ID3DXMatrixStack::MultMatrixLocal Method

Determines the product of the given matrix and the current matrix.

Syntax

HRESULT MultMatrixLocal(

    CONST D3DXMATRIX *pMat
);

Parameters

pMat
[in] Pointer to the D3DXMATRIX structure to be multiplied with the current matrix.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method left-multiplies the given matrix to the current matrix (transformation is about the local origin of the object).

m_pstack[m_currentPos] = (*pMat) * m_pstack[m_currentPos];

This method does not add an item to the stack, it replaces the current matrix with the product of the given matrix and the current matrix.

See Also

ID3DXMatrixStack::MultMatrix


ID3DXMatrixStack::Pop Method

Removes the current matrix from the top of the stack.

Syntax

HRESULT Pop(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

Remarks

Note that this method decrements the count of items on the stack by 1, effectively removing the current matrix from the top of the stack and promoting a matrix to the top of the stack. If the current count of items on the stack is 0, then this method returns without performing any action. If the current count of items on the stack is 1, then this method empties the stack.

See Also

ID3DXMatrixStack::GetTop, ID3DXMatrixStack::Push


ID3DXMatrixStack::Push Method

Adds a matrix to the stack.

Syntax

HRESULT Push(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method increments the count of items on the stack by 1, duplicating the current matrix. The stack will grow dynamically as more items are added.

See Also

ID3DXMatrixStack::GetTop, ID3DXMatrixStack::Pop


ID3DXMatrixStack::RotateAxis Method

Rotates (relative to world coordinate space) around an arbitrary axis.

Syntax

HRESULT RotateAxis(

    CONST D3DXVECTOR3 *pV,
    FLOAT Angle
);

Parameters

pV
[in] Pointer to the arbitrary axis of rotation. See D3DXVECTOR3.
Angle
[in] Rotation angle about the arbitrary axis, in radians. Angles are measured counterclockwise when looking along the arbitrary axis toward the origin.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method adds the rotation to the matrix stack with the computed rotation matrix similar to the following:
D3DXMATRIX tmp;
D3DXMatrixRotationAxis( &tmp, pV, angle );
m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;

Because the rotation is right-multiplied to the matrix stack, the rotation is relative to world coordinate space.

See Also

D3DXMatrixRotationAxis, ID3DXMatrixStack::RotateAxisLocal, ID3DXMatrixStack::RotateYawPitchRoll, ID3DXMatrixStack::RotateYawPitchRollLocal


ID3DXMatrixStack::RotateAxisLocal Method

Rotates (relative to the object's local coordinate space) around an arbitrary axis.

Syntax

HRESULT RotateAxisLocal(

    CONST D3DXVECTOR3 *pV,
    FLOAT Angle
);

Parameters

pV
[in] Pointer to the arbitrary axis of rotation. See D3DXVECTOR3.
Angle
[in] Rotation angle about the arbitrary axis, in radians. Angles are measured counterclockwise when looking along the arbitrary axis toward the origin.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method adds the rotation to the matrix stack with the computed rotation matrix similar to the following:
D3DXMATRIX tmp;
D3DXMatrixRotationAxis( &tmp, pV, angle );
m_stack[m_currentPos] = tmp * m_stack[m_currentPos];

Because the rotation is left-multiplied to the matrix stack, the rotation is relative to the object's local coordinate space.

See Also

D3DXMatrixRotationAxis, ID3DXMatrixStack::RotateAxis, ID3DXMatrixStack::RotateYawPitchRoll, ID3DXMatrixStack::RotateYawPitchRollLocal


ID3DXMatrixStack::RotateYawPitchRoll Method

Rotates (relative to world coordinate space) around an arbitrary axis.

Syntax

HRESULT RotateYawPitchRoll(

    FLOAT Yaw,
    FLOAT Pitch,
    FLOAT Roll
);

Parameters

Yaw
[in] The yaw around the y-axis in radians.
Pitch
[in] The pitch around the x-axis in radians.
Roll
[in] The roll around the z-axis in radians.

Return Value

If the method succeeds, the return value is D3D_OK.

Remarks

This method adds the rotation to the matrix stack with the computed rotation matrix similar to the following:
D3DXMATRIX tmp;
D3DXMatrixRotationYawPitchRoll( &tmp, yaw, pitch, roll );
m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;

Because the rotation is right-multiplied to the matrix stack, the rotation is relative to world coordinate space.

See Also

D3DXMatrixRotationAxis, ID3DXMatrixStack::RotateAxis, ID3DXMatrixStack::RotateAxisLocal, ID3DXMatrixStack::RotateYawPitchRollLocal


ID3DXMatrixStack::RotateYawPitchRollLocal Method

Rotates (relative to the object's local coordinate space) around an arbitrary axis.

Syntax

HRESULT RotateYawPitchRollLocal(

    FLOAT Yaw,
    FLOAT Pitch,
    FLOAT Roll
);

Parameters

Yaw
[in] The yaw around the y-axis in radians.
Pitch
[in] The pitch around the x-axis in radians.
Roll
[in] The roll around the z-axis in radians.

Return Value

If the method succeeds, the return value is D3D_OK.

Remarks

This method adds the rotation to the matrix stack with the computed rotation matrix similar to the following:
D3DXMATRIX tmp;
D3DXMatrixRotationYawPitchRoll( &tmp, yaw, pitch, roll );
m_stack[m_currentPos] = tmp * m_stack[m_currentPos];

Because the rotation is left-multiplied to the matrix stack, the rotation is relative to the object's local coordinate space.

See Also

D3DXMatrixRotationAxis, ID3DXMatrixStack::RotateAxis, ID3DXMatrixStack::RotateAxisLocal, ID3DXMatrixStack::RotateYawPitchRoll


ID3DXMatrixStack::Scale Method

Scale the current matrix about the world coordinate origin.

Syntax

HRESULT Scale(

    FLOAT x,
    FLOAT y,
    FLOAT z
);

Parameters

x
[in] The scaling component in the x-direction.
y
[in] The scaling component in the y-direction.
z
[in] The scaling component in the z-direction.

Return Value

If the method succeeds, the return value is D3D_OK.

Remarks

This method right-multiplies the current matrix with the computed scale matrix. The transformation is about the current world origin.

D3DXMATRIX tmp;
D3DXMatrixScaling(&tmp, x, y, z);
m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;

See Also

ID3DXMatrixStack::ScaleLocal


ID3DXMatrixStack::ScaleLocal Method

Scale the current matrix about the object origin.

Syntax

HRESULT ScaleLocal(

    FLOAT x,
    FLOAT y,
    FLOAT z
);

Parameters

x
[in] The scaling component in the x-direction.
y
[in] The scaling component in the y-direction.
z
[in] The scaling component in the z-direction.

Return Value

If the method succeeds, the return value is D3D_OK.

Remarks

This method left-multiplies the current matrix with the computed scale matrix. The transformation is about the local origin of the object.

D3DXMATRIX tmp;
D3DXMatrixScaling(&tmp, x, y, z);
m_stack[m_currentPos] = tmp * m_stack[m_currentPos];

See Also

ID3DXMatrixStack::Scale


ID3DXMatrixStack::Translate Method

Determines the product of the current matrix and the computed translation matrix determined by the given factors (x, y, and z).

Syntax

HRESULT Translate(

    FLOAT x,
    FLOAT y,
    FLOAT z
);

Parameters

x
[in] The translation factor in the x-direction.
y
[in] The translation factor in the y-direction.
z
[in] The translation factor in the z-direction.

Return Value

If the method succeeds, the return value is D3D_OK.

Remarks

This method right-multiplies the current matrix with the computed translation matrix (transformation is about the current world origin).

    D3DXMATRIX tmp;
    D3DXMatrixTranslation( &tmp, x, y, z );
    m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;

See Also

ID3DXMatrixStack::TranslateLocal


ID3DXMatrixStack::TranslateLocal Method

Determines the product of the computed translation matrix determined by the given factors (x, y, and z) and the current matrix.

Syntax

HRESULT TranslateLocal(

    FLOAT x,
    FLOAT y,
    FLOAT z
);

Parameters

x
[in] The translation factor in the x-direction.
y
[in] The translation factor in the y-direction.
z
[in] The translation factor in the z-direction.

Return Value

If the method succeeds, the return value is D3D_OK.

Remarks

This method left-multiplies the current matrix with the computed translation matrix (transformation is about the local origin of the object).

    D3DXMATRIX tmp;
    D3DXMatrixTranslation( &tmp, x, y, z );
    m_stack[m_currentPos] = tmp * m_stack[m_currentPos];

See Also

ID3DXMatrixStack::Translate


ID3DXMesh Interface

Applications use the methods of the ID3DXMesh interface to manipulate mesh objects.

ID3DXMesh Members

CloneMesh | Clones a mesh using a declarator.
CloneMeshFVF | Clones a mesh using a flexible vertex format (FVF) code.
ConvertAdjacencyToPointReps | Converts mesh adjacency information to an array of point representatives.
ConvertPointRepsToAdjacency | Converts point representative data to mesh adjacency information.
DrawSubset | Draws a subset of a mesh.
GenerateAdjacency | Generate a list of mesh edges and the faces that share each edge.
GetAttributeTable | Retrieves either an attribute table for a mesh, or the number of entries stored in an attribute table for a mesh.
GetDeclaration | Retrieves a declaration describing the vertices in the mesh.
GetDevice | Retrieves the device associated with the mesh.
GetFVF | Gets the fixed function vertex value.
GetIndexBuffer | Retrieves the data in an index buffer.
GetNumBytesPerVertex | Gets the number of bytes per vertex.
GetNumFaces | Retrieves the number of faces in the mesh.
GetNumVertices | Retrieves the number of vertices in the mesh.
GetOptions | Retrieves the mesh options enabled for this mesh at creation time.
GetVertexBuffer | Retrieves the data in a vertex buffer.
LockAttributeBuffer | Locks the mesh buffer that contains the mesh attribute data, and returns a pointer to it.
LockIndexBuffer | Locks an index buffer and obtains a pointer to the index buffer memory.
LockVertexBuffer | Locks a vertex buffer and obtains a pointer to the vertex buffer memory.
Optimize | Generate a new mesh with reordered faces and vertices to optimize drawing performance.
OptimizeInplace | Generate a mesh with reordered faces and vertices to optimize drawing performance. This method reorders the existing mesh.
SetAttributeTable | Sets the attribute table for a mesh and the number of entries stored in the table.
UnlockAttributeBuffer | Unlocks an attribute buffer.
UnlockIndexBuffer | Unlocks an index buffer.
UnlockVertexBuffer | Unlocks a vertex buffer.
UpdateSemantics | This method allows the user to change the mesh declaration without changing the data layout of the vertex buffer. The call is valid only if the old and new declaration formats have the same vertex size.

Remarks

To obtain the ID3DXMesh interface, call either the D3DXCreateMesh or D3DXCreateMeshFVF function.

This interface inherits additional functionality from the ID3DXBaseMesh interface.

The LPD3DXMESH type is defined as a pointer to the ID3DXMesh interface.

typedef struct ID3DXMesh *LPD3DXMESH;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | ID3DXBaseMesh
Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Mesh Functions


ID3DXMesh::LockAttributeBuffer Method

Locks the mesh buffer that contains the mesh attribute data, and returns a pointer to it.

Syntax

HRESULT LockAttributeBuffer(

    DWORD Flags,
    DWORD **ppData
);

Parameters

Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY

For a description of the flags, see D3DLOCK.

ppData
[out] Address of a pointer to a buffer containing a DWORD for each face in the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If ID3DXMesh::Optimize has been called, the mesh will also have an attribute table that can be accessed using the ID3DXMesh::GetAttributeTable method.

See Also

ID3DXMesh::UnlockAttributeBuffer, ID3DXMesh::GetAttributeTable, ID3DXMesh::SetAttributeTable


ID3DXMesh::Optimize Method

Generate a new mesh with reordered faces and vertices to optimize drawing performance.

Syntax

HRESULT Optimize(

    DWORD Flags,
    CONST DWORD *pAdjacencyIn,
    DWORD *pAdjacencyOut,
    DWORD *pFaceRemap,
    LPD3DXBUFFER *ppVertexRemap,
    LPD3DXMESH *ppOptMesh
);

Parameters

Flags
[in] Specifies the type of optimization to perform. This parameter can be set to a combination of one or more flags from D3DXMESHOPT and D3DXMESH (except D3DXMESH32_BIT, D3DXMESH_IB_WRITEONLY, and D3DXMESH_WRITEONLY).
pAdjacencyIn
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the source mesh. If the edge has no adjacent faces, the value is 0xffffffff. See Remarks.
pAdjacencyOut
[in, out] Pointer to a destination buffer for the face adjacency array of the optimized mesh. The face adjacency is stored as an array of arrays. The innermost array is three indices of adjacent triangles, and the outer array is one set of face adjacency per triangle in the mesh.
pFaceRemap
[in, out] Pointer to a destination buffer containing the new index for each face.
ppVertexRemap
[out] Address of a pointer to an ID3DXBuffer interface; containing the new index for each vertex.
ppOptMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the optimized mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

This method generates a new mesh.

Before running ID3DXMesh::Optimize, an application must generate an adjacency buffer by calling ID3DXMesh::GenerateAdjacency. The adjacency buffer contains adjacency data such as a list of edges and the faces that are adjacent to each other.

This method is very similar to the ID3DXBaseMesh::CloneMesh method, except that it can perform optimization while generating the new clone of the mesh. The output mesh inherits all of the creation parameters of the input mesh.

See Also

ID3DXMesh::OptimizeInplace


ID3DXMesh::OptimizeInplace Method

Generate a mesh with reordered faces and vertices to optimize drawing performance. This method reorders the existing mesh.

Syntax

HRESULT OptimizeInplace(

    DWORD Flags,
    CONST DWORD *pAdjacencyIn,
    DWORD *pAdjacencyOut,
    DWORD *pFaceRemap,
    LPD3DXBUFFER *ppVertexRemap
);

Parameters

Flags
[in] Combination of one or more D3DXMESHOPT flags, specifying the type of optimization to perform.
pAdjacencyIn
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the source mesh. If the edge has no adjacent faces, the value is 0xffffffff.
pAdjacencyOut
[out] Pointer to a destination buffer for the face adjacency array of the optimized mesh. The face adjacency is stored as an array of arrays. The innermost array is three indices of adjacent triangles, and the outer array is one set of face adjacency per triangle in the mesh. If the value supplied for this argument is NULL, adjacency data is not returned.
pFaceRemap
[out] Pointer to a destination buffer containing the new index for each face. If the value supplied for this argument is NULL, face remap data is not returned.
ppVertexRemap
[out] Address of a pointer to an ID3DXBuffer interface containing the new index for each vertex. If the value supplied for this argument is NULL, vertex remap data is not returned.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_CANNOTATTRSORT | Attribute sort (D3DXMESHOPT_ATTRSORT) is not supported as an optimization technique.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

Before running ID3DXMesh::OptimizeInplace, an application must generate an adjacency buffer by calling ID3DXMesh::GenerateAdjacency. The adjacency buffer contains adjacency data such as a list of edges and the faces that are adjacent to each other.

Note This method will fail if the mesh is sharing its vertex buffer with another mesh, unless the D3DXMESHOPT_IGNOREVERTS is set in Flags.

See Also

ID3DXMesh::Optimize


ID3DXMesh::SetAttributeTable Method

Sets the attribute table for a mesh and the number of entries stored in the table.

Syntax

HRESULT SetAttributeTable(

    CONST D3DXATTRIBUTERANGE * pAttribTable,
    DWORD cAttribTableSize
);

Parameters

pAttribTable
[in] Pointer to an array of D3DXATTRIBUTERANGE structures, representing the entries in the mesh attribute table.
cAttribTableSize
[in] Number of attributes in the mesh attribute table.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

If an application keeps track of the information in an attribute table, and rearranges the table as a result of changes to attributes or faces, this method allows the application to update the attribute tables instead of calling ID3DXMesh::Optimize again.

See Also

ID3DXMesh::LockAttributeBuffer, ID3DXMesh::GetAttributeTable


ID3DXMesh::UnlockAttributeBuffer Method

Unlocks an attribute buffer.

Syntax

HRESULT UnlockAttributeBuffer(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXMesh::LockAttributeBuffer


ID3DXPatchMesh Interface

This interface encapsulates patch mesh functionality.

ID3DXPatchMesh Members

CloneMesh | Creates a new patch mesh with the specified vertex declaration.
GenerateAdjacency | Generate a list of mesh edges and the patches that share each edge.
GetControlVerticesPerPatch | Gets the number of control vertices per patch.
GetDeclaration | Gets the vertex declaration.
GetDevice | Gets the device that created the mesh.
GetDisplaceParam | Gets mesh geometry displacement parameters.
GetIndexBuffer | Gets the mesh index buffer.
GetNumPatches | Gets the number of patches in the mesh.
GetNumVertices | Gets the number of vertices in the mesh.
GetOptions | Gets the type of patch.
GetPatchInfo | Gets the attributes of the patch.
GetTessSize | Gets the size of the tessellated mesh, given a tessellation level.
GetVertexBuffer | Gets the mesh vertex buffer.
LockAttributeBuffer | Locks the attribute buffer.
LockIndexBuffer | Lock the index buffer.
LockVertexBuffer | Lock the vertex buffer.
Optimize | Optimizes the patch mesh for efficient tessellation.
SetDisplaceParam | Sets mesh geometry displacement parameters.
Tessellate | Performs uniform tessellation based on the tessellation level.
TessellateAdaptive | Performs adaptive tessellation based on the z-based adaptive tessellation criterion.
UnlockAttributeBuffer | Unlock the attribute buffer.
UnlockIndexBuffer | Unlock the index buffer.
UnlockVertexBuffer | Unlock the vertex buffer.

Remarks

A patch mesh is a mesh that consists of a series of patches.

To obtain the ID3DXPatchMesh interface, call the D3DXCreatePatchMesh function.

The LPD3DXPATCHMESH type is defined as a pointer to the ID3DXPatchMesh interface, as follows:

typedef struct ID3DXPatchMesh *LPD3DXPATCHMESH;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Mesh Functions


ID3DXPatchMesh::CloneMesh Method

Creates a new patch mesh with the specified vertex declaration.

Syntax

HRESULT CloneMesh(

    DWORD Options,
    const D3DVERTEXELEMENT9 *pDecl,
    LPD3DXPATCHMESH *pMesh
);

Parameters

Options
[in] Combination of one or more D3DXMESH flags that specify creation options for the mesh.
pDecl
[in] Array of D3DVERTEXELEMENT9 elements that specify the vertex format for the vertices in the output mesh.
pMesh
[out, retval] Address of a pointer to an ID3DXPatchMesh interface that represents the cloned mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

ID3DXPatchMesh::CloneMesh converts the vertex buffer to the new vertex declaration. Entries in the vertex declaration that are new to the original mesh are set to 0. If the current mesh has adjacency, the new mesh will also have adjacency.


ID3DXPatchMesh::GenerateAdjacency Method

Generate a list of mesh edges and the patches that share each edge.

Syntax

HRESULT GenerateAdjacency(

    FLOAT fTolerance
);

Parameters

fTolerance
[in] Specifies that vertices that differ in position by less than the tolerance should be treated as coincident.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

After an application generates adjacency information for a mesh, the mesh data can be optimized for better drawing performance. This method determines which patches are adjacent (within the provided tolerance). This information is used internally to optimize tessellation.

See Also

ID3DXPatchMesh::Optimize


ID3DXPatchMesh::GetControlVerticesPerPatch Method

Gets the number of control vertices per patch.

Syntax

DWORD GetControlVerticesPerPatch(VOID);

Return Value

The number of control vertices per patch.


ID3DXPatchMesh::GetDeclaration Method

Gets the vertex declaration.

Syntax

HRESULT GetDeclaration(

    LPD3DVERTEXELEMENT9 pDeclaration[MAX_FVF_DECL_SIZE]
);

Parameters

pDeclaration
[out] Array of D3DVERTEXELEMENT9 elements describing the vertex format of the mesh vertices. The dimension of this declarator array is MAX_FVF_DECL_SIZE. The vertex element array ends with the D3DDECL_END macro.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The array of elements includes the D3DDECL_END macro, which ends the declaration.


ID3DXPatchMesh::GetDevice Method

Gets the device that created the mesh.

Syntax

HRESULT GetDevice(

    LPDIRECT3DDEVICE9* ppDevice
);

Parameters

ppDevice
[out] Pointer to the device.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXPatchMesh::GetDisplaceParam Method

Gets mesh geometry displacement parameters.

Syntax

HRESULT GetDisplaceParam(

    LPDIRECT3DBASETEXTURE9* Texture,
    D3DTEXTUREFILTERTYPE* MinFilter,
    D3DTEXTUREFILTERTYPE* MagFilter,
    D3DTEXTUREFILTERTYPE* MipFilter,
    D3DTEXTUREADDRESS* Wrap,
    DWORD* dwLODBias
);

Parameters

Texture
[in] Texture containing the displacement data.
MinFilter
[in] Minification level. For more information, see D3DTEXTUREFILTERTYPE.
MagFilter
[in] Magnification level. For more information, see D3DTEXTUREFILTERTYPE.
MipFilter
[in] Mip filter level. For more information, see D3DTEXTUREFILTERTYPE.
Wrap
[in] Texture address wrap mode. For more information, see D3DTEXTUREADDRESS.
dwLODBias
[in] Level of detail bias value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

Displacement maps can only be 2-D textures. Mipmapping is ignored for nonadaptive tessellation.


ID3DXPatchMesh::GetIndexBuffer Method

Gets the mesh index buffer.

Syntax

HRESULT GetIndexBuffer(

    LPDIRECT3DINDEXBUFFER9 *ppIB
);

Parameters

ppIB
[out, retval] Pointer to the index buffer.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The index buffer contains the vertex ordering in the vertex buffer. The index buffer is used to access the vertex buffer when the mesh is rendered.


ID3DXPatchMesh::GetNumPatches Method

Gets the number of patches in the mesh.

Syntax

DWORD GetNumPatches(VOID);

Return Value

The number of patches.


ID3DXPatchMesh::GetNumVertices Method

Gets the number of vertices in the mesh.

Syntax

DWORD GetNumVertices(VOID);

Return Value

The number of vertices.


ID3DXPatchMesh::GetOptions Method

Gets the type of patch.

Syntax

DWORD GetOptions(VOID);

Return Value

The patch type.

Remarks

For more information about patch types, see D3DXPATCHMESHTYPE.


ID3DXPatchMesh::GetPatchInfo Method

Gets the attributes of the patch.

Syntax

HRESULT GetPatchInfo(

    LPD3DXPATCHINFO PatchInfo
);

Parameters

PatchInfo
[out, retval] Pointer to the structures containing the patch attributes. For more information about patch attributes, see D3DXPATCHINFO.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXPatchMesh::GetTessSize Method

Gets the size of the tessellated mesh, given a tessellation level.

Syntax

HRESULT GetTessSize(

    FLOAT fTessLevel,
    DWORD Adaptive,
    DWORD *NumTriangles,
    DWORD *NumVertices
);

Parameters

fTessLevel
[in] Tessellation level.
Adaptive
[in] Adaptive tessellation. For adaptive tessellation, set this value to TRUE and set fTessLevel to the maximum tessellation value. This will result in the maximum mesh size necessary for adaptive tessellation.
NumTriangles
[out] Pointer to the number of triangles generated by the tessellated mesh.
NumVertices
[out] Pointer to the number of vertices generated by the tessellated mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

This method assumes uniform tessellation.


ID3DXPatchMesh::GetVertexBuffer Method

Gets the mesh vertex buffer.

Syntax

HRESULT GetVertexBuffer(

    LPDIRECT3DVERTEXBUFFER9 *ppVB
);

Parameters

ppVB
[out] Pointer to the vertex buffer.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

This method assumes uniform tessellation.


ID3DXPatchMesh::LockAttributeBuffer Method

Locks the attribute buffer.

Syntax

HRESULT LockAttributeBuffer(

    DWORD flags,
    DWORD **ppData
);

Parameters

flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY

For a description of the flags, see D3DLOCK.

ppData
[out, retval] Address of a pointer to a buffer containing a DWORD for each face in the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The attribute buffer is usually locked, written to, and then unlocked for reading.


ID3DXPatchMesh::LockIndexBuffer Method

Lock the index buffer.

Syntax

HRESULT LockIndexBuffer(

    DWORD flags,
    LPVOID *ppData
);

Parameters

flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY

For a description of the flags, see D3DLOCK.

ppData
[out, retval] VOID* pointer to a memory buffer containing the returned index data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The index buffer is usually locked, written to, and then unlocked for reading. Patch mesh index buffers are 16-bit buffers.

See Also

D3DXCreatePatchMesh


ID3DXPatchMesh::LockVertexBuffer Method

Lock the vertex buffer.

Syntax

HRESULT LockVertexBuffer(

    DWORD flags,
    LPVOID *ppData
);

Parameters

flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY
  • D3DLOCK_NOOVERWRITE

For a description of the flags, see D3DLOCK.

ppData
[out, retval] VOID* pointer to a memory buffer containing the returned vertex data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The vertex buffer is usually locked, written to, and then unlocked for reading.

Patch meshes use 16-bit index buffers.


ID3DXPatchMesh::Optimize Method

Optimizes the patch mesh for efficient tessellation.

Syntax

HRESULT Optimize(

    DWORD Flags
);

Parameters

Flags
[in] Currently unused.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_CANNOTATTRSORT | Attribute sort (D3DXMESHOPT_ATTRSORT) is not supported as an optimization technique.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

After an application generates adjacency information for a mesh, the mesh data can be optimized (reordered) for better drawing performance. This method determines which patches are adjacent (within the provided tolerance).

Adjacency information is also used to optimize tessellation. Generate adjacency information once and tessellate repeatedly by calling ID3DXPatchMesh::Tessellate. The optimization performed is independent of the actual tessellation level used. However, if the mesh vertices are changed, you must regenerate the adjacency information.

See Also

ID3DXPatchMesh::GenerateAdjacency


ID3DXPatchMesh::SetDisplaceParam Method

Sets mesh geometry displacement parameters.

Syntax

HRESULT SetDisplaceParam(

    LPDIRECT3DBASETEXTURE9 Texture,
    D3DTEXTUREFILTERTYPE MinFilter,
    D3DTEXTUREFILTERTYPE MagFilter,
    D3DTEXTUREFILTERTYPE MipFilter,
    D3DTEXTUREADDRESS Wrap,
    DWORD dwLODBias
);

Parameters

Texture
[in] Texture containing the displacement data.
MinFilter
[in] Minification level. For more information, see D3DTEXTUREFILTERTYPE.
MagFilter
[in] Magnification level. For more information, see D3DTEXTUREFILTERTYPE.
MipFilter
[in] Mip filter level. For more information, see D3DTEXTUREFILTERTYPE.
Wrap
[in] Texture address wrap mode. For more information, see D3DTEXTUREADDRESS
dwLODBias
[in] Level of detail bias value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

Displacement maps can only be 2-D textures. Mipmapping is ignored for nonadaptive tessellation.


ID3DXPatchMesh::Tessellate Method

Performs uniform tessellation based on the tessellation level.

Syntax

HRESULT Tessellate(

    FLOAT fTessLevel,
    LPD3DXMESH pMesh
);

Parameters

fTessLevel
[in] Tessellation level. This is the number of vertices introduced between existing vertices. The range of this float parameter is 0 < fTessLevel <= 32.
pMesh
[in] Resulting tessellated mesh. See ID3DXMesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

This function will perform more efficiently if the patch mesh has been optimized using ID3DXPatchMesh::Optimize.


ID3DXPatchMesh::TessellateAdaptive Method

Performs adaptive tessellation based on the z-based adaptive tessellation criterion.

Syntax

HRESULT TessellateAdaptive(

    const D3DXVECTOR4* pTrans,
    DWORD dwMaxTessLevel,
    DWORD dwMinTessLevel,
    LPD3DXMESH pMesh
);

Parameters

pTrans
[in] Specifies a 4-D vector that is dotted with the vertices to get the per-vertex adaptive tessellation amount. Each edge is tessellated to the average value of the tessellation levels for the two vertices it connects.
dwMaxTessLevel
[in] Maximum limit for adaptive tessellation. This is the number of vertices introduced between existing vertices. This integer value can range from 1 to 32, inclusive.
dwMinTessLevel
[in] Minimum limit for adaptive tessellation. This is the number of vertices introduced between existing vertices. This integer value can range from 1 to 32, inclusive.
pMesh
[in] Resulting tessellated mesh. See ID3DXMesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

This function will perform more efficiently if the patch mesh has been optimized using ID3DXPatchMesh::Optimize.


ID3DXPatchMesh::UnlockAttributeBuffer Method

Unlock the attribute buffer.

Syntax

HRESULT UnlockAttributeBuffer(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The attribute buffer is usually locked, written to, and then unlocked for reading.


ID3DXPatchMesh::UnlockIndexBuffer Method

Unlock the index buffer.

Syntax

HRESULT UnlockIndexBuffer(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The index buffer is usually locked, written to, and then unlocked for reading.


ID3DXPatchMesh::UnlockVertexBuffer Method

Unlock the vertex buffer.

Syntax

HRESULT UnlockVertexBuffer(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The vertex buffer is usually locked, written to, and then unlocked for reading.


ID3DXPMesh Interface

Applications use the methods of the ID3DXPMesh interface to manipulate progressive mesh objects. A progressive mesh enables progressive refinement of the mesh object.

ID3DXPMesh Members

CloneMesh | Clones a mesh using a declarator.
CloneMeshFVF | Clones a mesh using a flexible vertex format (FVF) code.
ClonePMesh | Clones a progressive mesh using a declarator.
ClonePMeshFVF | Clones a progressive mesh using a FVF code.
ConvertAdjacencyToPointReps | Converts mesh adjacency information to an array of point representatives.
ConvertPointRepsToAdjacency | Converts point representative data to mesh adjacency information.
DrawSubset | Draws a subset of a mesh.
GenerateAdjacency | Generate a list of mesh edges and the faces that share each edge.
GenerateVertexHistory | Generates an immediate ancestor for each vertex when it is removed by a vertex split. Allows generation of a geomorph.
GetAdjacency | Returns the face adjacency array of the mesh.
GetAttributeTable | Retrieves either an attribute table for a mesh, or the number of entries stored in an attribute table for a mesh.
GetDeclaration | Retrieves a declaration describing the vertices in the mesh.
GetDevice | Retrieves the device associated with the mesh.
GetFVF | Gets the fixed function vertex value.
GetIndexBuffer | Retrieves the data in an index buffer.
GetMaxFaces | Retrieves the maximum number of faces that the progressive mesh supports.
GetMaxVertices | Retrieves the maximum number of vertices that the progressive mesh supports.
GetMinFaces | Retrieves the minimum number of faces that the progressive mesh supports.
GetMinVertices | Retrieves the minimum number of vertices that the progressive mesh supports.
GetNumBytesPerVertex | Gets the number of bytes per vertex.
GetNumFaces | Retrieves the number of faces in the mesh.
GetNumVertices | Retrieves the number of vertices in the mesh.
GetOptions | Retrieves the mesh options enabled for this mesh at creation time.
GetVertexBuffer | Retrieves the data in a vertex buffer.
LockIndexBuffer | Locks an index buffer and obtains a pointer to the index buffer memory.
LockVertexBuffer | Locks a vertex buffer and obtains a pointer to the vertex buffer memory.
Optimize | Generates an output mesh with reordered faces and vertices to optimize performance.
OptimizeBaseLOD | Optimizes the base level of detail (LOD) part of an ID3DXPMesh object.
Save | Saves the progressive mesh to the specified stream object.
SetNumFaces | Sets the current level of detail to as close to the specified number of faces as possible.
SetNumVertices | Sets the current level of detail to as close to the specified number of vertices as possible.
TrimByFaces | Modifies the minimum and maximum LOD of an ID3DXPMesh object.
TrimByVertices | Modifies the minimum and maximum LOD of an ID3DXPMesh object.
UnlockIndexBuffer | Unlocks an index buffer.
UnlockVertexBuffer | Unlocks a vertex buffer.
UpdateSemantics | This method allows the user to change the mesh declaration without changing the data layout of the vertex buffer. The call is valid only if the old and new declaration formats have the same vertex size.

Remarks

To obtain the ID3DXPMesh interface, call the D3DXGeneratePMesh function. Or, create a progressive mesh with D3DXCreatePMeshFromStream.

This interface inherits additional functionality from the ID3DXBaseMesh interface.

The LPD3DXPMESH type is defined as a pointer to the ID3DXPMesh interface, as shown below.

typedef struct ID3DXPMesh *LPD3DXPMESH;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | ID3DXBaseMesh
Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Mesh Functions


ID3DXPMesh::ClonePMesh Method

Clones a progressive mesh using a declarator.

Syntax

HRESULT ClonePMesh(

    DWORD Options,
    CONST D3DVERTEXELEMENT9 *pDeclaration,
    LPDIRECT3DDEVICE9 pD3DDevice,
    LpD3DDeviceXPMESH *ppCloneMesh
);

Parameters

Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
pDeclaration
[in] Array of D3DVERTEXELEMENT9 elements describing the vertex format for the returned mesh. This parameter must map directly to an flexible vertex format (FVF).
pD3DDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device object associated with the mesh.
ppCloneMesh
[out] Address of a pointer to an ID3DXPMesh interface, representing the cloned progressive mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

See Also

ID3DXBaseMesh::GetDeclaration, D3DXDeclaratorFromFVF


ID3DXPMesh::ClonePMeshFVF Method

Clones a progressive mesh using a flexible vertex format (FVF) code.

Syntax

HRESULT ClonePMeshFVF(

    DWORD Options,
    DWORD FVF,
    LPDIRECT3DDEVICE9 pD3DDevice,
    LPD3DXPMESH *ppCloneMesh
);

Parameters

Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
FVF
[in] Combination of FVF codes, specifying the vertex format for the vertices in the output mesh. For the values of the codes, see D3DFVF.
pD3DDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device object associated with the mesh.
ppCloneMesh
[out] Address of a pointer to an ID3DXPMesh interface, representing the cloned progressive mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

ID3DXPMesh::ClonePMeshFVF can be used to convert a progressive mesh from one FVF to another.

See Also

ID3DXBaseMesh::GetFVF, D3DXFVFFromDeclarator


ID3DXPMesh::GenerateVertexHistory Method

Generates an immediate ancestor for each vertex when it is removed by a vertex split. Allows generation of a geomorph.

Syntax

HRESULT GenerateVertexHistory(

    DWORD *pVertexHistory
);

Parameters

pVertexHistory
[in] Pointer to an array of parent vertices that were used to form the current vertex. Cannot be NULL.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The vertex buffer must be equal to or greater than the maximum number of vertices in the progressive mesh.


ID3DXPMesh::GetAdjacency Method

Returns the face adjacency array of the mesh.

Syntax

HRESULT GetAdjacency(

    DWORD *pAdjacency
);

Parameters

pAdjacency
[out] Pointer to the returned face adjacency array of the mesh. The face adjacency is stored as an array of arrays. The innermost array is three indices of adjacent triangles, and the outer array is one set of face adjacency per triangle in the mesh. If the edge has no adjacent faces, the value is 0xffffffff. The size of the adjacency array is the maximum number of faces multiplied by 3.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXPMesh::GetMaxFaces


ID3DXPMesh::GetMaxFaces Method

Retrieves the maximum number of faces that the progressive mesh supports.

Syntax

DWORD GetMaxFaces(VOID);

Return Value

Returns the maximum number of faces supported by the progressive mesh.


ID3DXPMesh::GetMaxVertices Method

Retrieves the maximum number of vertices that the progressive mesh supports.

Syntax

DWORD GetMaxVertices(VOID);

Return Value

Returns the maximum number of vertices supported by the progressive mesh.


ID3DXPMesh::GetMinFaces Method

Retrieves the minimum number of faces that the progressive mesh supports.

Syntax

DWORD GetMinFaces(VOID);

Return Value

Returns the minimum number of faces supported by the progressive mesh.


ID3DXPMesh::GetMinVertices Method

Retrieves the minimum number of vertices that the progressive mesh supports.

Syntax

DWORD GetMinVertices(VOID);

Return Value

Returns the minimum number of vertices supported by the progressive mesh.


ID3DXPMesh::Optimize Method

Generates an output mesh with reordered faces and vertices to optimize performance.

Syntax

HRESULT Optimize(

    DWORD Flags,
    DWORD *pAdjacencyOut,
    DWORD *pFaceRemap,
    LPD3DXBUFFER *ppVertexRemap,
    LPD3DXMESH *ppOptMesh
);

Parameters

Flags
[in] Specifies the type of optimization to perform. This parameter can be set to a combination of one or more flags from D3DXMESHOPT and D3DXMESH (except D3DXMESH32_BIT, D3DXMESH_IB_WRITEONLY, and D3DXMESH_WRITEONLY).
pAdjacencyOut
[out] Pointer to a destination buffer for the face adjacency array of the optimized mesh. The face adjacency is stored as an array of arrays. The innermost array is three indices of adjacent triangles, and the outer array is one set of face adjacency per triangle in the mesh. The size of this array is the maximum number of faces multiplied by 3.
pFaceRemap
[out] Pointer to a destination buffer containing the new index for each face.
ppVertexRemap
[out] Address of a pointer to an ID3DXBuffer interface; containing the new index for each vertex.
ppOptMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the optimized mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

After an application generates adjacency information for a mesh, the mesh data can be optimized (reordered) for better drawing performance. This method determines which patches are adjacent (within the provided tolerance).

See Also

ID3DXPMesh::GenerateAdjacency, ID3DXPMesh::OptimizeBaseLOD


ID3DXPMesh::OptimizeBaseLOD Method

Optimizes the base level of detail (LOD) part of an ID3DXPMesh object.

Syntax

HRESULT OptimizeBaseLOD(

    DWORD Flags,
    DWORD *pFaceRemap
);

Parameters

Flags
[in] Combination of one or more flags from the D3DXMESHOPT enumeration that specifies the type of optimization to perform.
pFaceRemap
[in] Face remap array that indicates how the triangles were rearranged.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

After an application generates adjacency information for a mesh, the mesh data can be optimized (reordered) for better drawing performance. This method determines which patches are adjacent (within the provided tolerance).

See Also

ID3DXPMesh::GenerateAdjacency, ID3DXPMesh::Optimize


ID3DXPMesh::Save Method

Saves the progressive mesh to the specified stream object.

Syntax

HRESULT Save(

    IStream *pStream,
    const D3DXMATERIAL *pMaterials,
    CONST D3DXEFFECTINSTANCE* pEffectInstances,
    DWORD NumMaterials
);

Parameters

pStream
[in] Pointer to an IStream interface, representing the stream object to which the file data is written.
pMaterials
[in] Pointer to an array of D3DXMATERIAL structures, containing material information to be saved in the stream object.
pEffectInstances
[in] Pointer to an array of effect instances, one per attribute group in the mesh. An effect instance is a particular instance of state information used to initialize an effect. For more information, see D3DXEFFECTINSTANCE.
NumMaterials
[in] Number of D3DXMATERIAL structures in the pMaterials array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

For more information about the IStream interface, see the Microsoft Platform Software Development Kit (SDK).


ID3DXPMesh::SetNumFaces Method

Sets the current level of detail to as close to the specified number of faces as possible.

Syntax

HRESULT SetNumFaces(

    DWORD Faces
);

Parameters

Faces
[in] Target number of faces. This value specifies the desired change in the level of detail (LOD).

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the number of faces is greater than the maximum number of faces, it is capped at the maximum number of faces returned by ID3DXPMesh::GetMaxFaces. If the number of faces is less than the minimum number of faces, it is capped at the minimum number of faces returned by ID3DXPMesh::GetMinFaces.

The number of faces after this call may be off by one because some edge collapse may introduce or remove one face or two. For example, if you try setting the number of faces to an intermediate value such as 5, when 4 and 6 are possible, 4 will always be the result.


ID3DXPMesh::SetNumVertices Method

Sets the current level of detail to as close to the specified number of vertices as possible.

Syntax

HRESULT SetNumVertices(

    DWORD Vertices
);

Parameters

Vertices
[in] Target number of vertices. This value specifies the desired change in the level of detail (LOD).

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the number of vertices is greater than the maximum number of vertices, it is capped at the maximum number of vertices returned by ID3DXPMesh::GetMaxVertices. If the number of vertices is less than the minimum number of vertices, it is capped at the minimum number of vertices returned by ID3DXPMesh::GetMinVertices.

The number of vertices after this call may be off by one because some edge collapse may introduce or remove one face or two. For example, if you try setting the number of faces to an intermediate value such as 5, when 4 and 6 are possible, 4 will always be the result.


ID3DXPMesh::TrimByFaces Method

Modifies the minimum and maximum level of detail (LOD) of an ID3DXPMesh object.

Syntax

HRESULT TrimByFaces(

    DWORD NewFacesMin,
    DWORD NewFacesMax,
    DWORD *rgiFaceRemap,
    DWORD *rgiVertRemap
);

Parameters

NewFacesMin
[in] New minimum number of faces. This parameter must be between current minimum and maximum number of faces.
NewFacesMax
[in] New maximum number of faces. This parameter must be between current minimum and maximum number of faces.
rgiFaceRemap
[out] Returns one DWORD per face that contains face remap information.
rgiVertRemap
[out] Returns one DWORD per vertex that contians vertex remap information.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

See Also

ID3DXPMesh::TrimByVertices


ID3DXPMesh::TrimByVertices Method

Modifies the minimum and maximum level of detail (LOD) of an ID3DXPMesh object.

Syntax

HRESULT TrimByVertices(

    DWORD NewVerticesMin,
    DWORD NewVerticessMax,
    DWORD *rgiFaceRemap,
    DWORD *rgiVertRemap
);

Parameters

NewVerticesMin
[in] New minimum number of vertices. This parameter must be between current minimum and maximum number of vertices.
NewVerticessMax
[in] New maximum number of vertices. This parameter must be between current minimum and maximum number of vertices.
rgiFaceRemap
[out] Returns one DWORD per face that contains face remap information.
rgiVertRemap
[out] Returns one DWORD per vertex that contains vertex remap information.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

See Also

ID3DXPMesh::TrimByFaces


ID3DXPRTBuffer Interface

The ID3DXPRTBuffer interface is used as a data buffer to store vertex and pixel data for use with precomputed radiance transfer (PRT) methods and functions.

ID3DXPRTBuffer Members

AddBuffer | Adds another buffer to the ID3DXPRTBuffer and stores the results in ID3DXPRTBuffer.
AttachGH | Associates an ID3DXTextureGutterHelper object with the ID3DXPRTBuffer object.
EvalGH | Applies stored texture gutter data to an ID3DXPRTBuffer texture buffer.
ExtractTexture | Extracts coefficient data from a color channel of the buffer for a specified range of coefficients, and adds the data to an IDirect3DTexture9 object.
ExtractToMesh | Extracts coefficient data from a single-channel buffer and adds the data to an ID3DXMesh object.
GetHeight | Retrieves the height of the texture, in pixels.
GetNumChannels | Retrieves the number of color channels used in memory to store samples.
GetNumCoeffs | Retrieves the number of scalars per color channel used in memory to store samples.
GetNumSamples | Retrieves the number of vertices (or texels) sampled.
GetWidth | Retrieves the width of the texture, in pixels.
IsTexture | Indicates whether the buffer contains a texture.
LockBuffer | Locks a range of vertex or texel sample data and obtains a pointer to the location in buffer memory.
ReleaseGH | Unassociates an attached ID3DXTextureGutterHelper object with the ID3DXPRTBuffer object.
Resize | Changes the number of samples contained in the buffer.
ScaleBuffer | Multiplies every value in the buffer by a constant value.
UnlockBuffer | Ends the lifespan of the ppData pointer returned by ID3DXPRTBuffer::LockBuffer.

Remarks

The ID3DXPRTBuffer interface is obtained by calling the D3DXCreatePRTBuffer or D3DXCreatePRTBufferTex functions.

The LPD3DXPRTBUFFER type is defined as a pointer to the ID3DXPRTBuffer interface.

typedef interface ID3DXPRTBuffer ID3DXPRTBuffer;
typedef interface ID3DXPRTBuffer *LPD3DXPRTBUFFER;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreatePRTBuffer, D3DXCreatePRTBufferTex, ID3DXPRTCompBuffer


ID3DXPRTBuffer::AddBuffer Method

Adds another buffer to the ID3DXPRTBuffer and stores the results in ID3DXPRTBuffer.

Syntax

HRESULT AddBuffer(

    LPD3DXPRTBUFFER pBuffer
);

Parameters

pBuffer
[in] Pointer to a buffer that contains members to be added to the respective members of the ID3DXPRTBuffer buffer.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

pBuffer and ID3DXPRTBuffer must have the same number of samples, coefficients, and color channels; the method will fail otherwise.


ID3DXPRTBuffer::AttachGH Method

Associates an ID3DXTextureGutterHelper object with the ID3DXPRTBuffer object.

Syntax

HRESULT AttachGH(

    LPD3DXTEXTUREGUTTERHELPER pGH
);

Parameters

pGH
[in] Pointer to the ID3DXTextureGutterHelper interface of an object that contains texture gutter data.

Return Value

If the method succeeds, the return value is D3D_OK.

Remarks

The reference count of the ID3DXTextureGutterHelper object will automatically be incremented by one. Any existing ID3DXTextureGutterHelper pointers will be released.

You must ensure that the number of ID3DXPRTBuffer::AttachGH calls matches the number of ID3DXPRTBuffer::ReleaseGH calls. After calling ID3DXPRTBuffer::ReleaseGH, the pGH pointer returned by ID3DXPRTBuffer::AttachGH should no longer be used.

See Also

ID3DXPRTBuffer::ReleaseGH


ID3DXPRTBuffer::EvalGH Method

Applies stored texture gutter data to an ID3DXPRTBuffer texture buffer.

Syntax

HRESULT EvalGH(VOID);

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This method makes an internal call to ID3DXTextureGutterHelper::ApplyGuttersFloat to retrieve and apply texture gutter data.


ID3DXPRTBuffer::ExtractTexture Method

Extracts coefficient data from a color channel of the buffer for a specified range of coefficients, and adds the data to an IDirect3DTexture9 object.

Syntax

HRESULT ExtractTexture(

    UINT Channel,
    UINT StartCoefficient,
    UINT NumCoefficients,
    LPDIRECT3DTEXTURE9 pTexture
);

Parameters

Channel
[in] Buffer color channel from which to extract texture data.
StartCoefficient
[in] Starting value of the buffer coefficient from which to extract texture data.
NumCoefficients
[in] Number of scalars, beginning at StartCoefficient, from which to extract texture data.
pTexture
[in] Pointer to a IDirect3DTexture9 texture object that will store coefficients.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXPRTBuffer::ExtractToMesh Method

Extracts coefficient data from a single-channel buffer and adds the data to an ID3DXMesh object.

Syntax

HRESULT ExtractToMesh(

    UINT NumCoefficients,
    D3DDECLUSAGE Usage,
    UINT UsageIndexStart,
    LPD3DXMESH pScene
);

Parameters

NumCoefficients
[in] Number of coefficients to extract from the buffer. When using spherical harmonic (SH) precomputed radiance transfer (PRT), the number of coefficients should be Order2. Order must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive.
Usage
[in] Vertex usage descriptions of the mesh. See D3DDECLUSAGE.
UsageIndexStart
[in] Starting index for coefficients to be stored in the mesh.
pScene
[in] Pointer to an ID3DXMesh mesh object that will store coefficients.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXPRTBuffer::GetHeight Method

Retrieves the height of the texture, in pixels.

Syntax

UINT GetHeight(VOID);

Return Value

Returns the height of the texture, in pixels.

See Also

ID3DXPRTBuffer::GetWidth


ID3DXPRTBuffer::GetNumChannels Method

Retrieves the number of color channels used in memory to store samples.

Syntax

UINT GetNumChannels(VOID);

Return Value

Returns the number of color channels used in memory to store samples. The value generally will be either 1 to represent luminance values, or 3 to represent RGB values.


ID3DXPRTBuffer::GetNumCoeffs Method

Retrieves the number of scalars per color channel used in memory to store samples.

Syntax

UINT GetNumCoeffs(VOID);

Return Value

Returns the number of scalars per color channel used in memory to store samples.


ID3DXPRTBuffer::GetNumSamples Method

Retrieves the number of vertices (or texels) sampled.

Syntax

UINT GetNumSamples(VOID);

Return Value

Returns the number of vertices (or texels) sampled.


ID3DXPRTBuffer::GetWidth Method

Retrieves the width of the texture, in pixels.

Syntax

UINT GetWidth(VOID);

Return Value

Returns the width of the texture, in pixels.

See Also

ID3DXPRTBuffer::GetHeight


ID3DXPRTBuffer::IsTexture Method

Indicates whether the buffer contains a texture.

Syntax

BOOL IsTexture(VOID);

Return Value

Returns TRUE if the buffer contains a texture; returns FALSE otherwise.


ID3DXPRTBuffer::LockBuffer Method

Locks a range of vertex or texel sample data and obtains a pointer to the location in buffer memory.

Syntax

HRESULT LockBuffer(

    UINT Start,
    UINT NumSamples,
    FLOAT **ppData
);

Parameters

Start
[in] Index of the sample of vertex or texel data.
NumSamples
[in] Number of vertices (or texels) sampled.
ppData
[out] Pointer to the location in memory where the Start sample begins.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXPRTBuffer::ReleaseGH Method

Unassociates an attached ID3DXTextureGutterHelper object with the ID3DXPRTBuffer object.

Syntax

HRESULT ReleaseGH(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

Remarks

This method releases the pointer to the ID3DXTextureGutterHelper interface.

You must ensure that the number of ID3DXPRTBuffer::AttachGH calls matches the number of ID3DXPRTBuffer::ReleaseGH calls. After calling ID3DXPRTBuffer::ReleaseGH, the pGH pointer returned by ID3DXPRTBuffer::AttachGH should no longer be used.

See Also

ID3DXPRTBuffer::AttachGH


ID3DXPRTBuffer::Resize Method

Changes the number of samples contained in the buffer.

Syntax

HRESULT Resize(

    UINT NewSize
);

Parameters

NewSize
[in] Number of samples to be contained in the buffer.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the following value will be returned.

E_OUTOFMEMORY Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXPRTBuffer::ScaleBuffer Method

Multiplies every value in the buffer by a constant value.

Syntax

HRESULT ScaleBuffer(

    FLOAT Scale
);

Parameters

Scale
[in] Constant value used to scale the buffer. Every value in the buffer is replaced by the product of this value and the original buffer value.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXPRTBuffer::UnlockBuffer Method

Ends the lifespan of the ppData pointer returned by ID3DXPRTBuffer::LockBuffer.

Syntax

HRESULT UnlockBuffer(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.


ID3DXPRTCompBuffer Interface

The ID3DXPRTCompBuffer interface stores a compressed version of a ID3DXPRTBuffer buffer, for use with principal component analysis (PCA).

ID3DXPRTCompBuffer Members

ExtractBasis | Extracts the mean and principal component analysis (PCA) basis vectors for a given cluster from an ID3DXPRTCompBuffer compressed data buffer.
ExtractClusterIDs | Extracts the per-sample cluster identifiers (IDs) from an ID3DXPRTCompBuffer compressed data buffer.
ExtractPCA | Extracts the per-sample principal component analysis (PCA) projection coefficients from an ID3DXPRTCompBuffer compressed data buffer.
ExtractTexture | Extracts the per-sample principal component analysis (PCA) projection coefficients from an ID3DXPRTCompBuffer compressed data buffer and adds the data to an IDirect3DTexture9 object.
ExtractToMesh | Extracts the per-sample principal component analysis (PCA) projection coefficients from an ID3DXPRTCompBuffer compressed data buffer and adds the data to an ID3DXMesh object.
GetHeight | Retrieves the height of the texture, in pixels.
GetNumChannels | Retrieves the number of color channels used in memory to store samples.
GetNumClusters | Retrieves the number of clusters to use for compression.
GetNumCoeffs | Retrieves the number of scalars per color channel used in memory to store samples.
GetNumPCA | Retrieves the number of principal component analysis (PCA) basis vectors to use in each cluster.
GetNumSamples | Retrieves the number of vertices (or texels) sampled.
GetWidth | Retrieves the width of the texture, in pixels.
IsTexture | Indicates whether the buffer contains a texture.
NormalizeData | Normalizes all principal component analysis (PCA) weights so that they are between -1 and 1. Basis vectors are modified to reflect this normalization.

Remarks

The ID3DXPRTCompBuffer interface is obtained by calling the D3DXCreatePRTCompBuffer function.

The LPD3DXPRTCOMPBUFFER type is defined as a pointer to the ID3DXPRTCompBuffer interface.

typedef interface ID3DXPRTCompBuffer ID3DXPRTCompBuffer;
typedef interface ID3DXPRTCompBuffer *LPD3DXPRTCOMPBUFFER;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreatePRTCompBuffer, ID3DXPRTBuffer


ID3DXPRTCompBuffer::ExtractBasis Method

Extracts the mean and principal component analysis (PCA) basis vectors for a given cluster from an ID3DXPRTCompBuffer compressed data buffer.

Syntax

HRESULT ExtractBasis(

    UINT Cluster,
    FLOAT *pClusterBasis
);

Parameters

Cluster
[in] Cluster for which the basis will be extracted.
pClusterBasis
[in, out] Pointer to an array of basis vector data for Cluster.

The size of the FLOAT data stored will be:

(1 + Number of PCA vectors per cluster) * (Number of coefficients) * (Number of color channels)

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXPRTCompBuffer::ExtractClusterIDs Method

Extracts the per-sample cluster identifiers (IDs) from an ID3DXPRTCompBuffer compressed data buffer.

Syntax

HRESULT ExtractClusterIDs(

    UINT *pClusterIDs
);

Parameters

pClusterIDs
[in, out] Pointer to the location in memory where IDs are written. The length of memory required is the value returned by ID3DXPRTCompBuffer::GetNumSamples.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXPRTCompBuffer::ExtractPCA Method

Extracts the per-sample principal component analysis (PCA) projection coefficients from an ID3DXPRTCompBuffer compressed data buffer.

Syntax

HRESULT ExtractPCA(

    UINT StartPCA,
    UINT NumExtract,
    FLOAT *pPCACoefficients
);

Parameters

StartPCA
[in] Starting index for PCA projection coefficients to extract from the buffer.
NumExtract
[in] Number of PCA projection coefficients to extract from the buffer.
pPCACoefficients
[in] Pointer to the location where clustered principal component analysis (CPCA) coefficients are written. The size of the data written is (Number of Samples) * (Number of PCA Coefficients).

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXPRTCompBuffer::ExtractTexture Method

Extracts the per-sample principal component analysis (PCA) projection coefficients from an ID3DXPRTCompBuffer compressed data buffer and adds the data to an IDirect3DTexture9 object.

Syntax

HRESULT ExtractTexture(

    UINT StartPCA,
    UINT NumPCA,
    LPDIRECT3DTEXTURE9 pTexture
);

Parameters

StartPCA
[in] Starting value of the buffer coefficient from which to extract texture data.
NumPCA
[in] Number of PCA coefficients to extract from the buffer.
pTexture
[in] Pointer to an IDirect3DTexture9 texture object that will store PCA coefficients.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXPRTCompBuffer::ExtractToMesh Method

Extracts the per-sample principal component analysis (PCA) projection coefficients from an ID3DXPRTCompBuffer compressed data buffer and adds the data to an ID3DXMesh object.

Syntax

HRESULT ExtractToMesh(

    UINT NumPCA,
    D3DDECLUSAGE Usage,
    UINT UsageIndexStart,
    LPD3DXMESH pScene
);

Parameters

NumPCA
[in] Number of PCA coefficients to extract from the buffer.
Usage
[in] Vertex usage descriptions of the mesh. See D3DDECLUSAGE.
UsageIndexStart
[in] Starting index for PCA coefficients to be stored in the mesh.
pScene
[in] Pointer to an ID3DXMesh mesh object that will store PCA coefficients.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXPRTCompBuffer::GetHeight Method

Retrieves the height of the texture, in pixels.

Syntax

UINT GetHeight(VOID);

Return Value

Returns the height of the texture, in pixels.

See Also

ID3DXPRTCompBuffer::GetWidth


ID3DXPRTCompBuffer::GetNumChannels Method

Retrieves the number of color channels used in memory to store samples.

Syntax

UINT GetNumChannels(VOID);

Return Value

Returns the number of color channels used in memory to store samples. The value generally will be either 1 to represent luminance values, or 3 to represent RGB values.

Remarks


ID3DXPRTCompBuffer::GetNumClusters Method

Retrieves the number of clusters to use for compression.

Syntax

UINT GetNumClusters(VOID);

Return Value

Returns the number of clusters to use for compression.


ID3DXPRTCompBuffer::GetNumCoeffs Method

Retrieves the number of scalars per color channel used in memory to store samples.

Syntax

UINT GetNumCoeffs(VOID);

Return Value

Returns the number of scalars per color channel used in memory to store samples.

Remarks


ID3DXPRTCompBuffer::GetNumPCA Method

Retrieves the number of principal component analysis (PCA) basis vectors to use in each cluster.

Syntax

UINT GetNumPCA(VOID);

Return Value

Returns the number of principal component analysis (PCA) basis vectors to use in each cluster.


ID3DXPRTCompBuffer::GetNumSamples Method

Retrieves the number of vertices (or texels) sampled.

Syntax

UINT GetNumSamples(VOID);

Return Value

Returns the number of vertices (or texels) sampled.


ID3DXPRTCompBuffer::GetWidth Method

Retrieves the width of the texture, in pixels.

Syntax

UINT GetWidth(VOID);

Return Value

Returns the width of the texture, in pixels.

See Also

ID3DXPRTCompBuffer::GetHeight


ID3DXPRTCompBuffer::IsTexture Method

Indicates whether the buffer contains a texture.

Syntax

BOOL IsTexture(VOID);

Return Value

Returns TRUE if the buffer contains a texture; returns FALSE otherwise.


ID3DXPRTCompBuffer::NormalizeData Method

Normalizes all principal component analysis (PCA) weights so that they are between -1 and 1. Basis vectors are modified to reflect this normalization.

Syntax

HRESULT NormalizeData(VOID);

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXPRTEngine Interface

The ID3DXPRTEngine interface is used to compute a precomputed radiance transfer (PRT) simulation. Its methods are typically used offline, to compute per-vertex or per-texel transfer vectors in advance of real-time 3-D modeling.

ID3DXPRTEngine Members

ComputeBounce | Computes the source radiance resulting from a single bounce of interreflected light. This method can be used for any lit scene, including a spherical harmonic (SH)-based PRT model.
ComputeBounceAdaptive | Computes the source radiance resulting from a single bounce of interreflected light, using adaptive sampling. This method generates new vertices and faces on the mesh to more accurately approximate the PRT signal. This method can be used for any lit scene, including a SH-based PRT model.
ComputeConvCoeffs | Computes convolution coefficients relative to per-sample normal vectors to minimize the least-squares error with respect to input PRT data. The convolution coefficients can be used with skinned or transformed normals to model global effects on dynamic objects.
ComputeDirectLightingSH | Computes the direct lighting contribution to 3-D objects where the source radiance is represented by a SH approximation.
ComputeDirectLightingSHAdaptive | Computes the direct lighting contribution to 3-D objects where the source radiance is represented by a SH approximation, using adaptive sampling. This method generates new vertices and faces on the mesh to more accurately approximate the PRT signal.
ComputeDirectLightingSHGPU | Uses the graphics processing unit (GPU) to compute the direct lighting contribution to 3-D objects where the source radiance is represented by a SH approximation. Computing the lighting on the GPU will generally be much faster than on the CPU.
ComputeSS | Computes the source radiance resulting from subsurface scattering, using material properties set by ID3DXPRTEngine::SetMeshMaterials. This method can be used only for materials defined per-vertex in a mesh object.
ComputeVolumeSamples | Computes a projection of the direct lighting from the previous light bounce into SH basis vectors that represent incident radiance at specified locations.
ComputeVolumeSamplesDirectSH | Computes a projection of distant lighting into SH basis vectors that represent incident radiance at specified locations.
ExtractPerVertexAlbedo | Copies per-vertex albedo values from a mesh.
FreeBounceData | Frees memory used for temporary bounced-light simulation data.
FreeSSData | Frees memory used for temporary subsurface light scattering simulation data.
GetAdaptedMesh | Returns a mesh with modifications resulting from adaptive spatial sampling. The returned mesh contains only positions, normals, and texture coordinates (if defined).
GetNumFaces | Retrieves the number of faces in the mesh, including any new faces added as a result of adaptive spatial sampling.
GetNumVerts | Retrieves the number of vertices in the mesh, including any new vertices added as a result of adaptive spatial sampling.
GetVertexAlbedo | Retrieves albedo values of the mesh vertices.
MultiplyAlbedo | Multiplies each PRT vector by the per-vertex albedo.
ResampleBuffer | Resamples an input ID3DXPRTBuffer buffer and saves it to an output buffer. This method can be used to convert a vertex buffer to a texture buffer and vice-versa. It can also be used to convert single-channel buffers to 3-channel buffers and vice-versa.
RobustMeshRefine | Subdivides faces on a mesh, allowing for conservative adaptive sampling that will not eliminate features on the mesh.
ScaleMeshChunk | Scales all the samples associated with a given submesh. The method is useful for computing subsurface scattering.
SetCallBack | Sets a pointer to an optional callback function that computes the percentage of SH computations completed and gives the caller the option of aborting the simulator.
SetMeshMaterials | Sets mesh material properties in the 3-D scene. Use this method to specify subsurface scattering parameters.
SetPerTexelAlbedo | Sets an albedo value for each texel, overwriting previous albedo values.
SetPerTexelNormal | Sets a normal vector for each texel in a texture object. This method is used to store vertex normal vectors from a mesh (or interpolated vertex normals if pixel-based PRT is being computed).
SetPerVertexAlbedo | Sets an albedo value for each mesh
SetSamplingInfo | Sets sampling properties used by the PRT simulator.

Remarks

To convert from RGB to luminance values, the following formula is used:

Luminance = R * 0.2125 + G * 0.7154 + B * 0.0721

The ID3DXPRTEngine interface is obtained by calling the D3DXCreatePRTEngine function.

The LPD3DXPRTENGINE type is defined as a pointer to the ID3DXPRTEngine interface.

typedef interface ID3DXPRTEngine ID3DXPRTEngine;
typedef interface ID3DXPRTEngine *LPD3DXPRTENGINE;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreatePRTEngine


ID3DXPRTEngine::ComputeBounce Method

Computes the source radiance resulting from a single bounce of interreflected light. This method can be used for any lit scene, including a spherical harmonic (SH)-based precomputed radiance transfer (PRT) model.

Syntax

HRESULT ComputeBounce(

    LPD3DXPRTBUFFER pDataIn,
    LPD3DXPRTBUFFER pDataOut,
    LPD3DXPRTBUFFER pDataTotal
);

Parameters

pDataIn
[in] Pointer to an input ID3DXPRTBuffer object that represents the 3-D object from the previous light bounce. This input buffer must have the proper number of color channels allocated for the simulation.
pDataOut
[in, out] Pointer to an output ID3DXPRTBuffer object that models a single bounce of the interreflected light. This output buffer must have the proper number of color channels allocated for the simulation.
pDataTotal
[in, out] Pointer to an optional ID3DXPRTBuffer object that is the running sum of all previous pDataOut outputs. May be NULL.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

Use the following calling sequence to model multiple light bounces with direct lighting.

LPD3DXPRTBUFFER pDataA, pDataB, pDataC; // initialization
ID3DXPRTEngine* m_pPRTEngine;

ComputeDirectLightingSH( SHOrder, pDataA );

// The accumulation buffer, pDataC, needs to be
// initialized to the direct lighting result.

pDataC->AddBuffer( pDataA );

hr = m_pPRTEngine->ComputeBounce( pDataA, pDataB, pDataC ); // first bounce
hr = m_pPRTEngine->ComputeBounce( pDataB, pDataA, pDataC ); // second bounce
hr = m_pPRTEngine->ComputeBounce( pDataA, pDataB, pDataC ); // third bounce
hr = m_pPRTEngine->ComputeBounce( pDataB, pDataA, pDataC ); // fourth bounce

Use the following calling sequence to model multiple light bounces with subsurface scattering.

LPD3DXPRTBUFFER pDataA, pDataB, pDataC; // initialization
ID3DXPRTEngine* m_pPRTEngine;

ComputeDirectLightingSH( SHOrder, pDataA );

// *pDataC should be set to zero. The ComputeSS call will add together
// the direct lighting results from pDataA for non-subsurface scattering
// elements and subsurface scattering results for the subsurface scattering
// elements. Perform proper error handling for each call.

hr = m_pPRTEngine->ComputeSS    ( pDataA, pDataB, pDataC );
hr = m_pPRTEngine->ComputeBounce( pDataB, pDataA, NULL   ); // first bounce
hr = m_pPRTEngine->ComputeSS    ( pDataA, pDataB, pDataC );
hr = m_pPRTEngine->ComputeBounce( pDataB, pDataA, NULL   ); // second bounce
hr = m_pPRTEngine->ComputeSS    ( pDataA, pDataB, pDataC );

The output of this method does not include albedo, and only incoming light is integrated in the simulator. By not multiplying the albedo, you can model albedo variation at a finer scale than the source radiance, thereby yielding more accurate results from compression.

Call ID3DXPRTEngine::MultiplyAlbedo to multiply each PRT vector by the albedo.

See Also

ID3DXPRTEngine::ComputeSS


ID3DXPRTEngine::ComputeBounceAdaptive Method

Computes the source radiance resulting from a single bounce of interreflected light, using adaptive sampling. This method generates new vertices and faces on the mesh to more accurately approximate the precomputed radiance transfer (PRT) signal. This method can be used for any lit scene, including a spherical harmonic (SH)-based PRT model.

Syntax

HRESULT ComputeBounceAdaptive(

    LPD3DXPRTBUFFER pDataIn,
    FLOAT AdaptiveThresh,
    FLOAT MinEdgeLength,
    UINT MaxSubdiv,
    LPD3DXPRTBUFFER pDataOut,
    LPD3DXPRTBUFFER pDataTotal
);

Parameters

pDataIn
[in] Pointer to an input ID3DXPRTBuffer object that represents the 3-D object from the previous light bounce. This input buffer must have the proper number of color channels allocated for the simulation.
AdaptiveThresh
[in] Threshold on the PRT vector to use for subdividing mesh vertices and faces. If less than 1e-6f, a default value of 1e-6f is specified.
MinEdgeLength
[in] Minimum face edge length that will be generated in adaptive sampling. If the method determines that the value is too small, a model-dependent value is specified. If zero, a default value of 4 is specified.
MaxSubdiv
[in] Maximum level of subdivision of a face that will be used in adaptive sampling.
pDataOut
[in, out] Pointer to an output ID3DXPRTBuffer object. This output buffer must have the proper number of color channels allocated for the simulation.
pDataTotal
[in, out] Pointer to an optional ID3DXPRTBuffer object that keeps a running sum of pDataOut with each light bounce computation. May be NULL.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXPRTEngine::ComputeConvCoeffs Method

Computes convolution coefficients relative to per-sample normal vectors to minimize the least-squares error with respect to input precomputed radiance transfer (PRT) data. The convolution coefficients can be used with skinned or transformed normals to model global effects on dynamic objects.

Syntax

HRESULT ComputeConvCoeffs(

    LPD3DXPRTBUFFER pDataIn,
    UINT Order,
    D3DXVECTOR3 *pNormOut,
    LPD3DXPRTBUFFER pDataOut
);

Parameters

pDataIn
[in] Pointer to an input ID3DXPRTBuffer spherical harmonic (SH) PRT data object.
Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pNormOut
[in, out] Optional vector array to be filled with shader-optimal normal vectors for which convolution coefficients are optimized. This array must be the same size as the number of samples in pDataIn. If NULL, surface normals are used.
pDataOut
[in, out] Pointer to an output ID3DXPRTBuffer object that contains Order convolution coefficients per color channel per sample.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXPRTEngine::ComputeDirectLightingSH Method

Computes the direct lighting contribution to 3-D objects where the source radiance is represented by a spherical harmonic (SH) approximation.

Syntax

HRESULT ComputeDirectLightingSH(

    UINT Order,
    LPD3DXPRTBUFFER pDataOut
);

Parameters

Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pDataOut
[in, out] Pointer to an output ID3DXPRTBuffer object that models the direct lighting contribution with the SH approximation. This buffer must have the proper number of color channels allocated for the simulation.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The output does not include albedo, and only incoming light is integrated in the simulator. By not multiplying the albedo, you can model albedo variation at a finer scale than the source radiance, thereby yielding more accurate results from compression.

Call ID3DXPRTEngine::MultiplyAlbedo to multiply each precomputed radiance transfer (PRT) vector by the albedo.


ID3DXPRTEngine::ComputeDirectLightingSHAdaptive Method

Computes the direct lighting contribution to 3-D objects where the source radiance is represented by a spherical harmonic (SH) approximation, using adaptive sampling. This method generates new vertices and faces on the mesh to more accurately approximate the precomputed radiance transfer (PRT) signal.

Syntax

HRESULT ComputeDirectLightingSHAdaptive(

    UINT Order,
    FLOAT AdaptiveThresh,
    FLOAT MinEdgeLength,
    UINT MaxSubdiv,
    LPD3DXPRTBUFFER pDataOut
);

Parameters

Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
AdaptiveThresh
[in] Threshold on the PRT vector to use for subdividing mesh vertices and faces. If less than 1e-6f, a default value of 1e-6f is specified.
MinEdgeLength
[in] Minimum face edge length that will be generated in adaptive sampling. If the method determines that the value is too small, a model-dependent value is specified. If zero, a default value of 4 is specified.
MaxSubdiv
[in] Maximum level of subdivision of a face that will be used in adaptive sampling.
pDataOut
[in, out] Pointer to an output ID3DXPRTBuffer object. This buffer must have the proper number of color channels allocated for the simulation.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

See Also

ID3DXPRTEngine::RobustMeshRefine


ID3DXPRTEngine::ComputeDirectLightingSHGPU Method

Uses the graphics processing unit (GPU) to compute the direct lighting contribution to 3-D objects where the source radiance is represented by a spherical harmonic (SH) approximation. Computing the lighting on the GPU will generally be much faster than on the CPU.

Syntax

HRESULT ComputeDirectLightingSHGPU(

    LPDIRECT3DDEVICE9 pDevice,
    UINT Order,
    UINT Flags,
    FLOAT ZBias,
    FLOAT ZAngleBias,
    LPD3DXPRTBUFFER pDataOut
);

Parameters

pDevice
[in] Pointer to the IDirect3DDevice9 device object used to run the simulation on the GPU. The device must support ps_2_0 pixel shaders.

Note Callback functions should not use the IDirect3DDevice9 device object used by the GPU simulator.
Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
Flags
[in] GPU simulation parameter that defines the resolution of the shadow z-buffer. Should be set to one of the constant values from D3DXSHGPUSIMOPT. To specifiy higher precision simulation, the D3DXSHGPUSIMOPT_HIGHQUALITY value may be combined with one of the D3DXSHGPUSIMOPT_SHADOWRESxxx values.
ZBias
[in] Bias in the normal direction.
ZAngleBias
[in] Bias in the normal direction, scaled by one minus the cosine of the angle with the light ray.
pDataOut
[in, out] Pointer to an ID3DXPRTBuffer object. This buffer must have the proper number of color channels allocated for the simulation.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

In this method, the albedo is not multiplied by the light signal, and only incoming light is integrated in the simulator. By not multiplying the albedo, you can model albedo variation at a finer scale than the source radiance, thereby yielding more accurate results from compression.

Call ID3DXPRTEngine::MultiplyAlbedo to multiply each precomputed radiance transfer (PRT) vector by the albedo.


ID3DXPRTEngine::ComputeSS Method

Computes the source radiance resulting from subsurface scattering, using material properties set by ID3DXPRTEngine::SetMeshMaterials. This method can be used only for materials defined per-vertex in a mesh object.

Syntax

HRESULT ComputeSS(

    LPD3DXPRTBUFFER pDataIn,
    LPD3DXPRTBUFFER pDataOut,
    LPD3DXPRTBUFFER pDataTotal
);

Parameters

pDataIn
[in] Pointer to an input ID3DXPRTBuffer object that represents the 3-D object from the previous light bounce. This input buffer must have the proper number of color channels allocated for the simulation.
pDataOut
[in, out] Pointer to an output ID3DXPRTBuffer object that models a single bounce of the subsurface-scattered light. This output buffer must have the proper number of color channels allocated for the simulation.
pDataTotal
[in, out] Pointer to an optional ID3DXPRTBuffer object that is the running sum of all previous pDataOut outputs. May be NULL.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

To model subsurface scattering, call this method for each light bounce after an ID3DXPRTEngine::ComputeDirectLighting... method is called.

Use the following calling sequence to model subsurface scattering.

LPD3DXPRTBUFFER pDataA, pDataB, pDataC; // initialization
ID3DXPRTEngine* m_pPRTEngine;

hr = m_pPRTEngine->ComputeDirectLightingSH( SHOrder, pDataA );

// *pDataC should be set to zero. The ComputeSS call will add together the
// direct lighting results from pDataA for non-subsurface scattering elements
// and subsurface scattering results for the subsurface scattering elements.

hr = m_pPRTEngine->ComputeSS( pDataA, pDataB, pDataC );
if ( FAILED( hr ) goto Exit;

The output of this method does not include albedo, and only incoming light is integrated in the simulator. By not multiplying the albedo, you can model albedo variation at a finer scale than the source radiance, thereby yielding more accurate results from compression.

Call ID3DXPRTEngine::MultiplyAlbedo to multiply each precomputed radiance transfer (PRT) vector by the albedo.

See Also

ID3DXPRTEngine::ComputeBounce


ID3DXPRTEngine::ComputeVolumeSamples Method

Computes a projection of the direct lighting from the previous light bounce into spherical harmonic (SH) basis vectors that represent incident radiance at specified locations.

Syntax

HRESULT ComputeVolumeSamples(

    LPD3DXPRTBUFFER pSurfDataIn,
    UINT Order,
    UINT NumVolSamples,
    const D3DXVECTOR3 *pSampleLocs,
    LPD3DXPRTBUFFER pDataOut
);

Parameters

pSurfDataIn
[in] Pointer to an input ID3DXPRTBuffer object that represents the 3-D object from the previous light bounce.
Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
NumVolSamples
[in] Number of sample locations.
pSampleLocs
[in] Position for each sample.
pDataOut
[in, out] Pointer to an output ID3DXPRTBuffer object that projects the direct lighting from the previous light bounce into SH basis vectors. This buffer must have the proper number of color channels allocated for the simulation.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

This method computes how the light from the source radiance function is reflected off the surface that represents the scene (pSurfDataIn) and arrives at each point in space specified by pSampleLocs. The SH coefficients represent the mapping, at each pSampleLocs point, of source radiance to transferred incident radiance.

To use this method successfully, you must set sampling over a sphere with UseSphere = TRUE and UseCosine = FALSE in ID3DXPRTEngine::SetSamplingInfo; otherwise, this method will return an error with D3DERR_INVALIDCALL.

See Also

ID3DXPRTEngine::ComputeVolumeSamples


ID3DXPRTEngine::ComputeVolumeSamplesDirectSH Method

Computes a projection of distant lighting into spherical harmonic (SH) basis vectors that represent incident radiance at specified locations.

Syntax

HRESULT ComputeVolumeSamplesDirectSH(

    UINT OrderIn,
    UINT OrderOut,
    UINT NumVolSamples,
    const D3DXVECTOR3 *pSampleLocs,
    LPD3DXPRTBUFFER pDataOut
);

Parameters

OrderIn
[in] Order of the SH representation of distant lighting. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The degree of the evaluation is OrderIn - 1.
OrderOut
[in] Order of the SH representation of local lighting. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The degree of the evaluation is OrderOut - 1.
NumVolSamples
[in] Number of sample locations.
pSampleLocs
[in] Position for each sample.
pDataOut
[in, out] Pointer to an output ID3DXPRTBuffer object that projects the distant lighting into SH basis vectors. This buffer must have the proper number of color channels allocated for the simulation. This method generates OrderIn2 * OrderOut2 scalars per channel at each sample location.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

This method computes how light from a distant source arrives at each point in space specified by pSampleLocs. The SH coefficients represent the mapping, at each pSampleLocs point, of source radiance to transferred incident radiance.

To use this method successfully, you must set sampling over a sphere with UseSphere = TRUE and UseCosine = FALSE in ID3DXPRTEngine::SetSamplingInfo; otherwise, this method will return an error with D3DERR_INVALIDCALL.

See Also

ID3DXPRTEngine::ComputeVolumeSamples


ID3DXPRTEngine::ExtractPerVertexAlbedo Method

Copies per-vertex albedo values from a mesh.

Syntax

HRESULT ExtractPerVertexAlbedo(

    LPD3DXMESH pMesh,
    D3DDECLUSAGE Usage,
    UINT NumChanIn
);

Parameters

pMesh
[in] Pointer to the ID3DXMesh mesh object used in D3DXCreatePRTEngine to create the ID3DXPRTEngine object.
Usage
[in] Vertex usage descriptions to copy from the mesh. See D3DDECLUSAGE.
NumChanIn
[in] Number of color channels to copy from the mesh. Set to 1 to specify gray materials (R = G = B), or 3 to enable color bleeding effects.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXPRTEngine::FreeBounceData Method

Frees memory used for temporary bounced-light simulation data.

Syntax

HRESULT FreeBounceData(VOID);

Return Value

The return value is S_OK.


ID3DXPRTEngine::FreeSSData Method

Frees memory used for temporary subsurface light scattering simulation data.

Syntax

HRESULT FreeSSData(VOID);

Return Value

The return value is D3D_OK.


ID3DXPRTEngine::GetAdaptedMesh Method

Returns a mesh with modifications resulting from adaptive spatial sampling. The returned mesh contains only positions, normals, and texture coordinates (if defined).

Syntax

HRESULT GetAdaptedMesh(

    LPDIRECT3DDEVICE9 pDevice,
    UINT *pFaceRemap,
    UINT *pVertRemap,
    FLOAT *pfVertWeights,
    LPD3DXMESH *ppMesh
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 device that is used to create the output mesh.
pFaceRemap
[in, out] Pointer to the original mesh face that was split to generate the current face.
pVertRemap
[in, out] Pointer to a destination array containing the three original mesh vertices that are the parents of the current vertex.
pfVertWeights
[in, out] Pointer to a destination array containing blending factors for the pVertRemap vertices.
ppMesh
[out] Pointer to the output ID3DXMesh mesh object.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

pVertRemap and pfVertWeights can be used to interpolate any per-vertex value over the mesh.


ID3DXPRTEngine::GetNumFaces Method

Retrieves the number of faces in the mesh, including any new faces added as a result of adaptive spatial sampling.

Syntax

UINT GetNumFaces(VOID);

Return Value

Number of faces in the mesh, including any new faces added as a result of adaptive sampling.


ID3DXPRTEngine::GetNumVerts Method

Retrieves the number of vertices in the mesh, including any new vertices added as a result of adaptive spatial sampling.

Syntax

UINT GetNumVerts(VOID);

Return Value

Number of vertices in the mesh, including any new vertices added as a result of adaptive sampling.


ID3DXPRTEngine::GetVertexAlbedo Method

Retrieves albedo values of the mesh vertices.

Syntax

HRESULT GetVertexAlbedo(

    D3DXCOLOR *pVertColors,
    UINT NumVerts
);

Parameters

pVertColors
[in, out] Pointer to a destination array of albedo values of the mesh vertices. See D3DXCOLOR.
NumVerts
[in] Number of vertices in the mesh.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXPRTEngine::MultiplyAlbedo Method

Multiplies each precomputed radiance transfer (PRT) vector by the per-vertex albedo.

Syntax

HRESULT MultiplyAlbedo(

    LPD3DXPRTBUFFER pDataOut
);

Parameters

pDataOut
[in, out] Pointer to an output ID3DXPRTBuffer object that will contain PRT vectors multiplied by the per-vertex albedo.

If this output buffer is a texture object, then care must be taken to store the albedo of the texture at the same resolution as the simulation buffer. You can set the proper resolution on the albedo with D3DXLoadSurfaceFromSurface, applying texture gutter regions if appropriate.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The ID3DXPRTEngine::Computexxx methods compute output buffers in which the light signal has not been multiplied by albedo. By not multiplying the albedo, you can model albedo variation at a finer scale than the source radiance, thereby yielding more accurate results from compression.

To include albedo in the rendered-light model, call this method after one of the Computexxx methods.

ID3DXPRTEngine::SetMeshMaterials should be called before calling this method.

See Also

ID3DXPRTEngine::ComputeDirectLightingSH


ID3DXPRTEngine::ResampleBuffer Method

Resamples an input ID3DXPRTBuffer buffer and saves it to an output buffer. This method can be used to convert a vertex buffer to a texture buffer and vice-versa. It can also be used to convert single-channel buffers to 3-channel buffers and vice-versa.

Syntax

HRESULT ResampleBuffer(

    LPD3DXPRTBUFFER pBufferIn,
    LPD3DXPRTBUFFER pBufferOut
);

Parameters

pBufferIn
[in] Pointer to the input ID3DXPRTBuffer buffer.
pBufferOut
[in, out] Pointer to the output ID3DXPRTBuffer buffer.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXPRTEngine::RobustMeshRefine Method

Subdivides faces on a mesh, allowing for conservative adaptive sampling that will not eliminate features on the mesh.

Syntax

HRESULT RobustMeshRefine(

    FLOAT MinEdgeLength,
    UINT MaxSubdiv
);

Parameters

MinEdgeLength
[in] Minimum face edge length that will be generated in adaptive sampling. If zero, a reasonable default value will be substituted.
MaxSubdiv
[in] Maximum level of subdivision of a face that will be used in adaptive sampling. If zero, a default value of 5 will be substituted.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

See Also

ID3DXPRTEngine::ComputeBounceAdaptive, ID3DXPRTEngine::ComputeDirectLightingSHAdaptive


ID3DXPRTEngine::ScaleMeshChunk Method

Scales all the samples associated with a given submesh. The method is useful for computing subsurface scattering.

Syntax

HRESULT ScaleMeshChunk(

    UINT uMeshChunk,
    FLOAT fScale,
    LPD3DXPRTBUFFER pDataOut
);

Parameters

uMeshChunk
[in] Location in the mesh at which to start scaling samples.
fScale
[in] Value by which to multiply each vector in the submesh.
pDataOut
[in, out] Pointer to a ID3DXPRTBuffer object to receive rescaled samples in the submesh.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXPRTEngine::SetCallBack Method

Sets a pointer to an optional callback function that computes the percentage of spherical harmonic (SH) computations completed and gives the caller the option of aborting the simulator.

Syntax

HRESULT SetCallBack(

    LPD3DXSHPRTSIMCB pCB,
    FLOAT Frequency,
    LPVOID lpUserContext
);

Parameters

pCB
[in] Pointer to the LPD3DXSHPRTSIMCB callback function that computes the percentage of SH computations completed.

The callback function must be implemented to return S_OK to keep running the simulator. Any other value will abort the simulator.
Frequency
[in] Frequency of callback calls. The inverse of Frequency is approximately the number of times the callback function will be called.
lpUserContext
[in] Pointer to a user-defined value which is passed to the callback function. Typically used by an application to pass a pointer to a data structure that provides context information for the callback function.

Return Value

The return value is S_OK.


ID3DXPRTEngine::SetMeshMaterials Method

Sets mesh material properties in the 3-D scene. Use this method to specify subsurface scattering parameters.

Syntax

HRESULT SetMeshMaterials(

    const D3DXSHMATERIAL **ppMaterials,
    UINT NumMeshes,
    UINT NumChannels,
    BOOL bSetAlbedo,
    FLOAT fLengthScale
);

Parameters

ppMaterials
[in] Address of a pointer to desired mesh material properties. See D3DXSHMATERIAL.
NumMeshes
[in] Index of the mesh on which to set material properties.
NumChannels
[in] Number of color channels to set in the mesh. Set to 1 to specify gray materials (R = G = B), or 3 to enable color bleeding effects.

If you intend to change this parameter, first set the albedo using another method such as ID3DXPRTEngine::SetPerTexelAlbedo or ID3DXPRTEngine::SetPerVertexAlbedo.
bSetAlbedo
[in] If TRUE, sets the albedo of the mesh to ppMaterials, overwriting all existing texel and vertex albedo values.

If FALSE, preserves all existing texel and vertex albedo values set by other methods; NumChannels must match the NumChannels parameter used to create the buffer in D3DXCreatePRTBuffer or D3DXCreatePRTBufferTex.
fLengthScale
[in] Scale of the 3-D scene relative to a 1-mm cube. Used for subsurface scattering computations.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXPRTEngine::SetPerTexelAlbedo Method

Sets an albedo value for each texel, overwriting previous albedo values.

Syntax

HRESULT SetPerTexelAlbedo(

    LPDIRECT3DTEXTURE9 pAlbedoTexture,
    UINT NumChannels,
    LPD3DXTEXTUREGUTTERHELPER pGH
);

Parameters

pAlbedoTexture
[in] Pointer to an IDirect3DTexture9 texture object in which to store albedo values.
NumChannels
[in] Number of color channels to set. Set to 1 to specify gray materials (R = G = B), or 3 to enable color bleeding effects.
pGH
[in] Optional pointer to an ID3DXTextureGutterHelper object. If not provided, a texture gutter helper object is created and destroyed internally.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Direct3D does not have enough display memory to perform the operation.
D3DERR_WASSTILLDRAWING | The previous blit operation that is transferring information to or from this surface is incomplete.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.


ID3DXPRTEngine::SetPerTexelNormal Method

Sets a normal vector for each texel in a texture object. This method is used to store vertex normal vectors from a mesh (or interpolated vertex normals if pixel-based precomputed radiance transfer (PRT) is being computed).

Syntax

HRESULT SetPerTexelNormal(

    LPDIRECT3DTEXTURE9 pNormalTexture
);

Parameters

pNormalTexture
[in] Pointer to an IDirect3DTexture9 texture object that serves as an object space normal map in which to store normal vectors. The texture must have the same dimensions as ID3DXPRTBuffer and must be able to store signed texture formats.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.


ID3DXPRTEngine::SetPerVertexAlbedo Method

Sets an albedo value for each mesh vertex, overwriting previous albedo values.

Syntax

HRESULT SetPerVertexAlbedo(

    const VOID *pDataIn,
    UINT NumChannels,
    UINT Stride
);

Parameters

pDataIn
[in] Pointer to FLOAT albedo data of the first sample.
NumChannels
[in] Number of color channels to set. Set to 1 to specify gray materials (R = G = B), or 3 to enable color bleeding effects.
Stride
[in] Stride in bytes needed to get to next sample's albedo value. See Width vs. Pitch.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXPRTEngine::SetSamplingInfo Method

Sets sampling properties used by the precomputed radiance transfer (PRT) simulator.

Syntax

HRESULT SetSamplingInfo(

    UINT NumRays,
    BOOL UseSphere,
    BOOL UseCosine,
    BOOL Adaptive,
    FLOAT AdaptiveThresh
);

Parameters

NumRays
[in] Number of light rays to direct at each sample. Must be greater than zero.
UseSphere
[in] If TRUE, samples will be computed over a full sphere. If FALSE, samples will be computed over a hemisphere.
UseCosine
[in] If TRUE, use a cosine weighting of samples. If both UseCosine and UseSphere are TRUE, the method will fail and an error will be returned.
Adaptive
[in] Must be FALSE. Adaptive sampling is currently not implemented.
AdaptiveThresh
[in] Ignored.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXRenderToEnvMap Interface

The ID3DXRenderToEnvMap interface is used to generalize the process of rendering to environment maps.

ID3DXRenderToEnvMap Members

BeginCube | Initiate the rendering of a cubic environment map.
BeginHemisphere | Initiate the rendering of a hemispheric environment map.
BeginParabolic | Initiate the rendering of a parabolic environment map.
BeginSphere | Initiate the rendering of a spherical environment map.
End | Restore all render targets and, if needed, compose all the rendered faces into the environment map surface.
Face | Initiate the drawing of each face of an environment map.
GetDesc | Retrieves the description of the render surface.
GetDevice | Retrieves the Microsoft Direct3D device associated with the environment map.
OnLostDevice | Releases all references to video memory resources and deletes all stateblocks.
OnResetDevice | Should be called after the device has been reset.

Remarks

An environment map is used to texture-map scene geometry to provide a more sophisticated scene without using complex geometry. This interface supports creating surfaces for the following kinds of geometry: cube, half sphere or hemispheric, parabolic, or sphere.

The ID3DXRenderToEnvMap interface is obtained by calling the D3DXCreateRenderToEnvMap function.

The LPD3DXRenderToEnvMap type is defined as a pointer to the ID3DXRenderToEnvMap interface.

typedef interface ID3DXRenderToEnvMap ID3DXRenderToEnvMap;
typedef interface ID3DXRenderToEnvMap *LPD3DXRenderToEnvMap;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXRenderToEnvMap::BeginCube Method

Initiate the rendering of a cubic environment map.

Syntax

HRESULT BeginCube(

    LPDIRECT3DCUBETEXTURE9 pCubeTex
);

Parameters

pCubeTex
[in] Pointer to an IDirect3DCubeTexture9 interface that represents the cube texture to which to render.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

See ID3DXRenderToEnvMap::Face to draw each of the 6 faces.

See Also

ID3DXRenderToEnvMap::End


ID3DXRenderToEnvMap::BeginHemisphere Method

Initiate the rendering of a hemispheric environment map.

Syntax

HRESULT BeginHemisphere(

    LPDIRECT3DTEXTURE9 pTexZPos,
    LPDIRECT3DTEXTURE9 pTexZNeg
);

Parameters

pTexZPos
[in] Pointer to an IDirect3DTexture9 interface that represents the positive texture render surface.
pTexZNeg
[in] Pointer to an IDirect3DTexture9 interface that represents the negative texture render surface.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_FAIL | An undetermined error occurred inside the Microsoft Direct3D subsystem.

Remarks

See ID3DXRenderToEnvMap::Face to draw the face.

See Also

ID3DXRenderToEnvMap::End


ID3DXRenderToEnvMap::BeginParabolic Method

Initiate the rendering of a parabolic environment map.

Syntax

HRESULT BeginParabolic(

    LPDIRECT3DTEXTURE9 pTexZPos,
    LPDIRECT3DTEXTURE9 pTexZNeg
);

Parameters

pTexZPos
[in] Pointer to an IDirect3DTexture9 interface that represents the positive render texture.
pTexZNeg
[in] Pointer to an IDirect3DTexture9 interface that represents the negative render texture.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_FAIL | An undetermined error occurred inside the Microsoft Direct3D subsystem.

Remarks

See ID3DXRenderToEnvMap::Face to draw the faces.

See Also

ID3DXRenderToEnvMap::End


ID3DXRenderToEnvMap::BeginSphere Method

Initiate the rendering of a spherical environment map.

Syntax

HRESULT BeginSphere(

    LPDIRECT3DTEXTURE9 pTex
);

Parameters

pTex
[in] Pointer to an IDirect3DTexture9 interface that represents the texture to which to render.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_FAIL | An undetermined error occurred inside the Microsoft Direct3D subsystem.

Remarks

See ID3DXRenderToEnvMap::Face to draw the face.

See Also

ID3DXRenderToEnvMap::End


ID3DXRenderToEnvMap::End Method

Restore all render targets and, if needed, compose all the rendered faces into the environment map surface.

Syntax

HRESULT End(

    DWORD MipFilter
);

Parameters

MipFilter
[in] A valid combination of one or more D3DX_FILTER flags.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXRenderToEnvMap::Face


ID3DXRenderToEnvMap::Face Method

Initiate the drawing of each face of an environment map.

Syntax

HRESULT Face(

    D3DCUBEMAP_FACES Face,
    DWORD MipFilter
);

Parameters

Face
[in] The first face of the environmental cube map. See D3DCUBEMAP_FACES.
MipFilter
[in] A valid combination of one or more D3DX_FILTER flags.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method must be called once for each type of environment map. The only exception is a cubic environment map which requires this method to be called six times, once for each face in D3DCUBEMAP_FACES. For more information, see Environment Mapping.


ID3DXRenderToEnvMap::GetDesc Method

Retrieves the description of the render surface.

Syntax

HRESULT GetDesc(

    D3DXRTE_DESC *pDesc
);

Parameters

pDesc
[out] Pointer to a D3DXRTE_DESC structure that describes the rendering surface.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXRenderToEnvMap::GetDevice Method

Retrieves the Microsoft Direct3D device associated with the environment map.

Syntax

HRESULT GetDevice(

    LPDIRECT3DDEVICE9 *ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface that represents the Direct3D device object associated with the environment map.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Note Calling this method increases the internal reference count on the IDirect3DDevice9 interface. Be sure to call IUnknown::Release when you are done using this IDirect3DDevice9 interface or you will have a memory leak.


ID3DXRenderToEnvMap::OnLostDevice Method

Releases all references to video memory resources and deletes all stateblocks.

Syntax

HRESULT OnLostDevice(VOID);

Return Value

This method returns S_OK.

Remarks

This method should be called whenever the device is lost. Before this object can be used again, the device must be reset and the ID3DXRenderToEnvMap::OnResetDevice method called.


ID3DXRenderToEnvMap::OnResetDevice Method

Should be called after the device has been reset.

Syntax

HRESULT OnResetDevice(VOID);

Return Value

This method returns S_OK.

Remarks

This method should be called after the device has been reset, before any other methods are called.


ID3DXRenderToSurface Interface

The ID3DXRenderToSurface interface is used to generalize the process of rendering to surfaces.

ID3DXRenderToSurface Members

BeginScene | Begins a scene.
EndScene | Ends a scene.
GetDesc | Retrieves the parameters of the render surface.
GetDevice | Retrieves the Microsoft Direct3D device associated with the render surface.
OnLostDevice | Releases all references to video memory resources and deletes all stateblocks.
OnResetDevice | Should be called after the device has been reset.

Remarks

Surfaces can be used in a variety of ways including render targets, off-screen rendering, or rendering to textures.

A surface can be configured using a separate viewport using the ID3DXRenderToSurface::BeginScene method, to provide a custom render view. If the surface is not a render target, a compatible render target is used, and the result is copied to the surface at the end of the scene.

The ID3DXRenderToSurface interface is obtained by calling the D3DXCreateRenderToSurface function.

The LPD3DXRENDERTOSURFACE type is defined as a pointer to the ID3DXRenderToSurface interface.

typedef interface ID3DXRenderToSurface ID3DXRenderToSurface;
typedef interface ID3DXRenderToSurface *LPD3DXRENDERTOSURFACE;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXRenderToSurface::BeginScene Method

Begins a scene.

Syntax

HRESULT BeginScene(

    LPDIRECT3DSURFACE9 pSurface,
    CONST D3DVIEWPORT9 *pViewport
);

Parameters

pSurface
[in] Pointer to an IDirect3DSurface9 interface, representing the render surface.
pViewport
[in] Pointer to a D3DVIEWPORT9 structure, describing the viewport for the scene.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

See Also

ID3DXRenderToSurface::EndScene


ID3DXRenderToSurface::EndScene Method

Ends a scene.

Syntax

HRESULT EndScene(

    DWORD MipFilter
);

Parameters

MipFilter
[in] Filter options, enumerated in D3DX_FILTER.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

See Also

ID3DXRenderToSurface::BeginScene


ID3DXRenderToSurface::GetDesc Method

Retrieves the parameters of the render surface.

Syntax

HRESULT GetDesc(

    D3DXRTS_DESC *pParameters
);

Parameters

pParameters
[out] Pointer to a D3DXRTS_DESC structure, describing the parameters of the render surface.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXRenderToSurface::GetDevice Method

Retrieves the Microsoft Direct3D device associated with the render surface.

Syntax

HRESULT GetDevice(

    LPDIRECT3DDEVICE9 *ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface, representing the Direct3D device object associated with the render surface.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Be sure to call IUnknown::Release when you are done using this IDirect3DDevice9 interface or you will have a memory leak.


ID3DXRenderToSurface::OnLostDevice Method

Releases all references to video memory resources and deletes all stateblocks.

Syntax

HRESULT OnLostDevice(VOID);

Return Value

This method returns S_OK.

Remarks

This method should be called whenever the device is lost. Before this object can be used again, the device must be reset and the ID3DXRenderToSurface::OnResetDevice method called.


ID3DXRenderToSurface::OnResetDevice Method

Should be called after the device has been reset.

Syntax

HRESULT OnResetDevice(VOID);

Return Value

This method returns S_OK.

Remarks

This method should be called after the device has been reset, before any other methods are called.


ID3DXSaveUserData Interface

This interface is implemented by the application to save any additional user data embedded in .x files. An instance of this interface is passed to D3DXSaveMeshHierarchyToFile, and D3DX calls the appropriate method on this interface every time the appropriate data is encountered. For example, for each frame object in the .x file, ID3DXSaveUserData::AddFrameChildData is called and passed the child data.

ID3DXSaveUserData Members

AddFrameChildData | Add child data to the frame.
AddMeshChildData | Add child data to the mesh.
AddTopLevelDataObjectsPost | Add a top level object after the frame hierarchy.
AddTopLevelDataObjectsPre | Add a top level object before the frame hierarchy.
RegisterTemplates | A callback for the user to register a .x file template.
SaveTemplates | A callback for the user to save a .x file template.

Remarks

The LPD3DXSAVEUSERDATA type is defined as a pointer to this interface.

typedef interface ID3DXSaveUserData ID3DXSaveUserData;
typedef interface ID3DXSaveUserData *LPD3DXSAVEUSERDATA;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | Nothing
Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXSaveUserData::AddFrameChildData Method

Add child data to the frame.

Syntax

HRESULT AddFrameChildData(

    const D3DXFRAME *pFrame,
    LPD3DXFILESAVEOBJECT pXofSave,
    LPD3DXFILESAVEDATA pXofFrameData
);

Parameters

pFrame
[in] Pointer to a mesh container. See D3DXFRAME.
pXofSave
[in] Pointer to a .x file save object. Use the pointer to call ID3DXFileSaveObject::AddDataObject to add a child data object. Do not save the data with ID3DXFileSaveObject::Save.
pXofFrameData
[in] Pointer to a .x file data node. Use the pointer to call ID3DXFileSaveData::AddDataObject to add a child data object.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

Remarks

ID3DXSaveUserData::RegisterTemplates and ID3DXSaveUserData::SaveTemplates provide a mechanism for adding a template to a .x file for saving user data.


ID3DXSaveUserData::AddMeshChildData Method

Add child data to the mesh.

Syntax

HRESULT AddMeshChildData(

    const D3DXMESHCONTAINER *pMeshContainer,
    LPD3DXFILESAVEOBJECT pXofSave,
    LPD3DXFILESAVEDATA pXofMeshData
);

Parameters

pMeshContainer
[in] Pointer to a mesh container. See D3DXMESHCONTAINER.
pXofSave
[in] Pointer to a .x file save object. Use the pointer to call ID3DXFileSaveObject::AddDataObject to add a child data object. Do not save the data with ID3DXFileSaveObject::Save.
pXofMeshData
[in] Pointer to a .x file data node. Use the pointer to call ID3DXFileSaveData::AddDataObject to add a child data object.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.


ID3DXSaveUserData::AddTopLevelDataObjectsPost Method

Add a top level object after the frame hierarchy.

Syntax

HRESULT AddTopLevelDataObjectsPost(

    LPD3DXFILESAVEOBJECT pXofSave
);

Parameters

pXofSave
[in] Pointer to a .x file save object. Use this pointer to call IDirectXFileSaveObject::CreateDataObject to create the data object to be saved. Then call IDirectXFileSaveObject::SaveData to save the data.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.


ID3DXSaveUserData::AddTopLevelDataObjectsPre Method

Add a top level object before the frame hierarchy.

Syntax

HRESULT AddTopLevelDataObjectsPre(

    LPD3DXFILESAVEOBJECT pXofSave
);

Parameters

pXofSave
[in] Pointer to a .x file save object. Use this pointer to call IDirectXFileSaveObject::CreateDataObject to create the data object to be saved. Then call IDirectXFileSaveObject::SaveData to save the data.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.


ID3DXSaveUserData::RegisterTemplates Method

A callback for the user to register a .x file template.

Syntax

HRESULT RegisterTemplates(

    LPD3DXFILE pXFileApi
);

Parameters

pXFileApi
[in] Use this pointer to register user-defined .x file templates. See ID3DXFile. Do not use this parameter to add data objects.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

Remarks

ID3DXSaveUserData::RegisterTemplates and ID3DXSaveUserData::SaveTemplates provide a mechanism for adding a template to a .x file for saving user data.


ID3DXSaveUserData::SaveTemplates Method

A callback for the user to save a .x file template.

Syntax

HRESULT SaveTemplates(

    LPD3DXFILESAVEOBJECT pXofSave
);

Parameters

pXofSave
[in] Pointer to a .x file save object. Do not use this parameter to add data objects. See ID3DXFileSaveObject.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR, as this will cause D3DXLoadMeshHierarchyFromX to fail also, and return the error.

Remarks

ID3DXSaveUserData::RegisterTemplates and ID3DXSaveUserData::SaveTemplates provide a mechanism for adding a template to a .x file for saving user data.


ID3DXSkinInfo Interface

Applications use the methods of the ID3DXSkinInfo interface to manipulate bone matrices, which are used to skin vertex data for animation. This interface is no longer strictly tied to ID3DXMesh and can be used to skin any set of vertex data.

ID3DXSkinInfo Members

Clone | Clones a skin info object.
ConvertToBlendedMesh | Takes a mesh and returns a new mesh with per-vertex blend weights and a bone combination table. The table describes which bones affect which subsets of the mesh.
ConvertToIndexedBlendedMesh | Takes a mesh and returns a new mesh with per-vertex blend weights, indices, and a bone combination table. The table describes which bone palettes affect which subsets of the mesh.
FindBoneVertexInfluenceIndex | Retrieves the index of the bone influence affecting a single vertex.
GetBoneInfluence | Gets the vertices and weights that a bone influences.
GetBoneName | Gets the bone name, from the bone index.
GetBoneOffsetMatrix | Gets the bone offset matrix.
GetBoneVertexInfluence | Retrieves the blend factor and vertex affected by a specified bone influence.
GetDeclaration | Gets the vertex declaration.
GetFVF | Gets the fixed function vertex value.
GetMaxFaceInfluences | Gets the maximum face influences in a triangle mesh with the specified index buffer.
GetMaxVertexInfluences | Gets the maximum number of influences for any vertex in the mesh.
GetMinBoneInfluence | Gets the minimum bone influence. Influence values smaller than this are ignored.
GetNumBoneInfluences | Gets the number of influences for a bone.
GetNumBones | Gets the number of bones.
Remap | Updates bone influence information to match vertices after they are reordered. This method should be called if the target vertex buffer has been reordered externally.
SetBoneInfluence | Sets the influence value for a bone.
SetBoneName | Sets the bone name.
SetBoneOffsetMatrix | Sets the bone offset matrix.
SetBoneVertexInfluence | Sets an influence value of a bone on a single vertex.
SetDeclaration | Sets the vertex declaration.
SetFVF | Sets the flexible vertex format (FVF) type.
SetMinBoneInfluence | Sets the minimum bone influence. Influence values smaller than this are ignored.
UpdateSkinnedMesh | Applies software skinning to the target vertices based on the current matrices.

Remarks

Create a ID3DXSkinInfo interface with D3DXCreateSkinInfo, D3DXCreateSkinInfoFromBlendedMesh, or D3DXCreateSkinInfoFVF.

The LPD3DXSKININFO type is defined as a pointer to the ID3DXSkinInfo interface.

typedef struct ID3DXSkinInfo *LPD3DXSKININFO;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXSkinInfo::Clone Method

Clones a skin info object.

Syntax

HRESULT Clone(

    LPD3DXSKININFO *ppSkinInfo
);

Parameters

ppSkinInfo
[in, out] Address of a pointer to an ID3DXSkinInfo object, which will contain the cloned object if the method is successful.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXSkinInfo::ConvertToBlendedMesh Method

Takes a mesh and returns a new mesh with per-vertex blend weights and a bone combination table. The table describes which bones affect which subsets of the mesh.

Syntax

HRESULT ConvertToBlendedMesh(

    LPD3DXMESH pMesh,
    DWORD Options,
    const DWORD *pAdjacencyIn,
    LPDWORD pAdjacencyOut,
    DWORD *pFaceRemap,
    LPD3DXBUFFER *ppVertexRemap,
    DWORD *pMaxVertexInfl,
    DWORD *pNumBoneCombinations,
    LPD3DXBUFFER *ppBoneCombinationTable,
    LPD3DXMESH *ppMesh
);

Parameters

pMesh
[in] Input mesh. See ID3DXMesh.
Options
[in] Currently unused.
pAdjacencyIn
[in] Input mesh adjacency information.
pAdjacencyOut
[in] Output mesh adjacency information.
pFaceRemap
[out] Pointer to a destination buffer containing the new index for each face. This parameter is optional, NULL may be used.
ppVertexRemap
[out] Address of a pointer to an ID3DXBuffer interface, which contains the new index for each vertex. This parameter is optional, NULL may be used.
pMaxVertexInfl
[out] Pointer to a DWORD that will contain the maximum number of bone influences required per vertex for this skinning method.
pNumBoneCombinations
[out] Pointer to the number of bones in the bone combination table.
ppBoneCombinationTable
[out] Pointer to the bone combination table. The data is organized in a D3DXBONECOMBINATION structure.
ppMesh
[out] Pointer to the new mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Each element in the remap arrays specifies the previous index for that position. For example, if a vertex was in position 3 but has been remapped to position 5, then the fifth element of pVertexRemap will contain 3.


ID3DXSkinInfo::ConvertToIndexedBlendedMesh Method

Takes a mesh and returns a new mesh with per-vertex blend weights, indices, and a bone combination table. The table describes which bone palettes affect which subsets of the mesh.

Syntax

HRESULT ConvertToIndexedBlendedMesh(

    LPD3DXMESH pMesh,
    DWORD Options,
    DWORD paletteSize,
    const DWORD *pAdjacencyIn,
    LPDWORD pAdjacencyOut,
    DWORD *pFaceRemap,
    LPD3DXBUFFER *ppVertexRemap,
    DWORD *pMaxVertexInfl,
    DWORD *pNumBoneCombinations,
    LPD3DXBUFFER *ppBoneCombinationTable,
    LPD3DXMESH *ppMesh
);

Parameters

pMesh
[in] The input mesh. See ID3DXMesh.
Options
[in] Currently unused.
paletteSize
[in] Number of bone matrices available for matrix palette skinning.
pAdjacencyIn
[in] Input mesh adjacency information.
pAdjacencyOut
[in] Output mesh adjacency information.
pFaceRemap
[out] Pointer to a destination buffer containing the new index for each face. This parameter is optional, NULL may be used.
ppVertexRemap
[out] Address of a pointer to an ID3DXBuffer interface, which contains the new index for each vertex. This parameter is optional, NULL may be used.
pMaxVertexInfl
[out] Pointer to a DWORD that will contain the maximum number of bone influences required per vertex for this skinning method.
pNumBoneCombinations
[out] Pointer to the number of bones in the bone combination table.
ppBoneCombinationTable
[out] Pointer to the bone combination table. The data is organized in a D3DXBONECOMBINATION structure.
ppMesh
[out] Pointer to the new mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Each element in the remap arrays specifies the previous index for that position. For example, if a vertex was in position 3 but has been remapped to position 5, then the fifth element of pVertexRemap will contain 3.


ID3DXSkinInfo::FindBoneVertexInfluenceIndex Method

Retrieves the index of the bone influence affecting a single vertex.

Syntax

HRESULT FindBoneVertexInfluenceIndex(

    DWORD boneNum,
    DWORD vertexNum,
    DWORD *pInfluenceIndex
);

Parameters

boneNum
[in] Index of the bone. Must be between 0 and the number of bones.
vertexNum
[in] Index of the vertex for which the bone influence is to be found. Must be between 0 and the number of vertices in the mesh.
pInfluenceIndex
[in, out] Pointer to the index of the bone influence that affects vertexNum.

Return Value

If the method succeeds, the return value is S_OK. If the specified bone does not influence the given vertex, S_FALSE is returned.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXSkinInfo::GetBoneVertexInfluence, ID3DXSkinInfo::SetBoneVertexInfluence, ID3DXSkinInfo::GetBoneInfluence


ID3DXSkinInfo::GetBoneInfluence Method

Gets the vertices and weights that a bone influences.

Syntax

HRESULT GetBoneInfluence(

    DWORD Bone,
    DWORD *vertices,
    FLOAT *weights
);

Parameters

Bone
[in] Bone number.
vertices
[in, out] Get the array of vertices influenced by a bone.
weights
[in, out] Get the array of weights influenced by a bone.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Use ID3DXSkinInfo::GetNumBoneInfluences to find out how many vertices the bone influences.

See Also

ID3DXSkinInfo::SetBoneInfluence


ID3DXSkinInfo::GetBoneName Method

Gets the bone name, from the bone index.

Syntax

LPCSTR GetBoneName(

    DWORD Bone
);

Parameters

Bone
[in] Bone number.

Return Value

Returns the bone name. Do not free this string.

See Also

ID3DXSkinInfo::SetBoneName, ID3DXSkinInfo::GetNumBones


ID3DXSkinInfo::GetBoneOffsetMatrix Method

Gets the bone offset matrix.

Syntax

LPD3DXMATRIX GetBoneOffsetMatrix(

    DWORD Bone
);

Parameters

Bone
[in] Bone number.

Return Value

Returns a pointer to the bone offset matrix. Do not free this pointer.

See Also

ID3DXSkinInfo::SetBoneOffsetMatrix, ID3DXSkinInfo::GetNumBones


ID3DXSkinInfo::GetBoneVertexInfluence Method

Retrieves the blend factor and vertex affected by a specified bone influence.

Syntax

HRESULT GetBoneVertexInfluence(

    DWORD boneNum,
    DWORD influenceNum,
    FLOAT *pWeight,
    DWORD *pVertexNum
);

Parameters

boneNum
[in] Index of the bone. Must be between 0 and the number of bones.
influenceNum
[in] Index of the influence array of the specified bone.
pWeight
[in, out] Pointer to the blend factor influenced by influenceNum.
pVertexNum
[in, out] Pointer to the vertex influenced by influenceNum.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXSkinInfo::SetBoneVertexInfluence, ID3DXSkinInfo::FindBoneVertexInfluenceIndex, ID3DXSkinInfo::GetBoneInfluence


ID3DXSkinInfo::GetDeclaration Method

Gets the vertex declaration.

Syntax

HRESULT GetDeclaration(

    D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

Declaration
[in, out] Array of D3DVERTEXELEMENT9 elements describing the vertex format of the mesh vertices. The upper limit of this declarator array is MAX_FVF_DECL_SIZE. The vertex element array ends with the D3DDECL_END macro.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The array of elements includes the D3DDECL_END macro, which ends the declaration.

See Also

ID3DXSkinInfo::SetDeclaration


ID3DXSkinInfo::GetFVF Method

Gets the fixed function vertex value.

Syntax

DWORD GetFVF(VOID);

Return Value

Returns the flexible vertex format (FVF) codes.

Remarks

This method can return 0 if the vertex format cannot be mapped directly to an FVF code. This will occur for a mesh created from a vertex declaration that doesn't have the same order and elements supported by the FVF codes.

See Also

ID3DXSkinInfo::SetFVF


ID3DXSkinInfo::GetMaxFaceInfluences Method

Gets the maximum face influences in a triangle mesh with the specified index buffer.

Syntax

HRESULT GetMaxFaceInfluences(

    LPDIRECT3DINDEXBUFFER9 pIB,
    DWORD NumFaces,
    DWORD *maxFaceInfluences
);

Parameters

pIB
[in] Pointer to the index buffer that contains the mesh index data.
NumFaces
[in] Number of faces in the mesh.
maxFaceInfluences
[in] Pointer to the maximum face influences.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXSkinInfo::GetMaxVertexInfluences Method

Gets the maximum number of influences for any vertex in the mesh.

Syntax

HRESULT GetMaxVertexInfluences(

    DWORD *maxVertexInfluences
);

Parameters

maxVertexInfluences
[in] Pointer to the maximum vertex influence.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXSkinInfo::GetMinBoneInfluence Method

Gets the minimum bone influence. Influence values smaller than this are ignored.

Syntax

FLOAT GetMinBoneInfluence(VOID);

Return Value

Returns the minimum bone influence value.

See Also

ID3DXSkinInfo::SetMinBoneInfluence


ID3DXSkinInfo::GetNumBoneInfluences Method

Gets the number of influences for a bone.

Syntax

DWORD GetNumBoneInfluences(

    DWORD bone
);

Parameters

bone
[in] Bone number.

Return Value

Returns the number of influences for a bone.


ID3DXSkinInfo::GetNumBones Method

Gets the number of bones.

Syntax

DWORD GetNumBones(VOID);

Return Value

Returns the number of bones.


ID3DXSkinInfo::Remap Method

Updates bone influence information to match vertices after they are reordered. This method should be called if the target vertex buffer has been reordered externally.

Syntax

HRESULT Remap(

    DWORD NumVertices,
    DWORD *pVertexRemap
);

Parameters

NumVertices
[in] Number of vertices to remap.
pVertexRemap
[in] Array of DWORDS whose length is specified by NumVertices.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Each element in pVertexRemap specifies the previous vertex index for that position. For example, if a vertex was in position 3 but has been remapped to position 5, then the fifth element of pVertexRemap should contain 3. The vertex remap array returned by ID3DXMesh::Optimize can be used.


ID3DXSkinInfo::SetBoneInfluence Method

Sets the influence value for a bone.

Syntax

HRESULT SetBoneInfluence(

    DWORD Bone,
    DWORD numInfluences,
    CONST DWORD *vertices,
    CONST FLOAT *weights
);

Parameters

Bone
[in] Bone number.
numInfluences
[in] Number of influences.
vertices
[in] The array of vertices influenced by a bone.
weights
[in] The array of weights influenced by a bone.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXSkinInfo::GetBoneInfluence, ID3DXSkinInfo::GetNumBoneInfluences


ID3DXSkinInfo::SetBoneName Method

Sets the bone name.

Syntax

HRESULT SetBoneName(

    DWORD Bone,
    LPCSTR pName
);

Parameters

Bone
[in] Bone number
pName
[in] Bone name

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Bone names are returned by D3DXLoadMeshFromXof.

See Also

ID3DXSkinInfo::GetBoneName


ID3DXSkinInfo::SetBoneOffsetMatrix Method

Sets the bone offset matrix.

Syntax

HRESULT SetBoneOffsetMatrix(

    DWORD Bone,
    const D3DXMATRIX *pBoneTransform
);

Parameters

Bone
[in] Bone number.
pBoneTransform
[in] Pointer to the bone offset matrix.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Bone names are returned by D3DXLoadMeshFromXof.

See Also

ID3DXSkinInfo::GetBoneOffsetMatrix


ID3DXSkinInfo::SetBoneVertexInfluence Method

Sets an influence value of a bone on a single vertex.

Syntax

HRESULT SetBoneVertexInfluence(

    DWORD boneNum,
    DWORD influenceNum,
    FLOAT weight
);

Parameters

boneNum
[in] Index of the bone. Must be between 0 and the number of bones.
influenceNum
[in] Index of the influence array of the specified bone.
weight
[in] Blend factor of the specified bone influence.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXSkinInfo::GetBoneVertexInfluence, ID3DXSkinInfo::FindBoneVertexInfluenceIndex, ID3DXSkinInfo::GetBoneInfluence


ID3DXSkinInfo::SetDeclaration Method

Sets the vertex declaration.

Syntax

HRESULT SetDeclaration(

    const D3DVERTEXELEMENT9 *pDeclaration
);

Parameters

pDeclaration
[in] Pointer to an array of D3DVERTEXELEMENT9 elements.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXSkinInfo::GetDeclaration


ID3DXSkinInfo::SetFVF Method

Sets the flexible vertex format (FVF) type.

Syntax

HRESULT SetFVF(

    DWORD FVF
);

Parameters

FVF
[in] Flexible vertex format. See D3DFVF.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXSkinInfo::SetMinBoneInfluence Method

Sets the minimum bone influence. Influence values smaller than this are ignored.

Syntax

HRESULT SetMinBoneInfluence(

    FLOAT MinInfl
);

Parameters

MinInfl
[in] Minimum influence value. Influence values smaller than this are ignored.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXSkinInfo::GetMinBoneInfluence


ID3DXSkinInfo::UpdateSkinnedMesh Method

Applies software skinning to the target vertices based on the current matrices.

Syntax

HRESULT UpdateSkinnedMesh(

    const D3DXMATRIX *pBoneTransforms,
    const D3DXMATRIX *pBoneInvTransposeTransforms,
    LPCVOID pVerticesSrc,
    PVOID pVerticesDst
);

Parameters

pBoneTransforms
[in] Bone transform matrix.
pBoneInvTransposeTransforms
[in] Inverse transpose of the bone transform matrix.
pVerticesSrc
[in] Pointer to the buffer containing the source vertices.
pVerticesDst
[in] Pointer to the buffer containing the destination vertices.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When used to skin vertices with two position elements, this method skins the second position element with the inverse of the bone instead of the bone itself.


ID3DXSPMesh Interface

Applications use the methods of the ID3DXSPMesh interface to manipulate simplification mesh objects. A simplification mesh is used to simplify a given mesh to a lower number of faces.

ID3DXSPMesh Members

CloneMesh | Clones a mesh using a declarator.
CloneMeshFVF | Clones a mesh using a flexible vertex format (FVF) code.
ClonePMesh | Clones a progressive mesh using a declarator.
ClonePMeshFVF | Clones a progressive mesh using a FVF code.
GetDeclaration | Retrieves a declaration describing the vertices in the mesh.
GetDevice | Retrieves the device object associated with the simplification mesh.
GetFVF | Retrieves the FVF of the vertices in the simplification mesh.
GetMaxFaces | Retrieves the maximum number of faces that the simplification mesh supports.
GetMaxVertices | Retrieves the maximum number of vertices that the simplification mesh supports.
GetNumFaces | Retrieves the number of faces in the simplification mesh.
GetNumVertices | Retrieves the number of vertices in the simplification mesh.
GetOptions | Retrieves the mesh options enabled for this simplification mesh at creation time.
GetVertexAttributeWeights | Retrieves the per-vertex attribute weights used to create the ID3DXSPMesh object.
GetVertexWeights | Retrieves the per-vertex weights used to create the ID3DXSPMesh object.
ReduceFaces | Reduces the number of faces in a simplification mesh.
ReduceVertices | Reduces the number of vertices in a simplification mesh.

Remarks

The ID3DXSPMesh interface is obtained by calling the D3DXCreateSPMesh function.

The LPD3DXSPMESH type is defined as a pointer to the ID3DXSPMesh interface.

typedef struct ID3DXSPMesh *LPD3DXSPMESH;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Mesh Functions


ID3DXSPMesh::CloneMesh Method

Clones a mesh using a declarator.

Syntax

HRESULT CloneMesh(

    DWORD Options,
    CONST D3DVERTEXELEMENT9 *pDeclaration,
    LPDIRECT3DDEVICE9 pDevice,
    DWORD *pAdjacencyOut,
    DWORD *pVertexRemapOut,
    LPD3DXMESH *ppCloneMesh
);

Parameters

Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
pDeclaration
[in] Array of D3DVERTEXELEMENT9 elements, specifying the vertex format for the vertices in the output mesh.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device object associated with the mesh.
pAdjacencyOut
[out] Pointer to an array of three DWORDs per face, specifying the three neighbors for each face in the source mesh.
pVertexRemapOut
[out] Pointer to an array containing the index for each vertex.
ppCloneMesh
[out] Address of a pointer to an ID3DXPMesh interface, representing the cloned mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

See Also

ID3DXSPMesh::GetDeclaration, D3DXDeclaratorFromFVF


ID3DXSPMesh::CloneMeshFVF Method

Clones a mesh using a flexible vertex format (FVF) code.

Syntax

HRESULT CloneMeshFVF(

    DWORD Options,
    DWORD FVF,
    LPDIRECT3DDEVICE9 pD3DDevice,
    DWORD *pAdjacencyOut,
    DWORD *pVertexRemapOut,
    LPD3DXMESH *ppCloneMesh
);

Parameters

Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
FVF
[in] Combination of FVF codes, specifying the vertex format for the vertices in the output mesh. For the values of the codes, see D3DFVF.
pD3DDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device object associated with the mesh.
pAdjacencyOut
[out] Pointer to an array of three DWORDs per face, specifying the three neighbors for each face in the source mesh.
pVertexRemapOut
[out] Pointer to an array containing the index for each vertex.
ppCloneMesh
[out] Address of a pointer to an ID3DXPMesh interface, representing the cloned mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

CloneMeshFVF can be used to convert a mesh from one FVF to another.

See Also

ID3DXSPMesh::GetFVF, D3DXFVFFromDeclarator


ID3DXSPMesh::ClonePMesh Method

Clones a progressive mesh using a declarator.

Syntax

HRESULT ClonePMesh(

    DWORD Options,
    CONST D3DVERTEXELEMENT9 *pDeclaration,
    LPDIRECT3DDEVICE9 pD3DDevice,
    DWORD *pVertexRemapOut,
    FLOAT *pErrorsByFace,
    LPD3DXPMESH *ppCloneMesh
);

Parameters

Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh. The following flags are defined.
pDeclaration
[in] Array of D3DVERTEXELEMENT9 elements describing the vertex format for the returned mesh. This parameter must map directly to an flexible vertex format (FVF).
pD3DDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device object associated with the mesh.
pVertexRemapOut
[out] Pointer to an array containing the index for each vertex.
pErrorsByFace
[out] Pointer to an array containing error values.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXPMesh interface, representing the cloned progressive mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_CANNOTATTRSORT | Attribute sort (D3DXMESHOPT_ATTRSORT) is not supported as an optimization technique.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXSPMesh::ClonePMeshFVF Method

Clones a progressive mesh using a flexible vertex format (FVF) code.

Syntax

HRESULT ClonePMeshFVF(

    DWORD Options,
    DWORD FVF,
    LPDIRECT3DDEVICE9 pD3DDevice,
    DWORD *pVertexRemapOut,
    FLOAT *pErrorsByFace,
    LPD3DXPMESH *ppCloneMesh
);

Parameters

Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
FVF
[in] Combination of FVF codes, specifying the vertex format for the vertices in the output mesh. For the values of the codes, see D3DFVF.
pD3DDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device object associated with the mesh.
pVertexRemapOut
[out] Pointer to an array containing the index for each vertex.
pErrorsByFace
[out] Pointer to an array containing error values.
ppCloneMesh
[out] Address of a pointer to an ID3DXPMesh interface, representing the cloned progressive mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_CANNOTATTRSORT | Attribute sort (D3DXMESHOPT_ATTRSORT) is not supported as an optimization technique.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

ClonePMeshFVF can be used to convert a progressive mesh from one FVF to another.

See Also

ID3DXSPMesh::GetFVF, D3DXFVFFromDeclarator


ID3DXSPMesh::GetDeclaration Method

Retrieves a declaration describing the vertices in the mesh.

Syntax

HRESULT GetDeclaration(

    D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

Declaration
[out] Array of D3DVERTEXELEMENT9 elements describing the vertex format of the mesh vertices. The upper limit of this declarator array is MAX_FVF_DECL_SIZE. The vertex element array ends with the D3DDECL_END macro.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The array of elements includes the D3DDECL_END macro, which ends the declaration.

See Also

ID3DXSPMesh::GetFVF


ID3DXSPMesh::GetDevice Method

Retrieves the device object associated with the simplification mesh.

Syntax

HRESULT GetDevice(

    LPDIRECT3DDEVICE9 *ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface, representing the Microsoft Direct3D device object associated with the simplification mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Be sure to call IUnknown::Release when you are done using this IDirect3DDevice9 interface or you will have a memory leak.


ID3DXSPMesh::GetFVF Method

Retrieves the flexible vertex format (FVF) of the vertices in the simplification mesh.

Syntax

DWORD GetFVF(VOID);

Return Value

Returns an FVF that describes the vertex format of the vertices in the simplification mesh.

Remarks

This method can return 0 if the vertex format cannot be mapped directly to an FVF code. This will occur for a mesh created from a vertex declaration that doesn't have the same order and elements supported by the FVF codes.

See Also

ID3DXSPMesh::GetDeclaration


ID3DXSPMesh::GetMaxFaces Method

Retrieves the maximum number of faces that the simplification mesh supports.

Syntax

DWORD GetMaxFaces(VOID);

Return Value

Returns the maximum number of faces in the original mesh.


ID3DXSPMesh::GetMaxVertices Method

Retrieves the maximum number of vertices that the simplification mesh supports.

Syntax

DWORD GetMaxVertices(VOID);

Return Value

Returns the maximum number of vertices in the original mesh.


ID3DXSPMesh::GetNumFaces Method

Retrieves the number of faces in the simplification mesh.

Syntax

DWORD GetNumFaces(VOID);

Return Value

Returns the number of faces in the simplification mesh.


ID3DXSPMesh::GetNumVertices Method

Retrieves the number of vertices in the simplification mesh.

Syntax

DWORD GetNumVertices(VOID);

Return Value

Returns the number of vertices in the simplification mesh.


ID3DXSPMesh::GetOptions Method

Retrieves the mesh options enabled for this simplification mesh at creation time.

Syntax

DWORD GetOptions(VOID);

Return Value

Returns a combination of one or more flags from the D3DXMESH enumeration, indicating the options enabled for this mesh at creation time.


ID3DXSPMesh::GetVertexAttributeWeights Method

Retrieves the per-vertex attribute weights used to create the ID3DXSPMesh object.

Syntax

HRESULT GetVertexAttributeWeights(

    LPD3DXATTRIBUTEWEIGHTS pVertexAttributeWeights
);

Parameters

pVertexAttributeWeights
[out] Array of vertex attribute weights. See D3DXATTRIBUTEWEIGHTS.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

See Also

D3DXCreateSPMesh


ID3DXSPMesh::GetVertexWeights Method

Retrieves the per-vertex weights used to create the ID3DXSPMesh object.

Syntax

HRESULT GetVertexWeights(

    FLOAT *pVertexWeights
);

Parameters

pVertexWeights
[in, out] Array of floats that will be filled with vertex weights. Each float contains one vertex. The array should be large enough to handle the maximum number of vertices in the original ID3DXMesh (which was used to create the simplification mesh).

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

See Also

D3DXCreateSPMesh


ID3DXSPMesh::ReduceFaces Method

Reduces the number of faces in a simplification mesh.

Syntax

HRESULT ReduceFaces(

    DWORD Faces
);

Parameters

Faces
[in] Number of faces to which to reduce the primitive count.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method performs edge collapses to reduce the number of primitives to the value specified in Faces. It is not always possible to reduce a mesh to the requested value due to certain restrictions.


ID3DXSPMesh::ReduceVertices Method

Reduces the number of vertices in a simplification mesh.

Syntax

HRESULT ReduceVertices(

    DWORD Vertices
);

Parameters

Vertices
[in] Number of vertices to which to reduce the primitive count.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method performs edge collapses to reduce the number of primitives to the value specified in Vertices. It is not always possible to reduce a mesh to the requested value due to certain restrictions.


ID3DXSprite Interface

The ID3DXSprite interface provides a set of methods that simplify the process of drawing sprites using Microsoft Direct3D.

ID3DXSprite Members

Begin | Prepares a device for drawing sprites.
Draw | Adds a sprite to the list of batched sprites.
End | Calls ID3DXSprite::Flush and restores the device state to how it was before ID3DXSprite::Begin was called.
Flush | Forces all batched sprites to be submitted to the device. Device states remain as they were after the last call to ID3DXSprite::Begin. The list of batched sprites is then cleared.
GetDevice | Retrieves the device associated with the sprite object.
GetTransform | Gets the sprite transform.
OnLostDevice | Releases all references to video memory resources and deletes all stateblocks.
OnResetDevice | Should be called after the device has been reset.
SetTransform | Sets the sprite transform.
SetWorldViewLH | Sets the left-handed world-view transform for a sprite. A call to this method is required before billboarding or sorting sprites.
SetWorldViewRH | Sets the right-handed world-view transform for a sprite. A call to this method is required before billboarding or sorting sprites.

Remarks

The ID3DXSprite interface is obtained by calling the D3DXCreateSprite function.

The application typically first calls ID3DXSprite::Begin, which allows control over the device render state, alpha blending, and sprite transformation and sorting. Then for each sprite to be displayed, call ID3DXSprite::Draw. ID3DXSprite::Draw can be called repeatedly to store any number of sprites. To display the batched sprites to the device, call ID3DXSprite::End or ID3DXSprite::Flush.

The LPD3DXSPRITE type is defined as a pointer to the ID3DXSprite interface.

typedef interface ID3DXSprite ID3DXSprite;
typedef interface ID3DXSprite *LPD3DXSPRITE;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXSprite::Begin Method

Prepares a device for drawing sprites.

Syntax

HRESULT Begin(

    DWORD Flags
);

Parameters

Flags
[in] Combination of zero or more flags that describe sprite rendering options. For this method, the valid flags are:
  • D3DXSPRITE_ALPHABLEND
  • D3DXSPRITE_BILLBOARD
  • D3DXSPRITE_DONOTMODIFY_RENDERSTATE
  • D3DXSPRITE_DONOTSAVESTATE
  • D3DXSPRITE_OBJECTSPACE
  • D3DXSPRITE_SORT_DEPTH_BACKTOFRONT
  • D3DXSPRITE_SORT_DEPTH_FRONTTOBACK
  • D3DXSPRITE_SORT_TEXTURE
For a description of the flags and for information on how to control device state capture and device view transforms, see D3DXSPRITE.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

This method must be called from inside a IDirect3DDevice9::BeginScene . . . IDirect3DDevice9::EndScene sequence. ID3DXSprite::Begin cannot be used as a substitute for either IDirect3DDevice9::BeginScene or ID3DXRenderToSurface::BeginScene.

This method will set the following states on the device.

Render States:

Type (D3DRENDERSTATETYPE) | Value
D3DRS_ALPHABLENDENABLE | TRUE
D3DRS_ALPHAFUNC | D3DCMP_GREATER
D3DRS_ALPHAREF | 0x00
D3DRS_ALPHATESTENABLE | AlphaCmpCaps
D3DRS_BLENDOP | D3DBLENDOP_ADD
D3DRS_CLIPPING | TRUE
D3DRS_CLIPPLANEENABLE | FALSE
D3DRS_COLORWRITEENABLE | D3DCOLORWRITEENABLE_ALPHA | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_RED
D3DRS_CULLMODE | D3DCULL_NONE
D3DRS_DESTBLEND | D3DBLEND_INVSRCALPHA
D3DRS_DIFFUSEMATERIALSOURCE | D3DMCS_COLOR1
D3DRS_ENABLEADAPTIVETESSELLATION | FALSE
D3DRS_FILLMODE | D3DFILL_SOLID
D3DRS_FOGENABLE | FALSE
D3DRS_INDEXEDVERTEXBLENDENABLE | FALSE
D3DRS_LIGHTING | FALSE
D3DRS_RANGEFOGENABLE | FALSE
D3DRS_SEPARATEALPHABLENDENABLE | FALSE
D3DRS_SHADEMODE | D3DSHADE_GOURAUD
D3DRS_SPECULARENABLE | FALSE
D3DRS_SRCBLEND | D3DBLEND_SRCALPHA
D3DRS_SRGBWRITEENABLE | FALSE
D3DRS_STENCILENABLE | FALSE
D3DRS_VERTEXBLEND | FALSE
D3DRS_WRAP0 | 0

Texture Stage States:

Stage Identifier | Type (D3DTEXTURESTAGESTATETYPE) | Value
0 | D3DTSS_ALPHAARG1 | D3DTA_TEXTURE
0 | D3DTSS_ALPHAARG2 | D3DTA_DIFFUSE
0 | D3DTSS_ALPHAOP | D3DTOP_MODULATE
0 | D3DTSS_COLORARG1 | D3DTA_TEXTURE
0 | D3DTSS_COLORARG2 | D3DTA_DIFFUSE
0 | D3DTSS_COLOROP | D3DTOP_MODULATE
0 | D3DTSS_TEXCOORDINDEX | 0
0 | D3DTSS_TEXTURETRANSFORMFLAGS | D3DTTFF_DISABLE
1 | D3DTSS_ALPHAOP | D3DTOP_DISABLE
1 | D3DTSS_COLOROP | D3DTOP_DISABLE

Sampler States:

Sampler Stage Index | Type (D3DSAMPLERSTATETYPE) | Value
0 | D3DSAMP_ADDRESSU | D3DTADDRESS_CLAMP
0 | D3DSAMP_ADDRESSV | D3DTADDRESS_CLAMP
0 | D3DSAMP_MAGFILTER | D3DTEXF_ANISOTROPIC if TextureFilterCaps includes D3DPTFILTERCAPS_MAGFANISOTROPIC; otherwise D3DTEXF_LINEAR
0 | D3DSAMP_MAXMIPLEVEL | 0
0 | D3DSAMP_MAXANISOTROPY | MaxAnisotropy
0 | D3DSAMP_MINFILTER | D3DTEXF_ANISOTROPIC if TextureFilterCaps includes D3DPTFILTERCAPS_MINFANISOTROPIC; otherwise D3DTEXF_LINEAR
0 | D3DSAMP_MIPFILTER | D3DTEXF_LINEAR if TextureFilterCaps includes D3DPTFILTERCAPS_MIPFLINEAR; otherwise D3DTEXF_POINT
0 | D3DSAMP_MIPMAPLODBIAS | 0
0 | D3DSAMP_SRGBTEXTURE | 0

Note This method disables N-patches.

See Also

ID3DXSprite::End, D3DXSPRITE


ID3DXSprite::Draw Method

Adds a sprite to the list of batched sprites.

Syntax

HRESULT Draw(

    LPDIRECT3DTEXTURE9 pTexture,
    CONST RECT *pSrcRect,
    CONST D3DXVECTOR3 *pCenter,
    CONST D3DXVECTOR3 *pPosition,
    D3DCOLOR Color
);

Parameters

pTexture
[in] Pointer to an IDirect3DTexture9 interface that represents the sprite texture.
pSrcRect
[in] Pointer to a RECT World Wide Web link structure that indicates the portion of the source texture to use for the sprite. If this parameter is NULL, then the entire source image is used for the sprite.
pCenter
[in] Pointer to a D3DXVECTOR3 vector that identifies the center of the sprite. If this argument is NULL, the point (0,0,0) is used, which is the upper-left corner.
pPosition
[in] Pointer to a D3DXVECTOR3 vector that identifies the position of the sprite. If this argument is NULL, the point (0,0,0) is used, which is the upper-left corner.
Color
[in] D3DCOLOR type. The color and alpha channels are modulated by this value. A value of 0xFFFFFFFF maintains the original source color and alpha data. Use the D3DCOLOR_RGBA macro to help generate this color.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.


ID3DXSprite::End Method

Calls ID3DXSprite::Flush and restores the device state to how it was before ID3DXSprite::Begin was called.

Syntax

HRESULT End(VOID);

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

ID3DXSprite::End cannot be used as a substitute for either IDirect3DDevice9::EndScene or ID3DXRenderToSurface::EndScene.

See Also

ID3DXSprite::Begin


ID3DXSprite::Flush Method

Forces all batched sprites to be submitted to the device. Device states remain as they were after the last call to ID3DXSprite::Begin. The list of batched sprites is then cleared.

Syntax

HRESULT Flush(VOID);

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

See Also

ID3DXSprite::End


ID3DXSprite::GetDevice Method

Retrieves the device associated with the sprite object.

Syntax

HRESULT GetDevice(

    LPDIRECT3DDEVICE9 *ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface, representing the Microsoft Direct3D device object associated with the sprite object.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

Calling this method will increase the internal reference count on the IDirect3DDevice9 interface.


ID3DXSprite::GetTransform Method

Gets the sprite transform.

Syntax

HRESULT GetTransform(

    D3DXMATRIX *pTransform
);

Parameters

pTransform
[in] Pointer to a D3DXMATRIX that contains a transform of the sprite from the original world space.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXSprite::OnLostDevice Method

Releases all references to video memory resources and deletes all stateblocks.

Syntax

HRESULT OnLostDevice(VOID);

Return Value

Always returns S_OK.

Remarks

This method should be called whenever the device is lost. Before this object can be used again, the device must be reset and the ID3DXSprite::OnResetDevice method called.


ID3DXSprite::OnResetDevice Method

Should be called after the device has been reset.

Syntax

HRESULT OnResetDevice(VOID);

Return Value

Always returns S_OK.

Remarks

This method should be called after the device has been reset, before any other methods are called.


ID3DXSprite::SetTransform Method

Sets the sprite transform.

Syntax

HRESULT SetTransform(

    CONST D3DXMATRIX *pTransform
);

Parameters

pTransform
[in] Pointer to a D3DXMATRIX that contains a transform of the sprite from the original world space.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXSprite::SetWorldViewLH Method

Sets the left-handed world-view transform for a sprite. A call to this method is required before billboarding or sorting sprites.

Syntax

HRESULT SetWorldViewLH(

    CONST D3DXMATRIX *pWorld,
    CONST D3DXMATRIX *pView
);

Parameters

pWorld
[in] Pointer to a D3DXMATRIX that contains a world transform. If NULL, the identity matrix is used for the world transform.
pView
[in] Pointer to a D3DXMATRIX that contains a view transform. If NULL, the identity matrix is used for the view transform.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

A call to this method (or to ID3DXSprite::SetWorldViewRH) is required if the sprite will be rendered with the D3DXSPRITE_BILLBOARD, D3DXSPRITE_SORT_DEPTH_FRONTTOBACK, or D3DXSPRITE_SORT_DEPTH_BACKTOFRONT flag value in ID3DXSprite::Begin.


ID3DXSprite::SetWorldViewRH Method

Sets the right-handed world-view transform for a sprite. A call to this method is required before billboarding or sorting sprites.

Syntax

HRESULT SetWorldViewRH(

    CONST D3DXMATRIX *pWorld,
    CONST D3DXMATRIX *pView
);

Parameters

pWorld
[in] Pointer to a D3DXMATRIX that contains a world transform. If NULL, the identity matrix is used for the world transform.
pView
[in] Pointer to a D3DXMATRIX that contains a view transform. If NULL, the identity matrix is used for the view transform.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

A call to this method (or to ID3DXSprite::SetWorldViewLH) is required if the sprite will be rendered with the D3DXSPRITE_BILLBOARD, D3DXSPRITE_SORT_DEPTH_FRONTTOBACK, or D3DXSPRITE_SORT_DEPTH_BACKTOFRONT flag value in ID3DXSprite::Begin.


ID3DXTextureGutterHelper Interface

The ID3DXTextureGutterHelper interface is used to build and manage gutter regions in a texture. Gutter regions separate textures and allow for bilinear interpolation to avoid rendering artifacts at texture boundaries.

The Get... methods provide access to the data structures used by the Apply... methods.

ID3DXTextureGutterHelper Members

ApplyGuttersFloat | Applies gutters to a FLOAT texture buffer.
ApplyGuttersPRT | Applies gutters to an ID3DXPRTBuffer buffer object.
ApplyGuttersTex | Applies gutters to an IDirect3DTexture9 texture object.
GetBaryMap | Retrieves texel barycentric coordinates.
GetFaceMap | Retrieves the index of the mesh face to which each texel belongs.
GetGutterMap | Receives a texel class value that indicates texel class according to each texel's location.
GetHeight | Retrieves the height of the texture, in pixels.
GetTexelMap | Retrieves the (u, v) texture coordinates of each texel.
GetWidth | Retrieves the width of the texture, in pixels.
SetBaryMap | Sets texel barycentric coordinates.
SetFaceMap | Sets the index of the mesh face to which each texel belongs.
SetGutterMap | Sets a texel class value that indicates texel class according to each texel's location.
SetTexelMap | Sets the (u, v) texture coordinates of each texel.

Remarks

Note When used with precomputed radiance transfer (PRT), this interface requires a unique parameterization of the model. Every texel must correspond to a single point on the surface of the model and vice-versa. If the model includes multiple textures, it must be split into separate pieces that each contain one gutter helper object per texture.
This interface can be used to generate a map in texture space in which each texel is in one of four classes.

Texel Class | Texel Location
0 | Invalid point; texel will not be used.
1 | Inside triangle.
2 | Inside gutter.
4 | Inside gutter; texel will be evaluated as a full sample in the ApplyGuttersFloat, ApplyGuttersTex, or ApplyGuttersPRT methods.

For classes 1 and 2, a texel is stored with the face it belongs to, along with barycentric coordinates of the first two vertices of that face. Gutter vertices are assigned to the closest edge in texture space.

There is no texel class 3.

The ID3DXTextureGutterHelper interface is obtained by calling the D3DXCreateTextureGutterHelper function.

The LPD3DXTEXTUREGUTTERHELPER type is defined as a pointer to the ID3DXTextureGutterHelper interface.

typedef interface ID3DXTextureGutterHelper ID3DXTextureGutterHelper;
typedef interface ID3DXTextureGutterHelper *LPD3DXTEXTUREGUTTERHELPER;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXTextureGutterHelper::ApplyGuttersFloat Method

Applies gutters to a FLOAT texture buffer.

Syntax

HRESULT ApplyGuttersFloat(

    FLOAT *pDataIn,
    UINT *NumCoeffs,
    UINT *Width,
    UINT *Height
);

Parameters

pDataIn
[in] Pointer to a buffer of FLOAT texture data.
NumCoeffs
[in] Number of scalars per color channel used in memory to store samples. Each texel contains NumCoeffs FLOAT values.
Width
[in] Width of the texture, in pixels, obtained from ID3DXTextureGutterHelper::GetWidth.
Height
[in] Height of the texture, in pixels, obtained from ID3DXTextureGutterHelper::GetHeight.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

Class 2 texels are generated by resampling class 1 and 4 texels.


ID3DXTextureGutterHelper::ApplyGuttersPRT Method

Applies gutters to an ID3DXPRTBuffer buffer object.

Syntax

HRESULT ApplyGuttersPRT(

    LPD3DXPRTBUFFER pBuffer
);

Parameters

pBuffer
[in] Pointer to an ID3DXPRTBuffer buffer object.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

Class 2 texels are generated by resampling class 1 and 4 texels.

The width and height of the texture must be the same as those returned by ID3DXTextureGutterHelper::GetWidth and ID3DXTextureGutterHelper::GetHeight.


ID3DXTextureGutterHelper::ApplyGuttersTex Method

Applies gutters to an IDirect3DTexture9 texture object.

Syntax

HRESULT ApplyGuttersTex(

    LPDIRECT3DTEXTURE9 pTexture
);

Parameters

pTexture
[in] Pointer to a IDirect3DTexture9 texture object.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
D3DERR_WASSTILLDRAWING | The previous blit operation that is transferring information to or from this surface is incomplete.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Class 2 texels are generated by resampling class 1 and 4 texels.

The width and height of the texture must be the same as those returned by ID3DXTextureGutterHelper::GetWidth and ID3DXTextureGutterHelper::GetHeight.


ID3DXTextureGutterHelper::GetBaryMap Method

Retrieves texel barycentric coordinates.

Syntax

HRESULT GetBaryMap(

    D3DXVECTOR2 *pBaryData
);

Parameters

pBaryData
[in, out] Pointer to a D3DXVECTOR2 structure that contains the first two barycentric coordinates of each texel.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The third barycentric coordinate is given by:

1 - ( pBaryData.x + pBaryData.y )
Barycentric coordinates are always specified with respect to the triangle returned by ID3DXTextureGutterHelper::GetFaceMap.

The barycentric coordinates returned by this method are valid only for valid (non-class 0) texels. ID3DXTextureGutterHelper::GetGutterMap will return nonzero values for valid texels.

Class 2 texels are mapped to the nearest point on the triangle in texel space.

The application must allocate and manage pBaryData.


ID3DXTextureGutterHelper::GetFaceMap Method

Retrieves the index of the mesh face to which each texel belongs.

Syntax

HRESULT GetFaceMap(

    UINT *pFaceData
);

Parameters

pFaceData
[in] Pointer to the index of the mesh face to which each texel belongs.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The mesh face data returned by this method is valid only for valid (non-class 0) texels. ID3DXTextureGutterHelper::GetGutterMap will return nonzero values for valid (non-class 0) texels.

For class 2 texels, this method retrieves the closest face.

The application must allocate and manage pFaceData.


ID3DXTextureGutterHelper::GetGutterMap Method

Receives a texel class value that indicates texel class according to each texel's location.

Syntax

HRESULT GetGutterMap(

    BYTE *pGutterData
);

Parameters

pGutterData
[in, out] Pointer to the texel class. Possible texel classes are as follows. There is no texel class 3.

Texel Class | Texel Location
0 | Invalid point; texel will not be used.
1 | Inside triangle.
2 | Inside gutter.
4 | Inside gutter; texel will be evaluated as a full sample in the ApplyGuttersFloat, ApplyGuttersTex, or ApplyGuttersPRT methods.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The application must allocate and manage pGutterData, with size given by:

texture width * texture height * sizeof(BYTE)

Texture width and height are returned by ID3DXTextureGutterHelper::GetWidth and GetHeight.


ID3DXTextureGutterHelper::GetHeight Method

Retrieves the height of the texture, in pixels.

Syntax

UINT GetHeight(VOID);

Return Value

Returns the height of the texture, in pixels.

See Also

ID3DXTextureGutterHelper::GetWidth


ID3DXTextureGutterHelper::GetTexelMap Method

Retrieves the (u, v) texture coordinates of each texel.

Syntax

HRESULT GetTexelMap(

    D3DXVECTOR2 *pTexelData
);

Parameters

pTexelData
[out] Pointer to the location in pixel (u, v) texture coordinates where each texel is located.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

For class 2 and 4 texels, the returned (u, v) texture coordinates correspond to the closest point on the closest triangle.

The application must allocate and manage pTexelData.


ID3DXTextureGutterHelper::GetWidth Method

Retrieves the width of the texture, in pixels.

Syntax

UINT GetWidth(VOID);

Return Value

Returns the width of the texture, in pixels.

See Also

ID3DXTextureGutterHelper::GetHeight


ID3DXTextureGutterHelper::SetBaryMap Method

Sets texel barycentric coordinates.

Syntax

HRESULT SetBaryMap(

    D3DXVECTOR2 *pBaryData
);

Parameters

pBaryData
[in] Pointer to a D3DXVECTOR2 structure that contains the first two barycentric coordinates of each texel.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The third barycentric coordinate is given by:

1 - ( pBaryData.x + pBaryData.y )

The barycentric coordinates input to this method are valid only for valid (non-class 0) texels. ID3DXTextureGutterHelper::GetGutterMap will return non-zero values for valid texels.


ID3DXTextureGutterHelper::SetFaceMap Method

Sets the index of the mesh face to which each texel belongs.

Syntax

HRESULT SetFaceMap(

    UINT *pFaceData
);

Parameters

pFaceData
[in] Pointer to the index of the mesh face to which each texel belongs.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The mesh face data input to this method is valid only for valid (non-class 0) texels. ID3DXTextureGutterHelper::GetGutterMap will return non-zero values for valid texels.


ID3DXTextureGutterHelper::SetGutterMap Method

Sets a texel class value that indicates texel class according to each texel's location.

Syntax

HRESULT SetGutterMap(

    BYTE *pGutterData
);

Parameters

pGutterData
[in] Pointer to the texel class. Possible texel classes are as follows. There is no texel class 3.

Texel Class | Texel Location
0 | Invalid point; texel will not be used.
1 | Inside triangle.
2 | Inside gutter.
4 | Inside gutter; texel will be evaluated as a full sample in the ApplyGuttersFloat, ApplyGuttersTex, or ApplyGuttersPRT methods.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXTextureGutterHelper::SetTexelMap Method

Sets the (u, v) texture coordinates of each texel.

Syntax

HRESULT SetTexelMap(

    D3DXVECTOR2 *pTexelData
);

Parameters

pTexelData
[in] Pointer to the location in pixel (u, v) texture coordinates where each texel is located.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.


ID3DXTextureShader Interface

The ID3DXTextureShader interface.

ID3DXTextureShader Members

GetConstant | Gets a constant by looking up its index.
GetConstantBuffer | Get a pointer to the constant table.
GetConstantByName | Gets a constant by looking up its name.
GetConstantDesc | Gets a pointer to the array of constants in the constant table.
GetConstantElement | Get a constant from the constant table.
GetDesc | Gets a description of the constant table.
GetFunction | Gets a pointer the the function DWORD stream.
SetBool | Sets a BOOL value.
SetBoolArray | Sets an array of BOOL values.
SetDefaults | Sets the constants to the default values declared in the shader.
SetFloat | Sets a floating-point number.
SetFloatArray | Sets an array of floating-point numbers.
SetInt | Sets an integer value.
SetIntArray | Sets an array of integers.
SetMatrix | Sets a non-transposed matrix.
SetMatrixArray | Sets an array of non-transposed matrices.
SetMatrixPointerArray | Sets an array of pointers to non-transposed matrices.
SetMatrixTranspose | Sets a transposed matrix.
SetMatrixTransposeArray | Sets an array of transposed matrices.
SetMatrixTransposePointerArray | Sets an array of pointers to transposed matrices.
SetValue | Sets the constant table with the data in the buffer.
SetVector | Sets a 4-D vector.
SetVectorArray | Sets an array of 4-D vectors.

Remarks

The ID3DXTextureShader interface is obtained by calling the D3DXCreateTextureShader function.

The ID3DXTextureShader interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface.

The LPD3DXTEXTURESHADER type is defined as a pointer to the ID3DXTextureShader interface.

typedef interface ID3DXTextureShader *LPD3DXTEXTURESHADER;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum availability | DirectX 9.0
Minimum operating systems | Windows 2000, Windows 98


ID3DXTextureShader::GetConstant Method

Gets a constant by looking up its index.

Syntax

D3DXHANDLE GetConstant(

    D3DXHANDLE hConstant,
    UINT Index
);

Parameters

hConstant
[in] A handle to the parent data structure. If the constant is a top-level parameter (there is no parent data structure), use NULL.
Index
[in] Zero-based index of the constant.

Return Value

Returns a unique identifier to the constant.

Remarks

To get a constant from an array of constants, use ID3DXTextureShader::GetConstantElement.


ID3DXTextureShader::GetConstantBuffer Method

Get a pointer to the constant table.

Syntax

HRESULT GetConstantBuffer(

    LPD3DXBUFFER *ppConstantBuffer
);

Parameters

ppConstantBuffer
[out] Pointer to an ID3DXBuffer interface, which contains the constants.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.


ID3DXTextureShader::GetConstantByName Method

Gets a constant by looking up its name.

Syntax

D3DXHANDLE GetConstantByName(

    D3DXHANDLE hConstant,
    LPCSTR pName
);

Parameters

hConstant
[in] A handle to the parent data structure. If the constant is a top-level parameter (there is no parent data structure), use NULL.
pName
[in] A string containing the name of the constant.

Return Value

Returns a unique identifier to the constant.


ID3DXTextureShader::GetConstantDesc Method

Gets a pointer to the array of constants in the constant table.

Syntax

HRESULT GetConstantDesc(

    D3DXHANDLE hConstant,
    D3DXCONSTANT_DESC *pDesc,
    UINT *pCount
);

Parameters

hConstant
[in] Unique identifier to a constant. See D3DXHANDLE.
pDesc
[in, out] Returns a pointer to an array of descriptions. See D3DXCONSTANT_DESC.
pCount
[in, out] The input supplied must be the maximum size of the array. The output is the number of elements that are filled in the array when the function returns.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

Samplers can appear more than once in a constant table, therefore, this method can return an array of descriptions each with a different register index.

See Also

ID3DXTextureShader::GetDesc


ID3DXTextureShader::GetConstantElement Method

Get a constant from the constant table.

Syntax

D3DXHANDLE GetConstantElement(

    D3DXHANDLE hConstant,
    UINT Index
);

Parameters

hConstant
[in] A handle to the array of constants. This value may not be NULL.
Index
[in] Zero-based index of the element in the constant table.

Return Value

Returns a unique identifier to the constant.

Remarks

To get a constant that is not part of an array, use ID3DXTextureShader::GetConstant or ID3DXTextureShader::GetConstantByName.


ID3DXTextureShader::GetDesc Method

Gets a description of the constant table.

Syntax

HRESULT GetDesc(

    D3DXCONSTANTTABLE_DESC *pDesc
);

Parameters

pDesc
[in] The attributes of the constant table. See D3DXCONSTANTTABLE_DESC.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.


ID3DXTextureShader::GetFunction Method

Gets a pointer the the function DWORD stream.

Syntax

HRESULT GetFunction(

    LPD3DXBUFFER *ppFunction
);

Parameters

ppFunction
[in] A pointer to the function DWORD stream. See ID3DXBuffer.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.


ID3DXTextureShader::SetBool Method

Sets a BOOL value.

Syntax

HRESULT SetBool(

    D3DXHANDLE hConstant,
    BOOL b
);

Parameters

hConstant
[in] Unique identifier to the constant. See D3DXHANDLE.
b
[in] BOOL value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXTextureShader::SetBoolArray Method

Sets an array of BOOL values.

Syntax

HRESULT SetBoolArray(

    D3DXHANDLE hConstant,
    CONST BOOL* pB,
    UINT Count
);

Parameters

hConstant
[in] Unique identifier to the array of constants. See D3DXHANDLE.
pB
[in] Array of BOOL values.
Count
[in] Number of BOOL values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXTextureShader::SetDefaults Method

Sets the constants to the default values declared in the shader.

Syntax

HRESULT SetDefaults(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXTextureShader::SetFloat Method

Sets a floating-point number.

Syntax

HRESULT SetFloat(

    D3DXHANDLE hConstant,
    FLOAT f
);

Parameters

hConstant
[in] Unique identifier to the constant. See D3DXHANDLE.
f
[in] Floating-point number.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXTextureShader::SetFloatArray Method

Sets an array of floating-point numbers.

Syntax

HRESULT SetFloatArray(

    D3DXHANDLE hConstant,
    CONST FLOAT* pf,
    UINT Count
);

Parameters

hConstant
[in] Unique identifier to the array of constants. See D3DXHANDLE.
pf
[in] Array of floating-point numbers.
Count
[in] Number of floating-point values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXTextureShader::SetInt Method

Sets an integer value.

Syntax

HRESULT SetInt(

    D3DXHANDLE hConstant,
    INT n
);

Parameters

hConstant
[in] Unique identifier to the constant. See D3DXHANDLE.
n
[in] Integer value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXTextureShader::SetIntArray Method

Sets an array of integers.

Syntax

HRESULT SetIntArray(

    D3DXHANDLE hConstant,
    CONST INT* pn,
    UINT Count
);

Parameters

hConstant
[in] Unique identifier to the array of constants. See D3DXHANDLE.
pn
[in] Array of integers.
Count
[in] Number of integers in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXTextureShader::SetMatrix Method

Sets a non-transposed matrix.

Syntax

HRESULT SetMatrix(

    D3DXHANDLE hConstant,
    CONST D3DXMATRIX* pMatrix
);

Parameters

hConstant
[in] Unique identifier to the matrix of constants. See D3DXHANDLE.
pMatrix
[in] Pointer to a non-transposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A non-transposed matrix contains row-major data; that is, each vector is contained in a row.


ID3DXTextureShader::SetMatrixArray Method

Sets an array of non-transposed matrices.

Syntax

HRESULT SetMatrixArray(

    D3DXHANDLE hConstant,
    CONST D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hConstant
[in] Unique identifier to the array of constant matrices. See D3DXHANDLE.
pMatrix
[in] Array of non-transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A non-transposed matrix contains row-major data; that is, each vector is contained in a row.


ID3DXTextureShader::SetMatrixPointerArray Method

Sets an array of pointers to non-transposed matrices.

Syntax

HRESULT SetMatrixPointerArray(

    D3DXHANDLE hConstant,
    const D3DXMATRIX **ppMatrix,
    UINT Count
);

Parameters

hConstant
[in] Unique identifier to an array of constant matrices. See D3DXHANDLE.
ppMatrix
[in] Array of pointers to non-transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A non-transposed matrix contains row-major data; that is, each vector is contained in a row.


ID3DXTextureShader::SetMatrixTranspose Method

Sets a transposed matrix.

Syntax

HRESULT SetMatrixTranspose(

    D3DXHANDLE hConstant,
    CONST D3DXMATRIX* pMatrix
);

Parameters

hConstant
[in] Unique identifier to the matrix of constants. See D3DXHANDLE.
pMatrix
[in] Pointer to a transposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.


ID3DXTextureShader::SetMatrixTransposeArray Method

Sets an array of transposed matrices.

Syntax

HRESULT SetMatrixTransposeArray(

    D3DXHANDLE hConstant,
    CONST D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hConstant
[in] Unique identifier to the array of matrix constants. See D3DXHANDLE.
pMatrix
[in] Array of transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.


ID3DXTextureShader::SetMatrixTransposePointerArray Method

Sets an array of pointers to transposed matrices.

Syntax

HRESULT SetMatrixTransposePointerArray(

    D3DXHANDLE hConstant,
    CONST D3DXMATRIX** ppMatrix,
    UINT Count
);

Parameters

hConstant
[in] Unique identifier to the array of matrix constants. See D3DXHANDLE.
ppMatrix
[in] Array of pointers to transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.


ID3DXTextureShader::SetValue Method

Sets the constant table with the data in the buffer.

Syntax

HRESULT SetValue(

    D3DXHANDLE hConstant,
    LPCVOID pData,
    UINT Bytes
);

Parameters

hConstant
[in] Unique identifier to a constant. See D3DXHANDLE.
pData
[in] A pointer to a buffer containing the constant data.
Bytes
[in] Size of the buffer, in bytes.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXTextureShader::SetVector Method

Sets a 4-D vector.

Syntax

HRESULT SetVector(

    D3DXHANDLE hConstant,
    CONST D3DXVECTOR4* pVector
);

Parameters

hConstant
[in] Unique identifier to the vector constant. See D3DXHANDLE.
pVector
[in] Pointer to a 4-D vector. See D3DXVECTOR4.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXTextureShader::SetVectorArray Method

Sets an array of 4-D vectors.

Syntax

HRESULT SetVectorArray(

    D3DXHANDLE hConstant,
    CONST D3DXVECTOR4* pVector,
    UINT Count
);

Parameters

hConstant
[in] Unique identifier to the array of vector constants. See D3DXHANDLE.
pVector
[in] Array of 4-D vectors. See D3DXVECTOR4.
Count
[in] Number of vectors in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


Functions
Microsoft DirectX 9.0 SDK Update (October 2004)

Functions

This section contains reference information for the functions that you need to implement when you work with the D3DX utility library. The following functions are implemented.

  • Animation Functions
  • General Purpose Functions
  • Math Functions
  • Mesh Functions
  • Precomputed Radiance Transfer Functions
  • Shader Functions
  • Shape Drawing Functions
  • Texturing Functions


Animation Functions
Microsoft DirectX 9.0 SDK Update (October 2004)

Animation Functions

D3DX supplies the following animation functions.

  • D3DXCreateAnimationController
  • D3DXCreateCompressedAnimationSet
  • D3DXCreateKeyframedAnimationSet
  • D3DXFrameAppendChild
  • D3DXFrameCalculateBoundingSphere
  • D3DXFrameDestroy
  • D3DXFrameFind
  • D3DXFrameNumNamedMatrices
  • D3DXFrameRegisterNamedMatrices
  • D3DXLoadMeshHierarchyFromX
  • D3DXLoadMeshHierarchyFromXInMemory
  • D3DXSaveMeshHierarchyToFile


D3DXCreateAnimationController Function

Creates an animation controller object.

Syntax

HRESULT WINAPI D3DXCreateAnimationController(

    UINT MaxNumAnimationOutputs,
    UINT MaxNumAnimationSets,
    UINT MaxNumTracks,
    UINT MaxNumEvents,
    LPD3DXANIMATIONCONTROLLER* ppAnimController
);

Parameters

MaxNumAnimationOutputs
[in] Maximum number of animation outputs the controller can support.
MaxNumAnimationSets
[in] Maximum number of animation sets that can be mixed.
MaxNumTracks
[in] Maximum number of animation sets that can be mixed simultaneously.
MaxNumEvents
[in] Maximum number of outstanding events that the controller will support.
ppAnimController
[out, retval] Pointer to the animation controller object created. See ID3DXAnimationController.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

An animation controller controls an animation mixer. The controller adds methods to modify blending parameters over time to enable smooth transitions.

Function Information

Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXCreateCompressedAnimationSet Function

Creates a ID3DXCompressedAnimationSet key framed animation set interface that stores key frame data in a compressed format.

Syntax

HRESULT WINAPI D3DXCreateCompressedAnimationSet(

    LPCSTR pName,
    DOUBLE TicksPerSecond,
    D3DXPLAYBACK_TYPE Playback,
    LPD3DXBUFFER pCompressedData,
    UINT NumCallbackKeys,
    CONST LPD3DXKEY_CALLBACK *pCallKeys,
    LPD3DXCOMPRESSEDANIMATIONSET *ppAnimationSet
);

Parameters

pName
[in] Pointer to the name of the animation set.
TicksPerSecond
[in] Number of key frame ticks that elapse per second.
Playback
[in] Type of the animation set playback loop. See D3DXPLAYBACK_TYPE.
pCompressedData
[in] Pointer to the ID3DXBuffer buffer that stores the animation set as compressed data.
NumCallbackKeys
[in] Number of callback keys.
pCallKeys
[in] Pointer to a D3DXKEY_CALLBACK structure that stores user callback data.
ppAnimationSet
[out] Address of a pointer to the ID3DXCompressedAnimationSet interface that stores key framed animation set data in a compressed format.

Return Value

If the function succeeds, the return value is S_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXCreateKeyframedAnimationSet Function

Creates a ID3DXKeyframedAnimationSet key framed animation set interface.

Syntax

HRESULT WINAPI D3DXCreateKeyframedAnimationSet(

    LPCSTR pName,
    DOUBLE TicksPerSecond,
    D3DXPLAYBACK_TYPE Playback,
    UINT NumAnimations,
    UINT NumCallbackKeys,
    CONST LPD3DXKEY_CALLBACK *pCallKeys,
    LPD3DXKEYFRAMEDANIMATIONSET *ppAnimationSet
);

Parameters

pName
[in] Pointer to the name of the animation set.
TicksPerSecond
[in] Number of key frame ticks that elapse per second.
Playback
[in] Type of the animation set playback loop. See D3DXPLAYBACK_TYPE.
NumAnimations
[in] Number of scale, rotate, and translate (SRT) animation sets.
NumCallbackKeys
[in] Number of callback keys.
pCallKeys
[in] Pointer to a D3DXKEY_CALLBACK structure that stores user callback data.
ppAnimationSet
[out] Address of a pointer to the ID3DXKeyframedAnimationSet key framed animation set interface.

Return Value

If the function succeeds, the return value is S_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXFrameAppendChild Function

Adds a child frame to a frame.

Syntax

HRESULT WINAPI D3DXFrameAppendChild(

    LPD3DXFRAME pFrameParent,
    const D3DXFRAME *pFrameChild
);

Parameters

pFrameParent
[in] Pointer to the parent node.
pFrameChild
[in] Pointer to the child node.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXFrameCalculateBoundingSphere Function

Computes the bounding sphere of all the meshes in the frame hierarchy.

Syntax

HRESULT WINAPI D3DXFrameCalculateBoundingSphere(

    const D3DXFRAME *pFrameRoot,
    LPD3DXVECTOR3 pObjectCenter,
    FLOAT *pObjectRadius
);

Parameters

pFrameRoot
[in] Pointer to the root node.
pObjectCenter
[out] Returns the center of the bounding sphere.
pObjectRadius
[out] Returns the radius of the bounding sphere.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXFrameDestroy Function

Destroys the subtree of frames under the root, including the root.

Syntax

HRESULT WINAPI D3DXFrameDestroy(

    LPD3DXFRAME pFrameRoot,
    LPD3DXALLOCATEHIERARCHY pAlloc
);

Parameters

pFrameRoot
[in] Pointer to the root node.
pAlloc
[in] Allocation interface used to deallocate nodes of the frame hierarchy.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXFrameFind Function

Finds the child frame of a root frame.

Syntax

LPD3DXFRAME WINAPI D3DXFrameFind(

    const D3DXFRAME *pFrameRoot,
    LPCSTR Name
);

Parameters

pFrameRoot
[in] Pointer to the root frame. See D3DXFRAME.
Name
[in] Name of the child frame to find.

Return Value

Returns the child frame if it is found, or NULL otherwise. See D3DXFRAME.

Function Information

Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXFrameNumNamedMatrices Function

Counts number of frames in a subtree that have non-null names.

Syntax

UINT WINAPI D3DXFrameNumNamedMatrices(

    const D3DXFRAME *pFrameRoot
);

Parameters

pFrameRoot
[in] Pointer to the root node of the subtree.

Return Value

Returns the frame count.

Function Information

Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXFrameRegisterNamedMatrices Function

Given a frame hierarchy, registers all the named matrices in the animation mixer.

Syntax

HRESULT WINAPI D3DXFrameRegisterNamedMatrices(

    LPD3DXFRAME pFrameRoot,
    LPD3DXANIMATIONCONTROLLER pAnimController
);

Parameters

pFrameRoot
[in] The top level node in the frame hierarchy.
pAnimController
[in] Pointer to the animation controller object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXLoadMeshHierarchyFromX Function

Loads the first frame hierarchy from a .x file.

Syntax

HRESULT WINAPI D3DXLoadMeshHierarchyFromX(

    LPCSTR Filename,
    DWORD MeshOptions,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXALLOCATEHIERARCHY pAlloc,
    LPD3DXLOADUSERDATA pUserDataLoader,
    LPD3DXFRAME* ppFrameHierarchy,
    LPD3DXANIMATIONCONTROLLER* ppAnimController
);

Parameters

Filename
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
MeshOptions
[in] Combination of one or more flags from the D3DXMESH enumeration that specify creation options for the mesh.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object associated with the mesh.
pAlloc
[in] Pointer to an ID3DXAllocateHierarchy interface.
pUserDataLoader
[in] Application provided interface that allows loading of user data. See ID3DXLoadUserData.
ppFrameHierarchy
[out, retval] Returns a pointer to the loaded frame hierarchy. See D3DXFRAME.
ppAnimController
[out, retval] Returns a pointer to the animation controller corresponding to animation in the .x file. This is created with default tracks and events. See ID3DXAnimationController.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXLoadMeshHierarchyFromXW. Otherwise, the function call resolves to D3DXLoadMeshHierarchyFromXA.

All the meshes in the file will be collapsed into one output mesh. If the file contains a frame hierarchy, all the transformations will be applied to the mesh.

D3DXLoadMeshHierarchyFromX loads the animation data and frame hierarchy from a .x file. It scans the .x file and builds a frame hierarchy and animation controller according to the ID3DXAllocateHierarchy-derived object passed to it through pAlloc. Loading the data requires several steps as follows:

  1. Derive ID3DXAllocateHierarchy, implementing each method. This controls how frames and meshes are allocated and freed.
  2. Derive ID3DXLoadUserData, implementing each method. If your .x file has no embedded user-defined data, or if you do not need it, you can skip this part.
  3. Create an object of your ID3DXAllocateHierarchy class, and optionally of your LoadUserData class. You do not need to call any methods of these objects yourself.
  4. Call D3DXLoadMeshHierarchyFromX, passing in your ID3DXAllocateHierarchy object and your ID3DXLoadUserData object (or NULL) to create the frame hierarchy and animation controller. All the animation sets and frames are automatically registered to the animation controller.

During the load, ID3DXAllocateHierarchy::CreateFrame and ID3DXLoadUserData::LoadFrameChildData are called back on each frame to control loading and allocation of the frame. The application defines these methods to control how frames are stored. ID3DXAllocateHierarchy::CreateMeshContainer and ID3DXLoadUserData::LoadMeshChildData are called back on each mesh object to control loading and allocation of mesh objects. ID3DXLoadUserData::LoadTopLevelData is called back for each top level object that doesn't get loaded by the other methods.

To free this data, call ID3DXAnimationController::Release to free the animation sets, and D3DXFrameDestroy, passing in the root node of the frame hierarchy and an object of your derived ID3DXAllocateHierarchy class. ID3DXAllocateHierarchy::DestroyFrame and ID3DXAllocateHierarchy::DestroyMeshContainer will each be called for every frame and mesh object in the frame hierarchy. Your implementation of ID3DXAllocateHierarchy::DestroyFrame should release everything allocated by ID3DXAllocateHierarchy::CreateFrame, and likewise for the mesh container methods.

Function Information

Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXLoadMeshHierarchyFromXInMemory Function

Loads the first frame hierarchy from a .x file.

Syntax

HRESULT WINAPI D3DXLoadMeshHierarchyFromXInMemory(

    LPCVOID pMemory,
    DWORD SizeOfMemory,
    DWORD MeshOptions,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXALLOCATEHIERARCHY pAlloc,
    LPD3DXLOADUSERDATA pUserDataLoader,
    LPD3DXFRAME *ppFrameHeirarchy,
    LPD3DXANIMATIONCONTROLLER *ppAnimController
);

Parameters

pMemory
[in] ] Pointer to a buffer that contains the mesh hierarchy.
SizeOfMemory
[in] Size of the pMemory buffer, in bytes.
MeshOptions
[in] Combination of one or more flags from the D3DXMESH enumeration that specify creation options for the mesh.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object associated with the mesh.
pAlloc
[in] Pointer to an ID3DXAllocateHierarchy interface.
pUserDataLoader
[in] Application provided interface that allows loading of user data. See ID3DXLoadUserData.
ppFrameHeirarchy
[out, retval] Returns a pointer to the loaded frame heirarchy. See D3DXFRAME.
ppAnimController
[out, retval] Returns a pointer to the animation controller corresponding to animation in the .x file. This is created with default tracks and events. See ID3DXAnimationController.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

All the meshes in the file will be collapsed into one output mesh. If the file contains a frame hierarchy, all the transformations will be applied to the mesh.

Function Information

Header | d3dx9anim.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXSaveMeshHierarchyToFile Function

Creates a .x file and saves the mesh hierarchy and corresponding animations in it.

Syntax

HRESULT WINAPI D3DXSaveMeshHierarchyToFile(

    LPCSTR pFilename,
    DWORD XFormat,
    const D3DXFRAME *pFrameRoot,
    LPD3DXANIMATIONCONTROLLER pAnimController,
    LPD3DXSAVEUSERDATA pUserDataSaver
);

Parameters

pFilename
[in] Pointer to a string that specifies the name of the .x file identifying the saved mesh. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
XFormat
[in] Format of the .x file (text or binary, compressed or not). See D3DXF_FILEFORMAT. D3DXF_FILEFORMAT_COMPRESSED can be combined (using a logical OR) with either the D3DXF_FILEFORMAT_BINARY or D3DXF_FILEFORMAT_TEXT flags to reduce the output file size.
pFrameRoot
[in] Root node of the hierarchy to be saved. See D3DXFRAME.
pAnimController
[in] Animation controller that has animation sets to be stored. See ID3DXAnimationController.
pUserDataSaver
[in] Application-provided interface that allows saving of user data. See ID3DXSaveUserData.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be:

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXSaveMeshHierarchyToFileW. Otherwise, the function call resolves to D3DXSaveMeshHierarchyToFileA.

For more information about .x files, see X File Reference.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


General Purpose Functions
Microsoft DirectX 9.0 SDK Update (October 2004)

General Purpose Functions

D3DX supplies the following general purpose functions:

  • D3DXCheckVersion
  • D3DXCreateBuffer
  • D3DXCreateFont
  • D3DXCreateFontIndirect
  • D3DXCreateLine
  • D3DXCreateRenderToEnvMap
  • D3DXCreateRenderToSurface
  • D3DXCreateSprite
  • D3DXGetDriverLevel
  • D3DXGetFVFVertexSize


D3DXCheckVersion Function

Checks whether the Microsoft Direct3D runtime version is compatible with the D3DX utility library version.

Syntax

BOOL WINAPI D3DXCheckVersion(

    UINT D3DSdkVersion,
    UINT D3DXSdkVersion
);

Parameters

D3DSdkVersion
[in] D3D_SDK_VERSION version of the Direct3D runtime.
D3DXSdkVersion
[out] D3DX_SDK_VERSION version of the D3DX utility library.

Return Value

Returns TRUE if the the Direct3D runtime version is compatible with the D3DX utility library version; otherwise FALSE is returned.

Remarks

Use this function for initialization of your application as follows.

HRESULT CD3DXMyApplication::Initialize(HINSTANCE hInstance, LPCSTR szWindowName,
    LPCSTR szClassName, UINT uWidth, UINT uHeight)
{
    HRESULT hr;

    if (!D3DXCheckVersion(D3D_SDK_VERSION, D3DX_SDK_VERSION))
    return E_FAIL;
.
.
.
}

Function Information

Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXCreateBuffer Function

Creates a buffer object.

Syntax

HRESULT WINAPI D3DXCreateBuffer(

    DWORD NumBytes,
    LPD3DXBUFFER *ppBuffer
);

Parameters

NumBytes
[in] Size of the buffer to create, in bytes.
ppBuffer
[out] Address of a pointer to an ID3DXBuffer interface, representing the created buffer object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be

E_OUTOFMEMORY Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXCreateFont Function

Creates a font object for a device and font.

Syntax

HRESULT WINAPI D3DXCreateFont(

    LPDIRECT3DDEVICE9 pDevice,
    INT Height,
    UINT Width,
    UINT Weight,
    UINT MipLevels,
    BOOL Italic,
    DWORD CharSet,
    DWORD OutputPrecision,
    DWORD Quality,
    DWORD PitchAndFamily,
    LPCTSTR pFacename,
    LPD3DXFONT *ppFont
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device to be associated with the font object.
Height
[in] The height of the characters in logical units.
Width
[in] The width of the characters in logical units.
Weight
[in] Typeface weight. One example is bold.
MipLevels
[in] The number of mipmap levels.
Italic
[in] True for italic font, false otherwise.
CharSet
[in] The character set of the font.
OutputPrecision
[in] Specifies how Microsoft Windows should attempt to match the desired font sizes and characteristics with actual fonts. Use OUT_TT_ONLY_PRECIS for instance, to ensure that you always get a TrueType® font.
Quality
[in] Specifies how Windows should match the desired font with a real font. It applies to raster fonts only and should not affect TrueType fonts.
PitchAndFamily
[in] Pitch and family index.
pFacename
[in] String containing the typeface name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
ppFont
[out] Returns a pointer to an ID3DXFont interface, representing the created font object.

Return Value

If the function succeeds, the return value is S_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateFontW. Otherwise, the function call resolves to D3DXCreateFontA because ANSI strings are being used.

If you want more information about font parameters, see The Logical Font World Wide Web link.

Function Information

Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXCreateFontIndirect Function

Creates a font object indirectly for both a device and a font.

Syntax

HRESULT WINAPI D3DXCreateFontIndirect(

    LPDIRECT3DDEVICE9 pDevice,
    CONST D3DXFONT_DESC *pDesc,
    LPD3DXFONT *ppFont
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device to be associated with the font object.
pDesc
[in] Pointer to a D3DXFONT_DESC structure, describing the attributes of the font object to create. If the compiler settings require Unicode, the data type D3DXFONT_DESC resolves to D3DXFONT_DESCW; otherwise, the data type resolves to D3DXFONT_DESCA. See Remarks.
ppFont
[out] Returns a pointer to an ID3DXFont interface, representing the created font object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateFontIndirectW. Otherwise, the function call resolves to D3DXCreateFontIndirectA because ANSI strings are being used.

Function Information

Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXCreateLine Function

Uses a left-handed coordinate system to create a line.

Syntax

HRESULT WINAPI D3DXCreateLine(

    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXLINE* ppLine
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the created box mesh.
ppLine
[out] Pointer to an ID3DXLine interface.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXCreateRenderToEnvMap Function

Creates a render environment map.

Syntax

HRESULT WINAPI D3DXCreateRenderToEnvMap(

    LPDIRECT3DDEVICE9 pDevice,
    UINT Size,
    UINT MipLevels,
    D3DFORMAT Format,
    BOOL DepthStencil,
    D3DFORMAT DepthStencilFormat,
    LPD3DXRENDERTOENVMAP *ppRenderToEnvMap
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, which is the device to associate with the render surface.
Size
[in] Size of the render surface.
MipLevels
[in] The number of mipmap levels.
Format
[in] Member of the D3DFORMAT enumerated type that describes the pixel format of the environment map.
DepthStencil
[in] If TRUE, the render surface supports a depth-stencil surface. Otherwise, this member is set to FALSE.
DepthStencilFormat
[in] If DepthStencil is set to TRUE, this parameter is a member of the D3DFORMAT enumerated type that describes the depth-stencil format of the environment map.
ppRenderToEnvMap
[out, retval] Address of a pointer to an ID3DXRenderToEnvMap interface that represents the created render environment map.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXCreateRenderToSurface Function

Creates a render surface.

Syntax

HRESULT WINAPI D3DXCreateRenderToSurface(

    LPDIRECT3DDEVICE9 pDevice,
    UINT Width,
    UINT Height,
    D3DFORMAT Format,
    BOOL DepthStencil,
    D3DFORMAT DepthStencilFormat,
    LPD3DXRENDERTOSURFACE *ppRenderToSurface
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device to be associated with the render surface.
Width
[in] Width of the render surface, in pixels.
Height
[in] Height of the render surface, in pixels.
Format
[in] Member of the D3DFORMAT enumerated type, describing the pixel format of the render surface.
DepthStencil
[in] If TRUE, the render surface supports a depth-stencil surface. Otherwise, this member is set to FALSE. This function will create a new depth buffer.
DepthStencilFormat
[in] If DepthStencil is set to TRUE, this parameter is a member of the D3DFORMAT enumerated type, describing the depth-stencil format of the render surface.
ppRenderToSurface
[out, retval] Address of a pointer to an ID3DXRenderToSurface interface, representing the created render surface.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXCreateSprite Function

Creates a sprite object which is associated with a particular device. Sprite objects are used to draw 2-D images to the screen.

Syntax

HRESULT WINAPI D3DXCreateSprite(

    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXSPRITE *ppSprite
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device to be associated with the sprite.
ppSprite
[out] Address of a pointer to an ID3DXSprite interface. This interface allows the user to access sprite functions.

Return Value

If the function succeeds, the return value is S_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

This interface can be used to draw two dimensional images in screen space of the associated device.

Function Information

Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXDebugMute Function

Turns on or off all D3DX debug output.

Syntax

BOOL WINAPI D3DXDebugMute(

    BOOL Mute
);

Parameters

Mute
[in] If TRUE, debugger output is halted; if FALSE, debug output is enabled.

Return Value

Returns the previous value of Mute.

Function Information

Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXGetDriverLevel Function

Returns the driver level.

Syntax

UINT WINAPI D3DXGetDriverLevel(

    LPDIRECT3DDEVICE9 pDevice
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface representing the device.

Return Value

The driver level. See remarks.

Remarks

This method returns the driver version, which is one of the following:

  • 700 - DirectX 7.0 level driver
  • 800 - DirectX 8.0 level driver
  • 900 - DirectX 9.0 level driver

Function Information

Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXGetFVFVertexSize Function

Returns the size of a vertex for a flexible vertex format (FVF).

Syntax

UINT WINAPI D3DXGetFVFVertexSize(

    DWORD FVF
);

Parameters

FVF
[in] FVF to be queried. A combination of D3DFVF.

Return Value

The FVF vertex size, in bytes.

Function Information

Header | d3dx9core.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


Math Functions
Microsoft DirectX 9.0 SDK Update (October 2004)

Math Functions

The math library provided by the D3DX utility library supplies functions to compute 3-D mathematical operations. Each of the functions can take the same object as the passed [in] and returned [out] parameters. Also, out parameters are typically returned as return values, so that the output of one math function can be used as a parameter for another math function.

Many of the functions are implemented in d3dx9math.inl.

The 3-D math application functions can be organized into the following groups.

Functions

  • D3DXColorAdd
  • D3DXColorAdjustContrast
  • D3DXColorAdjustSaturation
  • D3DXColorLerp
  • D3DXColorModulate
  • D3DXColorNegative
  • D3DXColorScale
  • D3DXColorSubtract
  • D3DXCreateMatrixStack
  • D3DXFloat16To32Array
  • D3DXFloat32To16Array
  • D3DXFresnelTerm
  • D3DXMatrixAffineTransformation
  • D3DXMatrixAffineTransformation2D
  • D3DXMatrixDecompose
  • D3DXMatrixDeterminant
  • D3DXMatrixIdentity
  • D3DXMatrixInverse
  • D3DXMatrixIsIdentity
  • D3DXMatrixLookAtLH
  • D3DXMatrixLookAtRH
  • D3DXMatrixMultiply
  • D3DXMatrixMultiplyTranspose
  • D3DXMatrixOrthoLH
  • D3DXMatrixOrthoOffCenterLH
  • D3DXMatrixOrthoOffCenterRH
  • D3DXMatrixOrthoRH
  • D3DXMatrixPerspectiveFovLH
  • D3DXMatrixPerspectiveFovRH
  • D3DXMatrixPerspectiveLH
  • D3DXMatrixPerspectiveOffCenterLH
  • D3DXMatrixPerspectiveOffCenterRH
  • D3DXMatrixPerspectiveRH
  • D3DXMatrixReflect
  • D3DXMatrixRotationAxis
  • D3DXMatrixRotationQuaternion
  • D3DXMatrixRotationX
  • D3DXMatrixRotationY
  • D3DXMatrixRotationYawPitchRoll
  • D3DXMatrixRotationZ
  • D3DXMatrixScaling
  • D3DXMatrixShadow
  • D3DXMatrixTransformation
  • D3DXMatrixTransformation2D
  • D3DXMatrixTranslation
  • D3DXMatrixTranspose
  • D3DXPlaneDot
  • D3DXPlaneDotCoord
  • D3DXPlaneDotNormal
  • D3DXPlaneFromPointNormal
  • D3DXPlaneFromPoints
  • D3DXPlaneIntersectLine
  • D3DXPlaneNormalize
  • D3DXPlaneScale
  • D3DXPlaneTransform
  • D3DXPlaneTransformArray
  • D3DXQuaternionBaryCentric
  • D3DXQuaternionConjugate
  • D3DXQuaternionDot
  • D3DXQuaternionExp
  • D3DXQuaternionIdentity
  • D3DXQuaternionInverse
  • D3DXQuaternionIsIdentity
  • D3DXQuaternionLength
  • D3DXQuaternionLengthSq
  • D3DXQuaternionLn
  • D3DXQuaternionMultiply
  • D3DXQuaternionNormalize
  • D3DXQuaternionRotationAxis
  • D3DXQuaternionRotationMatrix
  • D3DXQuaternionRotationYawPitchRoll
  • D3DXQuaternionSlerp
  • D3DXQuaternionSquad
  • D3DXQuaternionSquadSetup
  • D3DXQuaternionToAxisAngle
  • D3DXSHAdd
  • D3DXSHDot
  • D3DXSHEvalConeLight
  • D3DXSHEvalDirection
  • D3DXSHEvalDirectionalLight
  • D3DXSHEvalHemisphereLight
  • D3DXSHEvalSphericalLight
  • D3DXSHProjectCubeMap
  • D3DXSHRotate
  • D3DXSHRotateZ
  • D3DXSHScale
  • D3DXVec2Add
  • D3DXVec2BaryCentric
  • D3DXVec2CatmullRom
  • D3DXVec2CCW
  • D3DXVec2Dot
  • D3DXVec2Hermite
  • D3DXVec2Length
  • D3DXVec2LengthSq
  • D3DXVec2Lerp
  • D3DXVec2Maximize
  • D3DXVec2Minimize
  • D3DXVec2Normalize
  • D3DXVec2Scale
  • D3DXVec2Subtract
  • D3DXVec2Transform
  • D3DXVec2TransformArray
  • D3DXVec2TransformCoord
  • D3DXVec2TransformCoordArray
  • D3DXVec2TransformNormal
  • D3DXVec2TransformNormalArray
  • D3DXVec3Add
  • D3DXVec3BaryCentric
  • D3DXVec3CatmullRom
  • D3DXVec3Cross
  • D3DXVec3Dot
  • D3DXVec3Hermite
  • D3DXVec3Length
  • D3DXVec3LengthSq
  • D3DXVec3Lerp
  • D3DXVec3Maximize
  • D3DXVec3Minimize
  • D3DXVec3Normalize
  • D3DXVec3Project
  • D3DXVec3ProjectArray
  • D3DXVec3Scale
  • D3DXVec3Subtract
  • D3DXVec3Transform
  • D3DXVec3TransformArray
  • D3DXVec3TransformCoord
  • D3DXVec3TransformCoordArray
  • D3DXVec3TransformNormal
  • D3DXVec3TransformNormalArray
  • D3DXVec3Unproject
  • D3DXVec3UnprojectArray
  • D3DXVec4Add
  • D3DXVec4BaryCentric
  • D3DXVec4CatmullRom
  • D3DXVec4Cross
  • D3DXVec4Dot
  • D3DXVec4Hermite
  • D3DXVec4Length
  • D3DXVec4LengthSq
  • D3DXVec4Lerp
  • D3DXVec4Maximize
  • D3DXVec4Minimize
  • D3DXVec4Normalize
  • D3DXVec4Scale
  • D3DXVec4Subtract
  • D3DXVec4Transform
  • D3DXVec4TransformArray


D3DXColorAdd Function

Adds two color values together to create a new color value.

Syntax

D3DXCOLOR *D3DXColorAdd(

    D3DXCOLOR *pOut,
    CONST D3DXCOLOR *pC1,
    CONST D3DXCOLOR *pC2
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC1
[in] Pointer to a source D3DXCOLOR structure.
pC2
[in] Pointer to a source D3DXCOLOR structure.

Return Value

This function returns a pointer to a D3DXCOLOR structure that is the sum of two color values.

Remarks

The return value for this function is the same value returned in pOut. In this way, the D3DXColorAdd function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXColorModulate, D3DXColorSubtract


D3DXColorAdjustContrast Function

Adjusts the contrast value of a color.

Syntax

D3DXCOLOR *WINAPI D3DXColorAdjustContrast(

    D3DXCOLOR *pOut,
    const D3DXCOLOR *pC,
    FLOAT c
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC
[in] Pointer to a source D3DXCOLOR structure.
c
[in] Contrast value. This parameter linearly interpolates between fifty percent gray and the color, pC. There are not limits on the value of c. If this parameter is zero, then the returned color is fifty percent gray. If this parameter is 1, then the returned color is the original color.

Return Value

This function returns a pointer to a D3DXCOLOR structure that is the result of the contrast adjustment.

Remarks

The input alpha channel is copied, unmodified, to the output alpha channel.

The return value for this function is the same value returned in the pOut parameter. In this way, this function can be used as a parameter for another function.

This function interpolates the red, green, and blue color components of a D3DXCOLOR structure between fifty percent gray and a specified contrast value, as shown in the following example.

pOut->r = 0.5f + c * (pC->r - 0.5f);

If c is greater than 0 and less than 1, the contrast is decreased. If c is greater than 1, the contrast is increased.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXColorAdjustSaturation


D3DXColorAdjustSaturation Function

Adjusts the saturation value of a color.

Syntax

D3DXCOLOR *WINAPI D3DXColorAdjustSaturation(

    D3DXCOLOR *pOut,
    const D3DXCOLOR *pC,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC
[in] Pointer to a source D3DXCOLOR structure.
s
[in] Saturation value. This parameter linearly interpolates between the color converted to grayscale and the original color, pC. There are no limits on the value of s. If s is 0, the returned color is the grayscale color. If s is 1, the returned color is the original color.

Return Value

This function returns a pointer to a D3DXCOLOR structure that is the result of the saturation adjustment.

Remarks

The input alpha channel is copied, unmodified, to the output alpha channel.

The return value for this function is the same value returned in the pOut parameter. In this way, this function can be used as a parameter for another function.

This function interpolates the red, green, and blue color components of a D3DXCOLOR structure between an unsaturated color and a color, as shown in the following example.

    // Approximate values for each component's contribution to luminance.
    // Based upon the NTSC standard described in ITU-R Recommendation BT.709.
    FLOAT grey = pC->r * 0.2125f + pC->g * 0.7154f + pC->b * 0.0721f;

    pOut->r = grey + s * (pC->r - grey);

If s is greater than 0 and less than 1, the saturation is decreased. If s is greater than 1, the saturation is increased.

The grayscale color is computed as:

r = g = b = 0.2125*r + 0.7154*g + 0.0721*b

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXColorAdjustContrast


D3DXColorLerp Function

Uses linear interpolation to create a color value.

Syntax

D3DXCOLOR *D3DXColorLerp(

    D3DXCOLOR *pOut,
    CONST D3DXCOLOR *pC1,
    CONST D3DXCOLOR *pC2,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC1
[in] Pointer to a source D3DXCOLOR structure.
pC2
[in] Pointer to a source D3DXCOLOR structure.
s
[in] Parameter that linearly interpolates between the colors, pC1 and pC2, treating them both as 4-D vectors. There are no limits on the value of s.

Return Value

This function returns a pointer to a D3DXCOLOR structure that is the result of the linear interpolation.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorLerp function can be used as a parameter for another function.

This function interpolates the red, green, blue, and alpha components of a D3DXCOLOR structure between two colors, as shown in the following example.

    pOut->r = pC1->r + s * (pC2->r - pC1->r);

If you are linearly interpolating between the colors A and B, and s is 0, the resulting color is A. If s is 1, the resulting color is color B.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXColorModulate, D3DXColorNegative, D3DXColorScale


D3DXColorModulate Function

Blends two colors.

Syntax

D3DXCOLOR *D3DXColorModulate(

    D3DXCOLOR *pOut,
    CONST D3DXCOLOR *pC1,
    CONST D3DXCOLOR *pC2
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC1
[in] Pointer to a source D3DXCOLOR structure.
pC2
[in] Pointer to a source D3DXCOLOR structure.

Return Value

This function returns a pointer to a D3DXCOLOR structure that is the result of the blending operation.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorModulate function can be used as a parameter for another function.

This function blends together two colors by multiplying matching color components, as shown in the following example.

    pOut->r = pC1->r * pC2->r;

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXColorLerp, D3DXColorNegative, D3DXColorScale


D3DXColorNegative Function

Creates the negative color value of a color value.

Syntax

D3DXCOLOR *D3DXColorNegative(

    D3DXCOLOR *pOut,
    CONST D3DXCOLOR *pC
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC
[in] Pointer to a source D3DXCOLOR structure.

Return Value

This function returns a pointer to a D3DXCOLOR structure that is the negative color value of the color value.

Remarks

The input alpha channel is copied, unmodified, to the output alpha channel.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorNegative function can be used as a parameter for another function.

This function returns the negative color value by subtracting 1.0 from the color components of the D3DXCOLOR structure, as shown in the following example.

pOut->r = 1.0f - pC->r;

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXColorLerp, D3DXColorModulate, D3DXColorScale


D3DXColorScale Function

Scales a color value.

Syntax

D3DXCOLOR *D3DXColorScale(

    D3DXCOLOR *pOut,
    CONST D3DXCOLOR *pC,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC
[in] Pointer to a source D3DXCOLOR structure.
s
[in] Scale factor. It scales the color, treating it like a 4-D vector. There are no limits on the value of s. If s is 1, the resulting color is the original color.

Return Value

This function returns a pointer to a D3DXCOLOR structure that is the scaled color value.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorScale function can be used as a parameter for another function.

This function computes the scaled color value by multiplying the color components of the D3DXCOLOR structure by the specified scale factor, as shown in the following example.

    pOut->r = pC->r * s;

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXColorLerp, D3DXColorModulate, D3DXColorNegative


D3DXColorSubtract Function

Subtracts two color values to create a new color value.

Syntax

D3DXCOLOR *D3DXColorSubtract(

    D3DXCOLOR *pOut,
    CONST D3DXCOLOR *pC1,
    CONST D3DXCOLOR *pC2
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC1
[in] Pointer to a source D3DXCOLOR structure.
pC2
[in] Pointer to a source D3DXCOLOR structure.

Return Value

This function returns a pointer to a D3DXCOLOR structure that is the difference between two color values.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorSubtract function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXColorAdd


D3DXCreateMatrixStack Function

Creates an instance of the ID3DXMatrixStack interface.

Syntax

HRESULT WINAPI D3DXCreateMatrixStack(

    DWORD Flags,
    LPD3DXMATRIXSTACK *ppStack
);

Parameters

Flags
[in] Not implemented. Specify zero.
ppStack
[out] Address of a pointer filled with an ID3DXMatrixStack interface pointer if the function succeeds.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXFloat16To32Array Function

Converts an array of 16-bit floats to 32-bit floats.

Syntax

FLOAT *WINAPI D3DXFloat16To32Array(

    FLOAT *pOut,
    const D3DXFLOAT16 *pIn,
    UINT n
);

Parameters

pOut
[in, out] Pointer to the array of 32-bit floats.
pIn
[in] Pointer to an array of 16-bit floats.
n
[in] Number of elements in the array.

Return Value

Pointer to an array of 32-bit floats.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXFloat32To16Array Function

Converts an array of 32-bit floats to 16-bit floats.

Syntax

D3DXFLOAT16 *WINAPI D3DXFloat32To16Array(

    D3DXFLOAT16* pOut,
    CONST FLOAT* pIn,
    UINT n
);

Parameters

pOut
[in, out] Pointer to the array of 16-bit floats.
pIn
[in] Pointer to an array of 32-bit floats.
n
[in] The number of elements in the array.

Return Value

Pointer to an array of 16-bit floats.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXFresnelTerm Function

Calculate the Fresnel term.

Syntax

FLOAT WINAPI D3DXFresnelTerm(

    FLOAT CosTheta,
    FLOAT RefractionIndex
);

Parameters

CosTheta
[in] The value must be between 0 and 1.
RefractionIndex
[in] The refraction index of a material. The value must be greater than 1.

Return Value

This function returns the Fresnel term for unpolarized light. CosTheta is the cosine of the incident angle.

Remarks

To find the Fresnel term (F):

If A is angle of incidence and B is the angle of refraction, then

F = 0.5 * [tan2(A - B) / tan2(A + B) + sin2(A - B) / sin2(A + B)]
  = 0.5 * sin2(A - B) / sin2(A + B) * [cos2(A + B) / cos2(A - B) + 1]

Let r   = sina(A) / sin(B)      (the relative refractive index)
Let c   = cos(A)
Let g   = (r2 + c2 - 1)1/2

Then, expanding using the trig identities and simplifying, you get:

F = 0.5 * (g + c)2 / (g - c)2 * ([c(g + c) - 1]2 / [c(g - c) + 1]2 + 1)

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXMatrixAffineTransformation Function

Builds a 3-D affine transformation matrix. NULL arguments are treated as identity transformations.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixAffineTransformation(

    D3DXMATRIX *pOut,
    FLOAT Scaling,
    const D3DXVECTOR3 *pRotationCenter,
    const D3DXQUATERNION *pRotation,
    const D3DXVECTOR3 *pTranslation
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
Scaling
[in] Scaling factor.
pRotationCenter
[in] Pointer to a D3DXVECTOR3 structure, a point identifying the center of rotation. If this argument is NULL, an identity Mrc matrix is applied to the formula in Remarks.
pRotation
[in] Pointer to a D3DXQUATERNION structure that specifies the rotation. If this argument is NULL, an identity Mr matrix is applied to the formula in Remarks.
pTranslation
[in] Pointer to a D3DXVECTOR3 structure representing the translation. If this argument is NULL, an identity Mt matrix is applied to the formula in Remarks.

Return Value

Pointer to a D3DXMATRIX structure that is an affine transformation matrix.

Remarks

This function calculates the affine transformation matrix with the following formula, with matrix concatenation evaluated in left-to-right order:

Mout = Ms * (Mrc)-1 * Mr * Mrc * Mt

where:

Mout = output matrix (pOut)

Ms = scaling matrix (Scaling)

Mrc = center of rotation matrix (pRotationCenter)

Mr = rotation matrix (pRotation)

Mt = translation matrix (pTranslation)

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixAffineTransformation function can be used as a parameter for another function.

For 2-D affine transformations, use D3DXMatrixAffineTransformation2D.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixTransformation, Matrix Transforms


D3DXMatrixAffineTransformation2D Function

Builds a 2-D affine transformation matrix in the x-y plane. NULL arguments are treated as identity transformations.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixAffineTransformation2D(

    D3DXMATRIX *pOut,
    FLOAT Scaling,
    CONST D3DXVECTOR2 *pRotationCenter,
    FLOAT Rotation,
    CONST D3DXVECTOR2 *pTranslation
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
Scaling
[in] Scaling factor.
pRotationCenter
[in] Pointer to a D3DXVECTOR2 structure, a point identifying the center of rotation. If this argument is NULL, an identity Mrc matrix is applied to the formula in Remarks.
Rotation
[in] The angle of rotation.
pTranslation
[in] Pointer to a D3DXVECTOR2 structure, representing the translation. If this argument is NULL, an identity Mt matrix is applied to the formula in Remarks.

Return Value

Pointer to a D3DXMATRIX structure that is an affine transformation matrix.

Remarks

This function calculates the affine transformation matrix with the following formula, with matrix concatenation evaluated in left-to-right order:

Mout = Ms * (Mrc)-1 * Mr * Mrc * Mt

where:

Mout = output matrix (pOut)

Ms = scaling matrix (Scaling)

Mrc = center of rotation matrix (pRotationCenter)

Mr = rotation matrix (Rotation)

Mt = translation matrix (pTranslation)

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixAffineTransformation2D function can be used as a parameter for another function.

For 3-D affine transformations, use D3DXMatrixAffineTransformation.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixTransformation2D, Matrix Transforms


D3DXMatrixDecompose Function

Breaks down a general 3-D transformation matrix into its scalar, rotational, and translational components.

Syntax

HRESULT WINAPI D3DXMatrixDecompose(

    D3DXVECTOR3 *pOutScale,
    D3DXQUATERNION *pOutRotation,
    D3DXVECTOR3 *pOutTranslation,
    const D3DXMATRIX *pM
);

Parameters

pOutScale
[in, out] Pointer to the output D3DXVECTOR3 that contains scaling factors applied along the x, y, and z-axes.
pOutRotation
[in, out] Pointer to the D3DXQUATERNION structure that describes the rotation.
pOutTranslation
[in, out] Pointer to the D3DXVECTOR3 vector that describes the translation.
pM
[in] Pointer to an input D3DXMATRIX matrix to decompose.

Return Value

If the function succeeds, the return value is S_OK.

If the function fails, the return value can be the following:

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXMatrixDeterminant Function

Returns the determinant of a matrix.

Syntax

FLOAT WINAPI D3DXMatrixDeterminant(

    CONST D3DXMATRIX *pM
);

Parameters

pM
[in] Pointer to the source D3DXMATRIX structure.

Return Value

Returns the determinant of the matrix.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXMatrixIdentity Function

Creates an identity matrix.

Syntax

D3DXMATRIX *D3DXMatrixIdentity(

    D3DXMATRIX *pOut
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.

Return Value

Pointer to a D3DXMATRIX structure that is the identity matrix.

Remarks

The identity matrix is a matrix in which all coefficients are 0 except the [1,1][2,2][3,3][4,4] coefficients, which are set to 1. The identity matrix is special in that when it is applied to vertices, they are unchanged. The identity matrix is used as the starting point for matrices that will modify vertex values to create rotations, translations, and any other transformations that can be represented by a 4 ×4 matrix.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixIdentity function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixIsIdentity


D3DXMatrixInverse Function

Calculates the inverse of a matrix.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixInverse(

    D3DXMATRIX *pOut,
    FLOAT *pDeterminant,
    CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pDeterminant
[in, out] Pointer to a FLOAT value containing the determinant of the matrix. If the determinant is not needed, set this parameter to NULL.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Value

Pointer to a D3DXMATRIX structure that is the inverse of the matrix. If matrix inversion fails, NULL is returned.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixInverse function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXMatrixIsIdentity Function

Determines if a matrix is an identity matrix.

Syntax

BOOL D3DXMatrixIsIdentity(

    CONST D3DXMATRIX *pM
);

Parameters

pM
[in] Pointer to the D3DXMATRIX structure that will be tested for identity.

Return Value

If the matrix is an identity matrix, this function returns TRUE. Otherwise, this function returns FALSE.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixIdentity


D3DXMatrixLookAtLH Function

Builds a left-handed, look-at matrix.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixLookAtLH(

    D3DXMATRIX *pOut,
    CONST D3DXVECTOR3 *pEye,
    CONST D3DXVECTOR3 *pAt,
    CONST D3DXVECTOR3 *pUp
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pEye
[in] Pointer to the D3DXVECTOR3 structure that defines the eye point. This value is used in translation.
pAt
[in] Pointer to the D3DXVECTOR3 structure that defines the camera look-at target.
pUp
[in] Pointer to the D3DXVECTOR3 structure that defines the current world's up, usually [0, 1, 0].

Return Value

Pointer to a D3DXMATRIX structure that is a left-handed, look-at matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixLookAtLH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

zaxis = normal(At - Eye)
xaxis = normal(cross(Up, zaxis))
yaxis = cross(zaxis, xaxis)

 xaxis.x           yaxis.x           zaxis.x          0
 xaxis.y           yaxis.y           zaxis.y          0
 xaxis.z           yaxis.z           zaxis.z          0
-dot(xaxis, eye)  -dot(yaxis, eye)  -dot(zaxis, eye)  1

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixLookAtRH


D3DXMatrixLookAtRH Function

Builds a right-handed, look-at matrix.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixLookAtRH(

    D3DXMATRIX *pOut,
    CONST D3DXVECTOR3 *pEye,
    CONST D3DXVECTOR3 *pAt,
    CONST D3DXVECTOR3 *pUp
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pEye
[in] Pointer to the D3DXVECTOR3 structure that defines the eye point. This value is used in translation.
pAt
[in] Pointer to the D3DXVECTOR3 structure that defines the camera look-at target.
pUp
[in] Pointer to the D3DXVECTOR3 structure that defines the current world's up, usually [0, 1, 0].

Return Value

Pointer to a D3DXMATRIX structure that is a right-handed, look-at matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixLookAtRH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

zaxis = normal(Eye - At)
xaxis = normal(cross(Up, zaxis))
yaxis = cross(zaxis, xaxis)

 xaxis.x           yaxis.x           zaxis.x          0
 xaxis.y           yaxis.y           zaxis.y          0
 xaxis.z           yaxis.z           zaxis.z          0
-dot(xaxis, eye)  -dot(yaxis, eye)  -dot(zaxis, eye)  1

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixLookAtLH


D3DXMatrixMultiply Function

Determines the product of two matrices.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixMultiply(

    D3DXMATRIX *pOut,
    CONST D3DXMATRIX *pM1,
    CONST D3DXMATRIX *pM2
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pM1
[in] Pointer to a source D3DXMATRIX structure.
pM2
[in] Pointer to a source D3DXMATRIX structure.

Return Value

Pointer to a D3DXMATRIX structure that is the product of two matrices.

Remarks

The result represents the transformation M1 followed by the transformation M2 (Out = M1 * M2).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixMultiply function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionMultiply


D3DXMatrixMultiplyTranspose Function

Calculates the transposed product of two matrices.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixMultiplyTranspose(

    D3DXMATRIX* pOut,
    const D3DXMATRIX* pM1,
    const D3DXMATRIX* pM2
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pM1
[in] Pointer to a source D3DXMATRIX structure.
pM2
[in] Pointer to a source D3DXMATRIX structure.

Return Value

Pointer to a D3DXMATRIX structure that is the product of two matrices.

Remarks

The result is the transposed of the product of two transformation matrices, Out = T(M1*M2).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixMultiplyTranspose function can be used as a parameter for another function.

This function is useful to set matrices as constants for vertex and pixel shaders.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixMultiply, D3DXQuaternionMultiply


D3DXMatrixOrthoLH Function

Builds a left-handed orthogonal projection matrix.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixOrthoLH(

    D3DXMATRIX *pOut,
    FLOAT w,
    FLOAT h,
    FLOAT zn,
    FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that contains the resulting matrix.
w
[in] Width of the view volume.
h
[in] Height of the view volume.
zn
[in] Minimum z-value of the view volume which is referred to as z-near.
zf
[in] Maximum z-value of the view volume which is referred to as z-far.

Return Value

Pointer to a D3DXMATRIX structure that is a left-handed orthogonal projection matrix.

Remarks

An orthogonal matrix is an invertible matrix for which the inverse of the matrix is equal to the transpose of the matrix.

All the parameters of the D3DXMatrixOrthoLH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixOrthoLH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2/w  0    0           0
0    2/h  0           0
0    0    1/(zf-zn)   0
0    0    zn/(zn-zf)  1

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixOrthoRH, D3DXMatrixOrthoOffCenterRH, D3DXMatrixOrthoOffCenterLH


D3DXMatrixOrthoOffCenterLH Function

Builds a customized, left-handed orthogonal projection matrix.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixOrthoOffCenterLH(

    D3DXMATRIX *pOut,
    FLOAT l,
    FLOAT r,
    FLOAT b,
    FLOAT t,
    FLOAT zn,
    FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
l
[in] Minimum x-value of view volume.
r
[in] Maximum x-value of view volume.
b
[in] Minimum y-value of view volume.
t
[in] Maximum y-value of view volume.
zn
[in] Minimum z-value of the view volume.
zf
[in] Maximum z-value of the view volume.

Return Value

Pointer to a D3DXMATRIX structure that is a customized, left-handed orthogonal projection matrix.

Remarks

An orthogonal matrix is an invertible matrix for which the inverse of the matrix is equal to the transpose of the matrix.

The D3DXMatrixOrthoLH function is a special case of the D3DXMatrixOrthoOffCenterLH function. To create the same projection using D3DXMatrixOrthoOffCenterLH, use the following values:
                l = -w/2,
                r = w/2,
                b = -h/2, and
                t = h/2.

All the parameters of the D3DXMatrixOrthoOffCenterLH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixOrthoOffCenterLH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2/(r-l)      0            0           0
0            2/(t-b)      0           0
0            0            1/(zf-zn)   0
(l+r)/(l-r)  (t+b)/(b-t)  zn/(zn-zf)  1

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixOrthoRH, D3DXMatrixOrthoLH, D3DXMatrixOrthoOffCenterRH


D3DXMatrixOrthoOffCenterRH Function

Builds a customized, right-handed orthogonal projection matrix.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixOrthoOffCenterRH(

    D3DXMATRIX *pOut,
    FLOAT l,
    FLOAT r,
    FLOAT b,
    FLOAT t,
    FLOAT zn,
    FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
l
[in] Minimum x-value of view volume.
r
[in] Maximum x-value of view volume.
b
[in] Minimum y-value of view volume.
t
[in] Maximum y-value of view volume.
zn
[in] Minimum z-value of the view volume.
zf
[in] Maximum z-value of the view volume.

Return Value

Pointer to a D3DXMATRIX structure that is a customized, right-handed orthogonal projection matrix.

Remarks

An orthogonal matrix is an invertible matrix for which the inverse of the matrix is equal to the transpose of the matrix.

The D3DXMatrixOrthoRH function is a special case of the D3DXMatrixOrthoOffCenterRH function. To create the same projection using D3DXMatrixOrthoOffCenterRH, use the following values:
                l = -w/2,
                r = w/2,
                b = -h/2, and
                t = h/2.

All the parameters of the D3DXMatrixOrthoOffCenterRH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixOrthoOffCenterRH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2/(r-l)      0            0           0
0            2/(t-b)      0           0
0            0            1/(zn-zf)   0
(l+r)/(l-r)  (t+b)/(b-t)  zn/(zn-zf)  1

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixOrthoRH, D3DXMatrixOrthoLH, D3DXMatrixOrthoOffCenterLH


D3DXMatrixOrthoRH Function

Builds a right-handed orthogonal projection matrix.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixOrthoRH(

    D3DXMATRIX *pOut,
    FLOAT w,
    FLOAT h,
    FLOAT zn,
    FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
w
[in] Width of the view volume.
h
[in] Height of the view volume.
zn
[in] Minimum z-value of the view volume.
zf
[in] Maximum z-value of the view volume.

Return Value

Pointer to a D3DXMATRIX structure that is a right-handed orthogonal projection matrix.

Remarks

An orthogonal matrix is an invertible matrix for which the inverse of the matrix is equal to the transpose of the matrix.

All the parameters of the D3DXMatrixOrthoRH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixOrthoRH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2/w  0    0           0
0    2/h  0           0
0    0    1/(zn-zf)   0
0    0    zn/(zn-zf)  1

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixOrthoLH, D3DXMatrixOrthoOffCenterRH, D3DXMatrixOrthoOffCenterLH


D3DXMatrixPerspectiveFovLH Function

Builds a left-handed perspective projection matrix based on a field of view.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixPerspectiveFovLH(

    D3DXMATRIX *pOut,
    FLOAT fovy,
    FLOAT Aspect,
    FLOAT zn,
    FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
fovy
[in] Field of view in the y direction, in radians.
Aspect
[in] Aspect ratio, defined as view space width divided by height.
zn
[in] Z-value of the near view-plane.
zf
[in] Z-value of the far view-plane.

Return Value

Pointer to a D3DXMATRIX structure that is a left-handed perspective projection matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveFovLH function can be used as a parameter for another function.

This function computes the returned matrix as shown:

xScale     0          0               0
0        yScale       0               0
0          0       zf/(zf-zn)         1
0          0       -zn*zf/(zf-zn)     0
where:
yScale = cot(fovY/2)

xScale = aspect ratio * yScale

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixPerspectiveRH, D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovRH, D3DXMatrixPerspectiveOffCenterRH, D3DXMatrixPerspectiveOffCenterLH


D3DXMatrixPerspectiveFovRH Function

Builds a right-handed perspective projection matrix based on a field of view.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixPerspectiveFovRH(

    D3DXMATRIX *pOut,
    FLOAT fovy,
    FLOAT Aspect,
    FLOAT zn,
    FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
fovy
[in] Field of view in the y direction, in radians.
Aspect
[in] Aspect ratio, defined as view space width divided by height.
zn
[in] Z-value of the near view-plane.
zf
[in] Z-value of the far view-plane.

Return Value

Pointer to a D3DXMATRIX structure that is a right-handed perspective projection matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveFovRH function can be used as a parameter for another function.

This function computes the returned matrix as shown.

xScale     0          0              0
0        yScale       0              0
0        0        zf/(zn-zf)        -1
0        0        zn*zf/(zn-zf)      0
where:
yScale = cot(fovY/2)

xScale = aspect ratio * yScale

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixPerspectiveRH, D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterRH, D3DXMatrixPerspectiveOffCenterLH


D3DXMatrixPerspectiveLH Function

Builds a left-handed perspective projection matrix

Syntax

D3DXMATRIX *WINAPI D3DXMatrixPerspectiveLH(

    D3DXMATRIX *pOut,
    FLOAT w,
    FLOAT h,
    FLOAT zn,
    FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
w
[in] Width of the view volume at the near view-plane.
h
[in] Height of the view volume at the near view-plane.
zn
[in] Z-value of the near view-plane.
zf
[in] Z-value of the far view-plane.

Return Value

Pointer to a D3DXMATRIX structure that is a left-handed perspective projection matrix.

Remarks

All the parameters of the D3DXMatrixPerspectiveLH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveLH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2*zn/w  0       0              0
0       2*zn/h  0              0
0       0       zf/(zf-zn)     1
0       0       zn*zf/(zn-zf)  0

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixPerspectiveRH, D3DXMatrixPerspectiveFovRH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterRH, D3DXMatrixPerspectiveOffCenterLH


D3DXMatrixPerspectiveOffCenterLH Function

Builds a customized, left-handed perspective projection matrix.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixPerspectiveOffCenterLH(

    D3DXMATRIX *pOut,
    FLOAT l,
    FLOAT r,
    FLOAT b,
    FLOAT t,
    FLOAT zn,
    FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
l
[in] Minimum x-value of the view volume.
r
[in] Maximum x-value of the view volume.
b
[in] Minimum y-value of the view volume.
t
[in] Maximum y-value of the view volume.
zn
[in] Minimum z-value of the view volume.
zf
[in] Maximum z-value of the view volume.

Return Value

Pointer to a D3DXMATRIX structure that is a customized, left-handed perspective projection matrix.

Remarks

All the parameters of the D3DXMatrixPerspectiveOffCenterLH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveOffCenterLH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2*zn/(r-l)   0            0              0
0            2*zn/(t-b)   0              0
(l+r)/(l-r)  (t+b)/(b-t)  zf/(zf-zn)     1
0            0            zn*zf/(zn-zf)  0

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixPerspectiveRH, D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovRH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterRH


D3DXMatrixPerspectiveOffCenterRH Function

Builds a customized, right-handed perspective projection matrix.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixPerspectiveOffCenterRH(

    D3DXMATRIX *pOut,
    FLOAT l,
    FLOAT r,
    FLOAT b,
    FLOAT t,
    FLOAT zn,
    FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
l
[in] Minimum x-value of the view volume.
r
[in] Maximum x-value of the view volume.
b
[in] Minimum y-value of the view volume.
t
[in] Maximum y-value of the view volume.
zn
[in] Minimum z-value of the view volume.
zf
[in] Maximum z-value of the view volume.

Return Value

Pointer to a D3DXMATRIX structure that is a customized, right-handed perspective projection matrix.

Remarks

All the parameters of the D3DXMatrixPerspectiveOffCenterRH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveOffCenterRH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2*zn/(r-l)   0            0                0
0            2*zn*(t-b)   0                0
(l+r)/(r-l)  (t+b)/(t-b)  zf/(zn-zf)      -1
0            0            zn*zf/(zn-zf)    0

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixPerspectiveRH, D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovRH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterLH


D3DXMatrixPerspectiveRH Function

Builds a right-handed perspective projection matrix.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixPerspectiveRH(

    D3DXMATRIX *pOut,
    FLOAT w,
    FLOAT h,
    FLOAT zn,
    FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
w
[in] Width of the view volume at the near view-plane.
h
[in] Height of the view volume at the near view-plane.
zn
[in] Z-value of the near view-plane.
zf
[in] Z-value of the far view-plane.

Return Value

Pointer to a D3DXMATRIX structure that is a right-handed perspective projection matrix.

Remarks

All the parameters of the D3DXMatrixPerspectiveRH function are distances in camera space. The parameters describe the dimensions of the view volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveRH function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

2*zn/w  0       0              0
0       2*zn/h  0              0
0       0       zf/(zn-zf)    -1
0       0       zn*zf/(zn-zf)  0

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovRH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterRH, D3DXMatrixPerspectiveOffCenterLH


D3DXMatrixReflect Function

Builds a matrix that reflects the coordinate system about a plane.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixReflect(

    D3DXMATRIX *pOut,
    CONST D3DXPLANE *pPlane
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pPlane
[in] Pointer to the source D3DXPLANE structure.

Return Value

Pointer to a D3DXMATRIX structure that reflects the coordinate system about the source plane.

Remarks

This function normalizes the plane equation before it creates the reflected matrix.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixReflect function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.

P = normalize(Plane);

-2 * P.a * P.a + 1  -2 * P.b * P.a      -2 * P.c * P.a        0
-2 * P.a * P.b      -2 * P.b * P.b + 1  -2 * P.c * P.b        0
-2 * P.a * P.c      -2 * P.b * P.c      -2 * P.c * P.c + 1    0
-2 * P.a * P.d      -2 * P.b * P.d      -2 * P.c * P.d        1

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXMatrixRotationAxis Function

Builds a matrix that rotates around an arbitrary axis.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixRotationAxis(

    D3DXMATRIX *pOut,
    CONST D3DXVECTOR3 *pV,
    FLOAT Angle
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pV
[in] Pointer to the arbitrary axis. See D3DXVECTOR3.
Angle
[in] Angle of rotation in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Value

Pointer to a D3DXMATRIX structure rotated around the specified axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationAxis function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixRotationQuaternion, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationYawPitchRoll, D3DXMatrixRotationZ


D3DXMatrixRotationQuaternion Function

Builds a rotation matrix from a quaternion.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixRotationQuaternion(

    D3DXMATRIX *pOut,
    CONST D3DXQUATERNION *pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Value

Pointer to a D3DXMATRIX structure built from the source quaternion.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationQuaternion function can be used as a parameter for another function.

For information about how to calculate quaternion values from a direction vector ( x, y, z ) and an angle of rotation, see D3DXQUATERNION.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationYawPitchRoll, D3DXMatrixRotationZ


D3DXMatrixRotationX Function

Builds a matrix that rotates around the x-axis.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixRotationX(

    D3DXMATRIX *pOut,
    FLOAT Angle
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
Angle
[in] Angle of rotation in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Value

Pointer to a D3DXMATRIX structure rotated around the x-axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationX function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationQuaternion, D3DXMatrixRotationY, D3DXMatrixRotationYawPitchRoll, D3DXMatrixRotationZ


D3DXMatrixRotationY Function

Builds a matrix that rotates around the y-axis.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixRotationY(

    D3DXMATRIX *pOut,
    FLOAT Angle
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
Angle
[in] Angle of rotation in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Value

Pointer to a D3DXMATRIX structure rotated around the y-axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationY function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationQuaternion, D3DXMatrixRotationX, D3DXMatrixRotationYawPitchRoll, D3DXMatrixRotationZ


D3DXMatrixRotationYawPitchRoll Function

Builds a matrix with a specified yaw, pitch, and roll.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixRotationYawPitchRoll(

    D3DXMATRIX *pOut,
    FLOAT Yaw,
    FLOAT Pitch,
    FLOAT Roll
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
Yaw
[in] Yaw around the y-axis, in radians.
Pitch
[in] Pitch around the x-axis, in radians.
Roll
[in] Roll around the z-axis, in radians.

Return Value

Pointer to a D3DXMATRIX structure with the specified yaw, pitch, and roll.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationYawPitchRoll function can be used as a parameter for another function.

The order of transformations is roll first, then pitch, then yaw. Relative to the object's local coordinate axis, this is equivalent to rotation around the z-axis, followed by rotation around the x-axis, followed by rotation around the y-axis.

Roll, pitch, yaw diagram

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationQuaternion, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationZ


D3DXMatrixRotationZ Function

Builds a matrix that rotates around the z-axis.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixRotationZ(

    D3DXMATRIX *pOut,
    FLOAT Angle
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
Angle
[in] Angle of rotation, in radians. Angles are measured clockwise when viewed from the rotation axis (positive side) toward the origin.

Return Value

Pointer to a D3DXMATRIX structure rotated around the z-axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationZ function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationQuaternion, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationYawPitchRoll


D3DXMatrixScaling Function

Builds a matrix that scales along the x-axis, the y-axis, and the z-axis.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixScaling(

    D3DXMATRIX *pOut,
    FLOAT sx,
    FLOAT sy,
    FLOAT sz
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
sx
[in] Scaling factor that is applied along the x-axis.
sy
[in] Scaling factor that is applied along the y-axis.
sz
[in] Scaling factor that is applied along the z-axis.

Return Value

Pointer to the scaling transformation D3DXMATRIX.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixScaling function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXMatrixShadow Function

Builds a matrix that flattens geometry into a plane.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixShadow(

    D3DXMATRIX *pOut,
    CONST D3DXVECTOR4 *pLight,
    CONST D3DXPLANE *pPlane
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pLight
[in] Pointer to a D3DXVECTOR4 structure describing the light's position.
pPlane
[in] Pointer to the source D3DXPLANE structure.

Return Value

Pointer to a D3DXMATRIX structure that flattens geometry into a plane.

Remarks

The D3DXMatrixShadow function flattens geometry into a plane, as if casting a shadow from a light.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixShadow function can be used as a parameter for another function.

This function uses the following formula to compute the returned matrix.
P = normalize(Plane);
L = Light;
d = dot(P, L)

P.a * L.x + d  P.a * L.y      P.a * L.z      P.a * L.w
P.b * L.x      P.b * L.y + d  P.b * L.z      P.b * L.w
P.c * L.x      P.c * L.y      P.c * L.z + d  P.c * L.w
P.d * L.x      P.d * L.y      P.d * L.z      P.d * L.w + d

If the light's w-component is 0, the ray from the origin to the light represents a directional light. If it is 1, the light is a point light.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXMatrixTransformation Function

Builds a transformation matrix. NULL arguments are treated as identity transformations.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixTransformation(

    D3DXMATRIX *pOut,
    CONST D3DXVECTOR3 *pScalingCenter,
    CONST D3DXQUATERNION *pScalingRotation,
    CONST D3DXVECTOR3 *pScaling,
    CONST D3DXVECTOR3 *pRotationCenter,
    CONST D3DXQUATERNION *pRotation,
    CONST D3DXVECTOR3 *pTranslation
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pScalingCenter
[in] Pointer to a D3DXVECTOR3 structure, identifying the scaling center point. If this argument is NULL, an identity Msc matrix is applied to the formula in Remarks.
pScalingRotation
[in] Pointer to a D3DXQUATERNION structure that specifies the scaling rotation. If this argument is NULL, an identity Msr matrix is applied to the formula in Remarks.
pScaling
[in] Pointer to a D3DXVECTOR3 structure, the scaling vector. If this argument is NULL, an identity Ms matrix is applied to the formula in Remarks.
pRotationCenter
[in] Pointer to a D3DXVECTOR3 structure, a point that identifies the center of rotation. If this argument is NULL, an identity Mrc matrix is applied to the formula in Remarks.
pRotation
[in] Pointer to a D3DXQUATERNION structure that specifies the rotation. If this argument is NULL, an identity Mr matrix is applied to the formula in Remarks.
pTranslation
[in] Pointer to a D3DXVECTOR3 structure, representing the translation. If this argument is NULL, an identity Mt matrix is applied to the formula in Remarks.

Return Value

Pointer to a D3DXMATRIX structure that is the transformation matrix.

Remarks

This function calculates the transformation matrix with the following formula, with matrix concatenation evaluated in left-to-right order:

Mout = (Msc)-1 * (Msr)-1 * Ms * Msr * Msc * (Mrc)-1 * Mr * Mrc * Mt

where:

Mout = output matrix (pOut)

Msc = scaling center matrix (pScalingCenter)

Msr = scaling rotation matrix (pScalingRotation)

Ms = scaling matrix (pScaling)

Mrc = center of rotation matrix (pRotationCenter)

Mr = rotation matrix (pRotation)

Mt = translation matrix (pTranslation)

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixTransformation function can be used as a parameter for another function.

For 2-D transformations, use D3DXMatrixTransformation2D.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixAffineTransformation, Matrix Transforms


D3DXMatrixTransformation2D Function

Builds a 2-D transformation matrix that represents transformations in the x-y plane. NULL arguments are treated as identity transformations.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixTransformation2D(

    D3DXMATRIX *pOut,
    CONST D3DXVECTOR2 *pScalingCenter,
    FLOAT *pScalingRotation,
    CONST D3DXVECTOR2 *pScaling,
    CONST D3DXVECTOR2 *pRotationCenter,
    FLOAT Rotation,
    CONST D3DXVECTOR2 *pTranslation
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that contains the result of the transformations.
pScalingCenter
[in] Pointer to a D3DXVECTOR2 structure, a point identifying the scaling center. If this argument is NULL, an identity Msc matrix is applied to the formula in Remarks.
pScalingRotation
[in] Pointer to the scaling rotation factor.
pScaling
[in] Pointer to a D3DXVECTOR2 structure, a point identifying the scale. If this argument is NULL, an identity Ms matrix is applied to the formula in Remarks.
pRotationCenter
[in] Pointer to a D3DXVECTOR2 structure, a point identifying the rotation center. If this argument is NULL, an identity Mrc matrix is applied to the formula in Remarks.
Rotation
[in] The angle of rotation in radians.
pTranslation
[in] Pointer to a D3DXVECTOR2 structure, identifying the translation. If this argument is NULL, an identity Mt matrix is applied to the formula in Remarks.

Return Value

Pointer to a D3DXMATRIX structure that contains the transformation matrix.

Remarks

This function calculates the transformation matrix with the following formula, with matrix concatenation evaluated in left-to-right order:

Mout = (Msc)-1 * (Msr)-1 * Ms * Msr * Msc * (Mrc)-1 * Mr * Mrc * Mt

where:

Mout = output matrix (pOut)

Msc = scaling center matrix (pScalingCenter)

Msr = scaling rotation matrix (pScalingRotation)

Ms = scaling matrix (pScaling)

Mrc = center of rotation matrix (pRotationCenter)

Mr = rotation matrix (Rotation)

Mt = translation matrix (pTranslation)

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixTransformation2D function can be used as a parameter for another function.

For 3-D transformations, use D3DXMatrixTransformation.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixAffineTransformation2D, Matrix Transforms


D3DXMatrixTranslation Function

Builds a matrix using the specified offsets.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixTranslation(

    D3DXMATRIX *pOut,
    FLOAT x,
    FLOAT y,
    FLOAT z
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
x
[in] X-coordinate offset.
y
[in] Y-coordinate offset.
z
[in] Z-coordinate offset.

Return Value

Pointer to a D3DXMATRIX structure that contains a translated transformation matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixTranslation can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXMatrixTranspose Function

Returns the matrix transpose of a matrix.

Syntax

D3DXMATRIX *WINAPI D3DXMatrixTranspose(

    D3DXMATRIX *pOut,
    CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Value

Pointer to the D3DXMATRIX structure that is the matrix transpose of the matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixTranspose function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXPlaneDot Function

Computes the dot product of a plane and a 4-D vector.

Syntax

FLOAT D3DXPlaneDot(

    CONST D3DXPLANE *pP,
    CONST D3DXVECTOR4 *pV
);

Parameters

pP
[in] Pointer to a source D3DXPLANE structure.
pV
[in] Pointer to a D3DXVECTOR4 structure.

Return Value

The dot product of the plane and 4-D vector.

Remarks

Given a plane (a, b, c, d) and a 4-D vector (x, y, z, w) the return value of this function is a*x + b*y + c*z + d*w. The D3DXPlaneDot function is useful for determining the plane's relationship with a homogeneous coordinate. For example, this function could be used to determine if a particular coordinate is on a particular plane, or on which side of a particular plane a particular coordinate lies.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXPlaneDotCoord, D3DXPlaneDotNormal


D3DXPlaneDotCoord Function

Computes the dot product of a plane and a 3-D vector. The w parameter of the vector is assumed to be 1.

Syntax

FLOAT D3DXPlaneDotCoord(

    CONST D3DXPLANE *pP,
    CONST D3DXVECTOR3 *pV
);

Parameters

pP
[in] Pointer to a source D3DXPLANE structure.
pV
[in] Pointer to a source D3DXVECTOR3 structure.

Return Value

The dot product of the plane and 3-D vector.

Remarks

Given a plane (a, b, c, d) and a 3-D vector (x, y, z) the return value of this function is a*x + b*y + c*z + d*1. The D3DXPlaneDotCoord function is useful for determining the plane's relationship with a coordinate in 3-D space.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXPlaneDot, D3DXPlaneDotNormal


D3DXPlaneDotNormal Function

Computes the dot product of a plane and a 3-D vector. The w parameter of the vector is assumed to be 0.

Syntax

FLOAT D3DXPlaneDotNormal(

    CONST D3DXPLANE *pP,
    CONST D3DXVECTOR3 *pV
);

Parameters

pP
[in] Pointer to a source D3DXPLANE structure.
pV
[in] Pointer to a source D3DXVECTOR3 structure.

Return Value

The dot product of the plane and 3-D vector.

Remarks

Given a plane (a, b, c, d) and a 3-D vector (x, y, z) the return value of this function is a*x + b*y + c*z + d*0. The D3DXPlaneDotNormal function is useful for calculating the angle between the normal of the plane, and another normal.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXPlaneDot, D3DXPlaneDotCoord


D3DXPlaneFromPointNormal Function

Constructs a plane from a point and a normal.

Syntax

D3DXPLANE *WINAPI D3DXPlaneFromPointNormal(

    D3DXPLANE *pOut,
    CONST D3DXVECTOR3 *pPoint,
    CONST D3DXVECTOR3 *pNormal
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE structure that is the result of the operation.
pPoint
[in] Pointer to a D3DXVECTOR3 structure, defining the point used to construct the plane.
pNormal
[in] Pointer to a D3DXVECTOR3 structure, defining the normal used to construct the plane.

Return Value

Pointer to the D3DXPLANE structure constructed from the point and the normal.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXPlaneFromPointNormal function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXPlaneFromPoints


D3DXPlaneFromPoints Function

Constructs a plane from three points.

Syntax

D3DXPLANE *WINAPI D3DXPlaneFromPoints(

    D3DXPLANE *pOut,
    CONST D3DXVECTOR3 *pV1,
    CONST D3DXVECTOR3 *pV2,
    CONST D3DXVECTOR3 *pV3
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE structure that is the result of the operation.
pV1
[in] Pointer to a D3DXVECTOR3 structure, defining one of the points used to construct the plane.
pV2
[in] Pointer to a D3DXVECTOR3 structure, defining one of the points used to construct the plane.
pV3
[in] Pointer to a D3DXVECTOR3 structure, defining one of the points used to construct the plane.

Return Value

Pointer to the D3DXPLANE structure constructed from the given points.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXPlaneFromPoints function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXPlaneFromPointNormal


D3DXPlaneIntersectLine Function

Finds the intersection between a plane and a line.

Syntax

D3DXVECTOR3 *WINAPI D3DXPlaneIntersectLine(

    D3DXVECTOR3 *pOut,
    CONST D3DXPLANE *pP,
    CONST D3DXVECTOR3 *pV1,
    CONST D3DXVECTOR3 *pV2
);

Parameters

pOut
[in, out] Pointer to a D3DXVECTOR3 structure, identifying the intersection between the specified plane and line.
pP
[in] Pointer to the source D3DXPLANE structure.
pV1
[in] Pointer to a source D3DXVECTOR3 structure, defining a line starting point.
pV2
[in] Pointer to a source D3DXVECTOR3 structure, defining a line ending point.

Return Value

Pointer to a D3DXVECTOR3 structure that is the intersection between the specified plane and line.

Remarks

If the line is parallel to the plane, NULL is returned.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXPlaneIntersectLine function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXPlaneNormalize Function

Normalizes the plane coefficients so that the plane normal has unit length.

Syntax

D3DXPLANE *WINAPI D3DXPlaneNormalize(

    D3DXPLANE *pOut,
    CONST D3DXPLANE *pP
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE structure that is the result of the operation.
pP
[in] Pointer to the source D3DXPLANE structure.

Return Value

Pointer to a D3DXPLANE structure that represents the normal of the plane.

Remarks

This function normalizes a plane so that |a,b,c| == 1.

The return value for this function is the same value returned in the pOut parameter. In this way, this function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXPlaneScale Function

Scale the plane with the given scaling factor.

Syntax

D3DXPLANE *D3DXPlaneScale(

    D3DXPLANE *pOut,
    CONST D3DXPLANE *pP,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE structure that is the result of the operation.
pP
[in] Pointer to the source D3DXPLANE structure.
s
[in] Scale factor.

Return Value

Pointer to a D3DXPLANE structure that represents the scaled plane.

Remarks

The return value for this function is the same value returned in the pOut parameter. Therefore, this function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXPlaneTransform Function

Transforms a plane by a matrix. The input matrix is the inverse transpose of the actual transformation.

Syntax

D3DXPLANE *WINAPI D3DXPlaneTransform(

    D3DXPLANE *pOut,
    CONST D3DXPLANE *pP,
    CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE structure that contains the resulting transformed plane. See example.
pP
[in] Pointer to the input D3DXPLANE structure, which contains the plane that will be transformed. The vector (a,b,c) that describes the plane must be normalized before this function is called. See example.
pM
[in] Pointer to the source D3DXMATRIX structure, which contains the transformation values. This matrix must contain the inverse transpose of the transformation values.

Return Value

Pointer to a D3DXPLANE structure, representing the transformed plane. This is the same value returned in the pOut parameter so that this function can be used as a parameter for another function.

Examples

This example transforms a plane by applying a non-uniform scale.

D3DXPLANE   planeNew;
D3DXPLANE   plane(0,1,1,0);
D3DXPlaneNormalize(&plane, &plane);

D3DXMATRIX  matrix;
D3DXMatrixScaling(&matrix, 1.0f,2.0f,3.0f);
D3DXMatrixInverse(&matrix, NULL, &matrix);
D3DXMatrixTranspose(&matrix, &matrix);
D3DXPlaneTransform(&planeNew, &plane, &matrix);

A plane is described by ax + by + cz + dw = 0. The first plane is created with (a,b,c,d) = (0,1,1,0), which is a plane described by y + z = 0. After scaling, the new plane contains (a,b,c,d) = (0, 0.353f, 0.235f, 0), which shows the new plane to be described by 0.353y + 0.235z = 0.

The parameter pM contains the inverse transpose of the transformation matrix. The inverse transpose is required by this method so that the normal vector of the transformed plane can be correctly transformed as well.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXPlaneNormalize, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationZ, D3DXMatrixInverse, D3DXMatrixTranspose


D3DXPlaneTransformArray Function

Transforms an array of planes by a matrix. The vectors that describe each plane must be normalized.

Syntax

D3DXPLANE *WINAPI D3DXPlaneTransformArray(

    D3DXPLANE *pOut,
    UINT OutStride,
    CONST D3DXPLANE* pP,
    UINT PStride,
    CONST D3DXMATRIX* pM,
    UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE structure that contains the resulting transformed plane. See Example.
OutStride
[out] The stride of each transformed plane.
pP
[in] Pointer to the input D3DXPLANE structure, which contains the array of planes to transform. The vector (a,b,c) that describes the plane must be normalized before this function is called. See Example.
PStride
[in] The stride of each non-transformed plane.
pM
[in] Pointer to the source D3DXMATRIX structure, which contains the inverse transpose of the transformation values.
n
[in] The number of planes to transform.

Return Value

Pointer to a D3DXPLANE structure, representing the transformed plane. This is the same value returned in the pOut parameter so that this function can be used as a parameter for another function.

Examples

This example transforms one plane by applying a non-uniform scale.

#define ARRAYSIZE 4
D3DXPLANE planeNew[ARRAYSIZE];
D3DXPLANE plane[ARRAYSIZE];

for(int i = 0; i < ARRAYSIZE; i++)
{
    plane = D3DXPLANE( 0.0f, 1.0f, 1.0f, 0.0f );
    D3DXPlaneNormalize( &plane[i], &plane[i] );
}

D3DXMATRIX  matrix;
D3DXMatrixScaling( &matrix, 1.0f, 2.0f, 3.0f );
D3DXMatrixInverse( &matrix, NULL, &matrix );
D3DXMatrixTranspose( &matrix, &matrix );
D3DXPlaneTransformArray( &planeNew, sizeof (D3DXPLANE), &plane,
                         sizeof (D3DXPLANE), &matrix, ARRAYSIZE );

A plane is described by ax + by + cz + dw = 0. The first plane is created with (a,b,c,d) = (0,1,1,0), which is a plane described by y + z = 0. After scaling, the new plane contains (a,b,c,d) = (0, 0.353f, 0.235f, 0), which shows the new plane to be described by 0.353y + 0.235z = 0.

The parameter pM, contains the inverse transpose of the transformation matrix. The inverse transpose is required by this method so that the normal vector of the transformed plane can be correctly transformed as well.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXPlaneNormalize, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationZ, D3DXMatrixInverse, D3DXMatrixTranspose


D3DXQuaternionBaryCentric Function

Returns a quaternion in Barycentric coordinates.

Syntax

D3DXQUATERNION *WINAPI D3DXQuaternionBaryCentric(

    D3DXQUATERNION *pOut,
    CONST D3DXQUATERNION *pQ1,
    CONST D3DXQUATERNION *pQ2,
    CONST D3DXQUATERNION *pQ3,
    FLOAT f,
    FLOAT g
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ1
[in] Pointer to a source D3DXQUATERNION structure.
pQ2
[in] Pointer to a source D3DXQUATERNION structure.
pQ3
[in] Pointer to a source D3DXQUATERNION structure.
f
[in] Weighting factor. See Remarks.
g
[in] Weighting factor. See Remarks.

Return Value

Pointer to a D3DXQUATERNION structure in Barycentric coordinates.

Remarks

To compute the Barycentric coordinates, the D3DXQuaternionBaryCentric function implements the following series of spherical linear interpolation operations: Slerp(Slerp(Q1, Q2, f+g), Slerp(Q1, Q3, f+g), g/(f+g))

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionBaryCentric function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXQuaternionConjugate Function

Returns the conjugate of a quaternion.

Syntax

D3DXQUATERNION *D3DXQuaternionConjugate(

    D3DXQUATERNION *pOut,
    CONST D3DXQUATERNION *pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Value

Pointer to a D3DXQUATERNION structure that is the conjugate of the quaternion.

Remarks

Given a quaternion (x, y, z, w), the D3DXQuaternionConjugate function will return the quaternion (-x, -y, -z, w).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionConjugate function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionInverse


D3DXQuaternionDot Function

Returns the dot product of two quaternions.

Syntax

FLOAT D3DXQuaternionDot(

    CONST D3DXQUATERNION *pQ1,
    CONST D3DXQUATERNION *pQ2
);

Parameters

pQ1
[in] Pointer to a source D3DXQUATERNION structure.
pQ2
[in] Pointer to a source D3DXQUATERNION structure.

Return Value

The dot product of two quaternions.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXQuaternionExp Function

Calculates the exponential.

Syntax

D3DXQUATERNION *WINAPI D3DXQuaternionExp(

    D3DXQUATERNION *pOut,
    CONST D3DXQUATERNION *pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Value

Pointer to a D3DXQUATERNION structure that is the exponential.

Remarks

This method converts a pure quaternion to a unit quaternion. D3DXQuaternionExp expects a pure quaternion, where w is ignored in the calculation (w == 0).

Given a pure quaternion defined by:
q = (0, theta * v);

This method calculates the exponential result.
exp(Q) = (cos(theta), sin(theta) * v)

where v is the vector portion of a quaternion.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionExp function can be used as a parameter for another function.

The D3DXQuaternionSquadSetup method can also be used to set up the control points of a quaternion.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionLn, D3DXQuaternionSquad


D3DXQuaternionIdentity Function

Returns the identity quaternion.

Syntax

D3DXQUATERNION *D3DXQuaternionIdentity(

    D3DXQUATERNION *pOut
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.

Return Value

Pointer to the D3DXQUATERNION structure that is the identity quaternion.

Remarks

Given a quaternion (x, y, z, w), the D3DXQuaternionIdentity function will return the quaternion (0, 0, 0, 1).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionIdentity function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionIsIdentity


D3DXQuaternionInverse Function

Conjugates and renormalizes a quaternion.

Syntax

D3DXQUATERNION *WINAPI D3DXQuaternionInverse(

    D3DXQUATERNION *pOut,
    CONST D3DXQUATERNION *pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Value

Pointer to a D3DXQUATERNION structure that is the inverse quaternion of the quaternion.

Remarks

A unit quaternion, is defined by:
Q == (cos(theta), sin(theta) * v) where |v| = 1
The natural logarithm of Q is, ln(Q) = (0, theta * v)

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionInverse function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionConjugate, D3DXQuaternionNormalize


D3DXQuaternionIsIdentity Function

Determines if a quaternion is an identity quaternion.

Syntax

BOOL D3DXQuaternionIsIdentity(

    CONST D3DXQUATERNION *pQ
);

Parameters

pQ
[in] Pointer to the D3DXQUATERNION structure that will be tested for identity.

Return Value

If the quaternion is an identity quaternion, this function returns TRUE. Otherwise, this function returns FALSE.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionIdentity


D3DXQuaternionLength Function

Returns the length of a quaternion.

Syntax

FLOAT D3DXQuaternionLength(

    CONST D3DXQUATERNION *pQ
);

Parameters

pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Value

The quaternion's length.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionLengthSq


D3DXQuaternionLengthSq Function

Returns the square of the length of a quaternion.

Syntax

FLOAT D3DXQuaternionLengthSq(

    CONST D3DXQUATERNION *pQ
);

Parameters

pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Value

The quaternion's squared length.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionLength


D3DXQuaternionLn Function

Calculates the natural logarithm.

Syntax

D3DXQUATERNION *WINAPI D3DXQuaternionLn(

    D3DXQUATERNION *pOut,
    CONST D3DXQUATERNION *pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Value

Pointer to a D3DXQUATERNION structure that is the natural logarithm.

Remarks

The D3DXQuaternionLn function works only for unit quaternions.

A unit quaternion, is defined by:
Q == (cos(theta), sin(theta) * v) where |v| = 1
The natural logarithm of Q is, ln(Q) = (0, theta * v)

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionLn function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionExp, D3DXQuaternionSquad


D3DXQuaternionMultiply Function

Multiplies two quaternions.

Syntax

D3DXQUATERNION *WINAPI D3DXQuaternionMultiply(

    D3DXQUATERNION *pOut,
    CONST D3DXQUATERNION *pQ1,
    CONST D3DXQUATERNION *pQ2
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ1
[in] Pointer to a source D3DXQUATERNION structure.
pQ2
[in] Pointer to a source D3DXQUATERNION structure.

Return Value

Pointer to a D3DXQUATERNION structure that is the product of two quaternions.

Remarks

The result represents the rotation Q1 followed by the rotation Q2 (Out = Q1 * Q2). This is done so that D3DXQuaternionMultiply maintain the same semantics as D3DXMatrixMultiply because unit quaternions can be considered as another way to represent rotation matrices.

Transformations are concatenated in the same order for both the D3DXQuaternionMultiply and D3DXMatrixMultiply functions. For example, assuming mX and mY represent the same rotations as qX and qY, both m and q will represent the same rotations.

D3DXMatrixMultiply(&m, &mX, &mY);

D3DXQuaternionMultiply(&q, &qX, &qY);

The multiplication of quaternions is not commutative.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionMultiply function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXMatrixMultiply


D3DXQuaternionNormalize Function

Computes a unit length quaternion.

Syntax

D3DXQUATERNION *WINAPI D3DXQuaternionNormalize(

    D3DXQUATERNION *pOut,
    CONST D3DXQUATERNION *pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Value

Pointer to a D3DXQUATERNION structure that is the normal of the quaternion.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionNormalize function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionInverse


D3DXQuaternionRotationAxis Function

Rotates a quaternion about an arbitrary axis.

Syntax

D3DXQUATERNION *WINAPI D3DXQuaternionRotationAxis(

    D3DXQUATERNION *pOut,
    CONST D3DXVECTOR3 *pV,
    FLOAT Angle
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pV
[in] Pointer to the D3DXVECTOR3 structure that identifies the axis about which to rotate the quaternion.
Angle
[in] Angle of rotation, in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Value

Pointer to a D3DXQUATERNION structure rotated around the specified axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionRotationAxis function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionRotationMatrix, D3DXQuaternionRotationYawPitchRoll


D3DXQuaternionRotationMatrix Function

Builds a quaternion from a rotation matrix.

Syntax

D3DXQUATERNION *WINAPI D3DXQuaternionRotationMatrix(

    D3DXQUATERNION *pOut,
    CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Value

Pointer to the D3DXQUATERNION structure built from a rotation matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionRotationMatrix function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionRotationAxis, D3DXQuaternionRotationYawPitchRoll


D3DXQuaternionRotationYawPitchRoll Function

Builds a quaternion with the given yaw, pitch, and roll.

Syntax

D3DXQUATERNION *WINAPI D3DXQuaternionRotationYawPitchRoll(

    D3DXQUATERNION *pOut,
    FLOAT Yaw,
    FLOAT Pitch,
    FLOAT Roll
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
Yaw
[in] Yaw around the y-axis, in radians.
Pitch
[in] Pitch around the x-axis, in radians.
Roll
[in] Roll around the z-axis, in radians.

Return Value

Pointer to a D3DXQUATERNION structure with the specified yaw, pitch, and roll.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionRotationYawPitchRoll function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionRotationAxis, D3DXQuaternionRotationMatrix


D3DXQuaternionSlerp Function

Interpolates between two quaternions, using spherical linear interpolation.

Syntax

D3DXQUATERNION *WINAPI D3DXQuaternionSlerp(

    D3DXQUATERNION *pOut,
    CONST D3DXQUATERNION *pQ1,
    CONST D3DXQUATERNION *pQ2,
    FLOAT t
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ1
[in] Pointer to a source D3DXQUATERNION structure.
pQ2
[in] Pointer to a source D3DXQUATERNION structure.
t
[in] Parameter that indicates how far to interpolate between the quaternions.

Return Value

Pointer to a D3DXQUATERNION structure that is the result of the interpolation.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionSlerp function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXQuaternionSquad Function

Interpolates between quaternions, using spherical quadrangle interpolation.

Syntax

D3DXQUATERNION *WINAPI D3DXQuaternionSquad(

    D3DXQUATERNION *pOut,
    CONST D3DXQUATERNION *pQ1,
    CONST D3DXQUATERNION *pA,
    CONST D3DXQUATERNION *pB,
    CONST D3DXQUATERNION *pC,
    FLOAT t
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ1
[in] Pointer to a source D3DXQUATERNION structure.
pA
[in] Pointer to a source D3DXQUATERNION structure.
pB
[in] Pointer to a source D3DXQUATERNION structure.
pC
[in] Pointer to a source D3DXQUATERNION structure.
t
[in] Parameter that indicates how far to interpolate between the quaternions.

Return Value

Pointer to a D3DXQUATERNION structure that is the result of the spherical quadrangle interpolation.

Remarks

This function uses the following sequence of spherical linear interpolation operations: Slerp(Slerp(pQ1, pC, t), Slerp(pA, pB, t), 2t(1 - t))

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionSquad function can be used as a parameter for another function.

For an example of interpolating between quaternions, see SkinnedMesh Sample.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionExp, D3DXQuaternionLn, D3DXQuaternionSquadSetup


D3DXQuaternionSquadSetup Function

Setup control points for spherical quadrangle interpolation.

Syntax

void WINAPI D3DXQuaternionSquadSetup(

    D3DXQUATERNION *pAOut,
    D3DXQUATERNION *pBOut,
    D3DXQUATERNION *pCOut,
    const D3DXQUATERNION *pQ0,
    const D3DXQUATERNION *pQ1,
    const D3DXQUATERNION *pQ2,
    const D3DXQUATERNION *pQ3
);

Parameters

pAOut
[out] Pointer to AOut.
pBOut
[out] Pointer to BOut.
pCOut
[out] Pointer to COut.
pQ0
[in] Pointer to the input control point, Q0.
pQ1
[in] Pointer to the input control point, Q1.
pQ2
[in] Pointer to the input control point, Q2.
pQ3
[in] Pointer to the input control point, Q3.

Return Value

None.

Remarks

This function takes four control points, which are supplied to the inputs pQ0, pQ1, pQ2, and pQ3. The function then alters these values to find a curve that flows along the shortest path. The values of q0, q2, and q3 are calculated as shown below.

q0 = |Q0 + Q1| < |Q0 - Q1| ? -Q0 : Q0
q2 = |Q1 + Q2| < |Q1 - Q2| ? -Q2 : Q2
q3 = |Q2 + Q3| < |Q2 - Q3| ? -Q3 : Q3

Having calculated the new Q values, the values for AOut, BOut, and COut are calculated as shown below.

AOut = q1 * e[-0.25 *( Ln[Exp(q1)*q2] + Ln[Exp(q1)*q0] ) ]

BOut = q2 * e[-0.25 *( Ln[Exp(q2)*q3] + Ln[Exp(q2)*q1] ) ]

COut = q2

Note Ln is the application programming interface (API) method D3DXQuaternionLn and Exp is the API method D3DXQuaternionExp.

Examples

The following example shows how to use a set of quaternion keys (Q0, Q1, Q2, Q3) to compute the inner quadrangle points (A, B, C). This ensures that the tangents are continuous across adjacent segments.

        A     B
  Q0    Q1    Q2    Q3

This is how you can interpolate between Q1 and Q2.

// Rotation about the z-axis
D3DXQUATERNION Q0 = D3DXQUATERNION(0,  0, 0.707f, -.707f);
D3DXQUATERNION Q1 = D3DXQUATERNION(0,  0, 0.000f, 1.000f);
D3DXQUATERNION Q2 = D3DXQUATERNION(0,  0, 0.707f, 0.707f);
D3DXQUATERNION Q3 = D3DXQUATERNION(0,  0, 1.000f, 0.000f);
D3DXQUATERNION A, B, C, Qt;
FLOAT time = 0.5f;

D3DXQuaternionSquadSetup(&A, &B, &C, &Q0, &Q1, &Q2, &Q3);
D3DXQuaternionSquad(&Qt, &Q1, &A, &B, &C, time);

Note:

  • C is +/- Q2 depending on the result of the function
  • Qt is the result of the function

The result is a rotation of 45 degrees around the z-axis for time = 0.5.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXQuaternionSquad


D3DXQuaternionToAxisAngle Function

Computes a quaternion's axis and angle of rotation.

Syntax

void WINAPI D3DXQuaternionToAxisAngle(

    CONST D3DXQUATERNION *pQ,
    D3DXVECTOR3 *pAxis,
    FLOAT *pAngle
);

Parameters

pQ
[in] Pointer to the source D3DXQUATERNION structure.
pAxis
[in, out] When this function returns, pointer to a D3DXVECTOR3 structure that identifies the quaternion's axis of rotation.
pAngle
[in, out] This function returns a pointer to a FLOAT value that identifies the quaternion's angle of rotation in radians.

Return Value

No return value.

Remarks

This function expects unit quaternions.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXSHAdd Function

Adds two spherical harmonic (SH) vectors; in other words, pOut[i] = pA[i] + pB[i].

Syntax

FLOAT *WINAPI D3DXSHAdd(

    FLOAT *pOut,
    UINT Order,
    const FLOAT *pA,
    const FLOAT *pB
);

Parameters

pOut
[out] Pointer to SH output coefficients. The evaluation generates Order2 coefficients. See Remarks.
Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pA
[in] Pointer to the first SH vector.
pB
[in] Pointer to the second SH vector.

Return Value

Pointer to SH output coefficients.

Remarks

Each coefficient of the basis function Ylm is stored at memory location l2 + m + l, where:

  • l is the degree of the basis function.
  • m is the basis function index for the given l value and ranges from -l to l, inclusive.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Precomputed Radiance Transfer


D3DXSHDot Function

Computes the dot product of two spherical harmonic (SH) vectors.

Syntax

FLOAT WINAPI D3DXSHDot(

    UINT Order,
    const FLOAT *pA,
    const FLOAT *pB
);

Parameters

Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pA
[in] Pointer to the first SH vector.
pB
[in] Pointer to the second SH vector.

Return Value

SH output coefficients.

Remarks

Each coefficient of the basis function Ylm is stored at memory location l2 + m + l, where:

  • l is the degree of the basis function.
  • m is the basis function index for the given l value and ranges from -l to l, inclusive.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Precomputed Radiance Transfer


D3DXSHEvalConeLight Function

Evaluates a light that is a cone of constant intensity and returns spectral spherical harmonic (SH) data.

Syntax

HRESULT WINAPI D3DXSHEvalConeLight(

    UINT Order,
    const D3DXVECTOR3 *pDir,
    FLOAT Radius,
    FLOAT RIntensity,
    FLOAT GIntensity,
    FLOAT BIntensity,
    FLOAT* pROut,
    FLOAT* pGOut,
    FLOAT* pBOut
);

Parameters

Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pDir
[in] Pointer to the (x, y, z) hemisphere axis direction vector in which to evaluate the SH basis functions. See Remarks.
Radius
[in] Radius of cone in radians.
RIntensity
[in] The red intensity of the light.
GIntensity
[in] The green intensity of the light.
BIntensity
[in] The blue intensity of the light.
pROut
[out] Pointer to the output SH vector for the red component.
pGOut
[out] Pointer to the output SH vector for the green component.
pBOut
[out] Pointer to the output SH vector for the blue component.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Evaluates a light that is a cone of constant intensity and returns spectral SH data. The output vector is computed so that if the intensity ratio R/G/B is equal to 1, the exit radiance of a point directly under the light (oriented in the cone direction on a diffuse object with an albedo of 1) would be 1.0. This will compute three spectral samples; pROut will be returned, while pGOut and pBOut may be returned.

On the sphere with unit radius as shown, direction can be specified simply with theta, the angle about the z-axis in the right-handed direction, and phi, the angle from z.

The following equations show the relationship between Cartesian (x, y, z) and spherical (theta, phi) coordinates on the unit sphere. The angle theta varies over the range of 0 to 2 pi, while phi varies from 0 to pi.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Precomputed Radiance Transfer


D3DXSHEvalDirection Function

Evaluates the spherical harmonic (SH) basis functions from an input direction vector.

Syntax

FLOAT *WINAPI D3DXSHEvalDirection(

    FLOAT *pOut,
    UINT Order,
    const D3DXVECTOR3 *pDir
);

Parameters

pOut
[out] Pointer to SH output coefficients. The evaluation generates Order2 coefficients. See Remarks.
Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pDir
[in] (x, y, z) direction vector in which to evaluate the SH basis functions. Must be normalized. See Remarks.

Return Value

Pointer to SH output coefficients. See Remarks.

Remarks

Each coefficient of the basis function Ylm is stored at memory location l2 + m + l, where:

  • l is the degree of the basis function.
  • m is the basis function index for the given l value and ranges from -l to l, inclusive.

On the sphere with unit radius as shown, direction can be specified simply with theta, the angle about the z-axis in the right-handed direction, and phi, the angle from z.

The following equations show the relationship between Cartesian (x, y, z) and spherical (theta, phi) coordinates on the unit sphere. The angle theta varies over the range of 0 to 2 pi, while phi varies from 0 to pi.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Precomputed Radiance Transfer


D3DXSHEvalDirectionalLight Function

Evaluates a directional light and returns spectral spherical harmonic (SH) data.

Syntax

HRESULT WINAPI D3DXSHEvalDirectionalLight(

    UINT Order,
    const D3DXVECTOR3 *pDir,
    FLOAT RIntensity,
    FLOAT GIntensity,
    FLOAT BIntensity,
    FLOAT *pROut,
    FLOAT *pGOut,
    FLOAT *pBOut
);

Parameters

Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pDir
[in] Pointer to the (x, y, z) hemisphere axis direction vector in which to evaluate the SH basis functions. See Remarks.
RIntensity
[in] The red intensity of the light.
GIntensity
[in] The green intensity of the light.
BIntensity
[in] The blue intensity of the light.
pROut
[out] Pointer to the output SH vector for the red component.
pGOut
[out] Optional pointer to the output SH vector for the green component.
pBOut
[out] Optional pointer to the output SH vector for the blue component.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The output vector is computed so that if the intensity ratio R/G/B is equal to 1, the resulting exit radiance of a point directly under the light on a diffuse object with an albedo of 1 would be 1.0. This will compute three spectral samples; pROut will be returned, while pGOut and pBOut may be returned.

On the sphere with unit radius as shown, direction can be specified simply with theta, the angle about the z-axis in the right-handed direction, and phi, the angle from z.

The following equations show the relationship between Cartesian (x, y, z) and spherical (theta, phi) coordinates on the unit sphere. The angle theta varies over the range of 0 to 2 pi, while phi varies from 0 to pi.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Precomputed Radiance Transfer


D3DXSHEvalHemisphereLight Function

Evaluates a light that is a linear interpolation between two colors over the sphere.

Syntax

HRESULT WINAPI D3DXSHEvalHemisphereLight(

    UINT Order,
    const D3DXVECTOR3 *pDir,
    D3DXCOLOR Top,
    D3DXCOLOR Bottom,
    FLOAT *pROut,
    FLOAT *pGOut,
    FLOAT *pBOut
);

Parameters

Order
[in] Order of the spherical harmonic (SH) evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pDir
[in] Pointer to the (x, y, z) hemisphere axis direction vector in which to evaluate the SH basis functions. See Remarks.
Top
[in] The sky color.
Bottom
[in] The ground color.
pROut
[in] Pointer to the output SH vector for the red component.
pGOut
[in] Pointer to the output SH vector for the green component.
pBOut
[in] Pointer to the output SH vector for the blue component.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The interpolation is done linearly between the two points, not over the surface of the sphere (that is, if the axis was (0,0,1) it is linear in Z, not in the azimuthal angle). The resulting spherical lighting function is normalized so that a point on a perfectly diffuse surface with no shadowing and a normal pointed in the direction pDir would result in exit radiance with a value of 1 (if the top color was white and the bottom color was black). This is a very simple model where Top represents the intensity of the "sky" and Bottom represents the intensity of the "ground."

On the sphere with unit radius as shown, direction can be specified simply with theta, the angle about the z-axis in the right-handed direction, and phi, the angle from z.

The following equations show the relationship between Cartesian (x, y, z) and spherical (theta, phi) coordinates on the unit sphere. The angle theta varies over the range of 0 to 2 pi, while phi varies from 0 to pi.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Precomputed Radiance Transfer


D3DXSHEvalSphericalLight Function

Evaluates a spherical light and returns spectral spherical harmonic (SH) data.

Syntax

HRESULT WINAPI D3DXSHEvalSphericalLight(

    UINT Order,
    const D3DXVECTOR3 *pPos,
    FLOAT Radius,
    FLOAT RIntensity,
    FLOAT GIntensity,
    FLOAT BIntensity,
    FLOAT *pROut,
    FLOAT *pGOut,
    FLOAT *pBOut
);

Parameters

Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pPos
[in] Pointer to the light position.
Radius
[in] Radius of spherical light source.
RIntensity
[in] The red intensity of the light.
GIntensity
[in] The green intensity of the light.
BIntensity
[in] The blue intensity of the light.
pROut
[out] Pointer to the output SH vector for the red component.
pGOut
[out] Pointer to the output SH vector for the green component.
pBOut
[out] Pointer to the output SH vector for the blue component.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Evaluates a spherical light and returns spectral SH data. There is no normalization of the intensity of the light like there is for directional lights, so care has to be taken when specifying the intensities. This will compute three spectral samples; pROut will be returned, while pGOut and pBOut may be returned.

On the sphere with unit radius as shown, direction can be specified simply with theta, the angle about the z-axis in the right-handed direction, and phi, the angle from z.

The following equations show the relationship between Cartesian (x, y, z) and spherical (theta, phi) coordinates on the unit sphere. The angle theta varies over the range of 0 to 2 pi, while phi varies from 0 to pi.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Precomputed Radiance Transfer


D3DXSHProjectCubeMap Function

Projects a function represented on a cube map into spherical harmonics (SH).

Syntax

HRESULT WINAPI D3DXSHProjectCubeMap(

    UINT Order,
    LPDIRECT3DCUBETEXTURE9 pCubeMap,
    FLOAT *pROut,
    FLOAT *pGOut,
    FLOAT *pBOut
);

Parameters

Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pCubeMap
[in] Pointer to a source cube texture. See IDirect3DCubeTexture9.
pROut
[in] Pointer to the output SH vector for the red component.
pGOut
[in] Pointer to the output SH vector for the green component.
pBOut
[in] Pointer to the output SH vector for the blue component.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be D3DERR_INVALIDCALL.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Precomputed Radiance Transfer


D3DXSHRotate Function

Rotates the spherical harmonic (SH) vector by the given matrix.

Syntax

FLOAT *WINAPI D3DXSHRotate(

    FLOAT *pOut,
    UINT Order,
    const D3DXMATRIX *pMatrix,
    const FLOAT *pIn
);

Parameters

pOut
[out] Pointer to SH output coefficients. The evaluation generates Order2 coefficients. This pointer should not alias with pIn. See Remarks.
Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pMatrix
[in] Pointer to the rotation matrix. The rotation sub-matrix must be orthogonal, with a unit determinant.
pIn
[in] Pointer to rotated SH coefficients.

Return Value

Pointer to SH output coefficients.

Remarks

Each coefficient of the basis function Ylm is stored at memory location l2 + m + l, where:

  • l is the degree of the basis function.
  • m is the basis function index for the given l value and ranges from -l to l, inclusive.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Precomputed Radiance Transfer


D3DXSHRotateZ Function

Rotates the spherical harmonic (SH) vector in the z-axis by the given angle.

Syntax

FLOAT *WINAPI D3DXSHRotateZ(

    FLOAT *pOut,
    UINT Order,
    FLOAT Angle,
    const FLOAT *pIn
);

Parameters

pOut
[out] Pointer to SH output coefficients. The evaluation generates Order2 coefficients. This pointer should not alias with pIn. See Remarks.
Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
Angle
[in] Rotation angle in radians. The rotation is performed around the z-axis.
pIn
[in] Pointer to rotated SH coefficients.

Return Value

Pointer to SH output coefficients.

Remarks

Each coefficient of the basis function Ylm is stored at memory location l2 + m + l, where:

  • l is the degree of the basis function.
  • m is the basis function index for the given l value and ranges from -l to l, inclusive.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Precomputed Radiance Transfer


D3DXSHScale Function

Scales a spherical harmonic (SH) vector; in other words, pOut[i] = pA[i]*Scale.

Syntax

FLOAT *WINAPI D3DXSHScale(

    FLOAT *pOut,
    UINT Order,
    const FLOAT *pIn,
    const FLOAT *Scale
);

Parameters

pOut
[out] Pointer to SH output coefficients. The evaluation generates Order2 coefficients. See Remarks.
Order
[in] Order of the SH evaluation. Must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The evaluation generates Order2 coefficients. The degree of the evaluation is Order - 1.
pIn
[in] Pointer to the SH vector to scale.
Scale
[in] Pointer to the scale value.

Return Value

Pointer to SH output coefficients.

Remarks

Each coefficient of the basis function Ylm is stored at memory location l2 + m + l, where:

  • l is the degree of the basis function.
  • m is the basis function index for the given l value and ranges from -l to l, inclusive.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Precomputed Radiance Transfer


D3DXVec2Add Function

Adds two 2-D vectors.

Syntax

D3DXVECTOR2 *D3DXVec2Add(

    D3DXVECTOR2 *pOut,
    CONST D3DXVECTOR2 *pV1,
    CONST D3DXVECTOR2 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.

Return Value

Pointer to a D3DXVECTOR2 structure that is the sum of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Add function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2Subtract, D3DXVec2Scale


D3DXVec2BaryCentric Function

Returns a point in Barycentric coordinates, using the specified 2-D vectors.

Syntax

D3DXVECTOR2 *WINAPI D3DXVec2BaryCentric(

    D3DXVECTOR2 *pOut,
    CONST D3DXVECTOR2 *pV1,
    CONST D3DXVECTOR2 *pV2,
    CONST D3DXVECTOR2 *pV3,
    FLOAT f,
    FLOAT g
);

Parameters

pOut
[out, retval] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.
pV3
[in] Pointer to a source D3DXVECTOR2 structure.
f
[in] Weighting factor. See Remarks.
g
[in] Weighting factor. See Remarks.

Return Value

Pointer to a D3DXVECTOR2 structure in Barycentric coordinates.

Remarks

The D3DXVec2BaryCentric function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + f(V2-V1) + g(V3-V1).

Any point in the plane V1V2V3 can be represented by the Barycentric coordinate ( f,g).The parameter f controls how much V2 gets weighted into the result, and the parameter g controls how much V3 gets weighted into the result. Lastly, 1- f- g controls how much V1 gets weighted into the result.

Note the following relations.

  • If (f>=0 && g>=0 && 1-f-g>=0), the point is inside the triangle V1V2V3.
  • If (f==0 && g>=0 && 1-f-g>=0), the point is on the line V1V3.
  • If (f>=0 && g==0 && 1-f-g>=0), the point is on the line V1V2.
  • If (f>=0 && g>=0 && 1-f-g==0), the point is on the line V2V3.

Barycentric coordinates are a form of general coordinates. In this context, using Barycentric coordinates represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for Barycentric coordinates.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2BaryCentric function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXVec2CatmullRom Function

Performs a Catmull-Rom interpolation, using the specified 2-D vectors.

Syntax

D3DXVECTOR2 *WINAPI D3DXVec2CatmullRom(

    D3DXVECTOR2 *pOut,
    const D3DXVECTOR2 *pV0,
    const D3DXVECTOR2 *pV1,
    const D3DXVECTOR2 *pV2,
    const D3DXVECTOR2 *pV3,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV0
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
pV1
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
pV2
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
pV3
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
s
[in] Weighting factor. See Remarks.

Return Value

Pointer to a D3DXVECTOR2 structure that is the result of the Catmull-Rom interpolation.

Remarks

Given four points (p1, p2, p3, p4), find a function Q(s) such that:

Q(s) is a cubic function.
Q(s) interpolates between p2 and p3 as s ranges from 0 to 1.
Q(s) is parallel to the line joining p1 to p3 when s is 0.
Q(s) is parallel to the line joining p2 to p4 when s is 1.

The Catmull-Rom spline can be derived from the Hermite spline by setting:

v1 = p2
v2 = p3
t1 = (p3 - p1) / 2
t2 = (p4 - p2) / 2

where:

v1 is the contents of pV0.

v2 is the contents of pV1.

p3 is the contents of pV2.

p4 is the contents of pV3.

Using the Hermite spline equation:

Q(s) = (2s3 - 3s2 + 1)v1 + (-2s3 + 3s2)v2 + (s3 - 2s2 + s)t1 + (s3 - s2)t2

and substituting for v1, v2, t1, t2 yields:

Q(s) = (2s3 - 3s2 + 1)p2 + (-2s3 + 3s2)p3 + (s3 - 2s2 + s)(p3 - p1) / 2 + (s3 - s2)(p4 - p2)/2

This can be rearranged as:

Q(s) = [(-s3 + 2s2 - s)p1 + (3s3 - 5s2 + 2)p2 + (-3s3 + 4s2 + s)p3 + (s3 - s2)p4] / 2

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3CatmullRom, D3DXVec4CatmullRom


D3DXVec2CCW Function

Returns the z-component by taking the cross product of two 2-D vectors.

Syntax

FLOAT D3DXVec2CCW(

    CONST D3DXVECTOR2 *pV1,
    CONST D3DXVECTOR2 *pV2
);

Parameters

pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.

Return Value

The z-component.

Remarks

This function determines the z-component by determining the cross-product based on the following formula: ((x1,y1,0) cross (x2,y2,0)). Or as shown in the following example.

pV1->x * pV2->y - pV1->y * pV2->x

If the value of the z-component is positive, the vector V2 is counterclockwise from the vector V1. This information is useful for back-face culling.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2Dot


D3DXVec2Dot Function

Determines the dot product of two 2-D vectors.

Syntax

FLOAT D3DXVec2Dot(

    CONST D3DXVECTOR2 *pV1,
    CONST D3DXVECTOR2 *pV2
);

Parameters

pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.

Return Value

The dot product.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2CCW


D3DXVec2Hermite Function

Performs a Hermite spline interpolation, using the specified 2-D vectors.

Syntax

D3DXVECTOR2 *WINAPI D3DXVec2Hermite(

    D3DXVECTOR2 *pOut,
    CONST D3DXVECTOR2 *pV1,
    CONST D3DXVECTOR2 *pT1,
    CONST D3DXVECTOR2 *pV2,
    CONST D3DXVECTOR2 *pT2,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
pT1
[in] Pointer to a source D3DXVECTOR2 structure, a tangent vector.
pV2
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
pT2
[in] Pointer to a source D3DXVECTOR2 structure, a tangent vector.
s
[in] Weighting factor. See Remarks.

Return Value

Pointer to a D3DXVECTOR2 structure that is the result of the Hermite spline interpolation.

Remarks

The D3DXVec2Hermite function interpolates from (positionA, tangentA) to (positionB, tangentB) using Hermite spline interpolation.

The spline interpolation is a generalization of the ease-in, ease-out spline. The ramp is a function of Q(s) with the following properties.

Q(s) = As3 + Bs2 + Cs + D (and therefore, Q'(s) = 3As2 + 2Bs + C)

a) Q(0) = v1, so Q'(0) = t1
b) Q(1) = v2, so Q'(1) = t2

v1 is the contents of pV1, v2 in the contents of pV2, t1 is the contents of pT1, and t2 is the contents of pT2.

These properties are used to solve for A, B, C, D.

D = v1  (from a)
C = t1  (from a)
3A + 2B = t2 - t-1 (substituting for C)
A + B = v2 - v1 - t1 (substituting for C and D)

Plug in the solutions for A,B,C and D to generate Q(s).

A = 2v1 - 2v2 + t2 + t1
B = 3v2 - 3v1 - 2t1 - t2
C = t1
D = v1

This yields:

Q(s) = (2v1 - 2v2 + t2 + t1)s3 + (3v2 - 3v1 - 2t1 - t2)s2 + t1s + v1.

// Which can be rearranged as:

Q(s) = (2s3 - 3s2 + 1)v1 + (-2s3 + 3s2)v2 + (s3 - 2s2 + s)t1 + (s3 - s2)t2.

Hermite splines are useful for controlling animation because the curve runs through all the control points. Also, because the position and tangent are explicitly specified at the ends of each segment, it is easy to create a C2 continuous curve as long as you make sure that your starting position and tangent match the ending values of the last segment.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Hermite function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXVec2Length Function

Returns the length of a 2-D vector.

Syntax

FLOAT D3DXVec2Length(

    CONST D3DXVECTOR2 *pV
);

Parameters

pV
[in] Pointer to the source D3DXVECTOR2 structure.

Return Value

The vector's length.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2LengthSq


D3DXVec2LengthSq Function

Returns the square of the length of a 2-D vector.

Syntax

FLOAT D3DXVec2LengthSq(

    CONST D3DXVECTOR2 *pV
);

Parameters

pV
[in] Pointer to the source D3DXVECTOR2 structure.

Return Value

The vector's squared length.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2Length


D3DXVec2Lerp Function

Performs a linear interpolation between two 2-D vectors.

Syntax

D3DXVECTOR2 *D3DXVec2Lerp(

    D3DXVECTOR2 *pOut,
    CONST D3DXVECTOR2 *pV1,
    CONST D3DXVECTOR2 *pV2,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.
s
[in] Parameter that linearly interpolates between the vectors.

Return Value

Pointer to a D3DXVECTOR2 structure that is the result of the linear interpolation.

Remarks

This function performs the linear interpolation based on the following formula: V1 + s(V2-V1).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Lerp function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXVec2Maximize Function

Returns a 2-D vector that is made up of the largest components of two 2-D vectors.

Syntax

D3DXVECTOR2 *D3DXVec2Maximize(

    D3DXVECTOR2 *pOut,
    CONST D3DXVECTOR2 *pV1,
    CONST D3DXVECTOR2 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.

Return Value

Pointer to a D3DXVECTOR2 structure that is made up of the largest components of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Maximize function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2Minimize


D3DXVec2Minimize Function

Returns a 2-D vector that is made up of the smallest components of two 2-D vectors.

Syntax

D3DXVECTOR2 *D3DXVec2Minimize(

    D3DXVECTOR2 *pOut,
    CONST D3DXVECTOR2 *pV1,
    CONST D3DXVECTOR2 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.

Return Value

Pointer to a D3DXVECTOR2 structure that is made up of the smallest components of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Minimize function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2Maximize


D3DXVec2Normalize Function

Returns the normalized version of a 2-D vector.

Syntax

D3DXVECTOR2 *WINAPI D3DXVec2Normalize(

    D3DXVECTOR2 *pOut,
    CONST D3DXVECTOR2 *pV
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR2 structure.

Return Value

Pointer to a D3DXVECTOR2 structure that is the normalized version of the vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Normalize function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXVec2Scale Function

Scales a 2-D vector.

Syntax

D3DXVECTOR2 *D3DXVec2Scale(

    D3DXVECTOR2 *pOut,
    CONST D3DXVECTOR2 *pV,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR2 structure.
s
[in] Scaling value.

Return Value

Pointer to a D3DXVECTOR2 structure that is the scaled vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Scale function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2Add, D3DXVec2Subtract


D3DXVec2Subtract Function

Subtracts two 2-D vectors.

Syntax

D3DXVECTOR2 *D3DXVec2Subtract(

    D3DXVECTOR2 *pOut,
    CONST D3DXVECTOR2 *pV1,
    CONST D3DXVECTOR2 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.

Return Value

Pointer to a D3DXVECTOR2 structure that is the difference of two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Subtract function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2Add, D3DXVec2Scale


D3DXVec2Transform Function

Transforms a 2-D vector by a given matrix.

Syntax

D3DXVECTOR4 *WINAPI D3DXVec2Transform(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR2 *pV,
    CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR2 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Value

Pointer to a D3DXVECTOR4 structure that is the transformed vector.

Remarks

This function transforms the vector pV (x, y, 0, 1) by the matrix pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Transform function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2TransformCoord, D3DXVec2TransformNormal


D3DXVec2TransformArray Function

Transforms an array (x, y, 0, 1) by a given matrix.

Syntax

D3DXVECTOR4 *WINAPI D3DXVec2TransformArray(

    D3DXVECTOR4 *pOut,
    UINT OutStride,
    CONST D3DXVECTOR2 *pV,
    UINT VStride,
    CONST D3DXMATRIX *pM,
    UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR2 structure.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure.
n
[in] Number of elements in the array.

Return Value

Pointer to a D3DXVECTOR4 structure that is the transformed array.

Remarks

This function transforms the array pV (x, y, 0, 1) by the matrix pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Transform function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2TransformCoord, D3DXVec2TransformNormal


D3DXVec2TransformCoord Function

Transforms a 2-D vector by a given matrix, projecting the result back into w = 1.

Syntax

D3DXVECTOR2 *WINAPI D3DXVec2TransformCoord(

    D3DXVECTOR2 *pOut,
    CONST D3DXVECTOR2 *pV,
    CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR2 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Value

Pointer to a D3DXVECTOR2 structure that is the transformed vector.

Remarks

This function transforms the vector, pV (x, y, 0, 1), by the matrix, pM, projecting the result back into w=1.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2TransformCoord function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2Transform, D3DXVec2TransformNormal


D3DXVec2TransformCoordArray Function

Transforms an array (x, y, 0, 1) by a given matrix, and projects the result back into w = 1.

Syntax

D3DXVECTOR2 *WINAPI D3DXVec2TransformCoordArray(

    D3DXVECTOR2* pOut,
    UINT OutStride,
    const D3DXVECTOR2 *pV,
    UINT VStride,
    const D3DXMATRIX *pM,
    UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR2 array.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure.
n
[in] Number of elements in the array.

Return Value

Pointer to a D3DXVECTOR4 transformed array.

Remarks

This function transforms the array pV (x, y, 0, 1) by the matrix pM, projecting the result back into w = 1.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2TransformCoordArray function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXVec2TransformNormal Function

Transforms the 2-D vector normal by the given matrix.

Syntax

D3DXVECTOR2 *WINAPI D3DXVec2TransformNormal(

    D3DXVECTOR2* pOut,
    CONST D3DXVECTOR2 *pV,
    CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR2 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Value

Pointer to a D3DXVECTOR2 structure that is the transformed vector.

Remarks

This function transforms the vector normal (x, y, 0, 0) of the vector, pV, by the matrix, pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2TransformNormal function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2Transform, D3DXVec2TransformCoord


D3DXVec2TransformNormalArray Function

Transforms an array (x, y, 0, 0) by a given matrix.

Syntax

D3DXVECTOR2 *WINAPI D3DXVec2TransformNormalArray(

    D3DXVECTOR2* pOut,
    UINT OutStride,
    CONST D3DXVECTOR2* pV,
    UINT VStride,
    CONST D3DXMATRIX* pM,
    UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR2 array.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure. To transpose a normal with a non-affine matrix, this matrix should be a transposed-inverse transformation matrix.
n
[in] Number of elements in the array.

Return Value

Pointer to a D3DXVECTOR2 structure that is the transformed array.

Remarks

This function transforms the vector normal pV (x, y, 0, 0) by the matrix pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2TransformNormal function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXVec3Add Function

Adds two 3-D vectors.

Syntax

D3DXVECTOR3 *D3DXVec3Add(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV1,
    CONST D3DXVECTOR3 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.

Return Value

Pointer to a D3DXVECTOR3 structure that is the sum of the two 3-D vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Add function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Subtract, D3DXVec3Scale


D3DXVec3BaryCentric Function

Returns a point in Barycentric coordinates, using the specified 3-D vectors.

Syntax

D3DXVECTOR3 *WINAPI D3DXVec3BaryCentric(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV1,
    CONST D3DXVECTOR3 *pV2,
    CONST D3DXVECTOR3 *pV3,
    FLOAT f,
    FLOAT g
);

Parameters

pOut
[out, retval] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.
pV3
[in] Pointer to a source D3DXVECTOR3 structure.
f
[in] Weighting factor. See Remarks.
g
[in] Weighting factor. See Remarks.

Return Value

Pointer to a D3DXVECTOR3 structure in Barycentric coordinates.

Remarks

The D3DXVec3BaryCentric function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + f(V2-V1) + g(V3-V1).

Any point in the plane V1V2V3 can be represented by the Barycentric coordinate ( f,g).The parameter f controls how much V2 gets weighted into the result and the parameter g controls how much V3 gets weighted into the result. Lastly, 1- f- g controls how much V1 gets weighted into the result.

Note the following relations.

  • If (f>=0 && g>=0 && 1-f-g>=0), the point is inside the triangle V1V2V3.
  • If (f==0 && g>=0 && 1-f-g>=0), the point is on the line V1V3.
  • If (f>=0 && g==0 && 1-f-g>=0), the point is on the line V1V2.
  • If (f>=0 && g>=0 && 1-f-g==0), the point is on the line V2V3.

Barycentric coordinates are a form of general coordinates. In this context, using Barycentric coordinates represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for Barycentric coordinates.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3BaryCentric function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXVec3CatmullRom Function

Performs a Catmull-Rom interpolation, using the specified 3-D vectors.

Syntax

D3DXVECTOR3 *WINAPI D3DXVec3CatmullRom(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV0,
    CONST D3DXVECTOR3 *pV1,
    CONST D3DXVECTOR3 *pV2,
    CONST D3DXVECTOR3 *pV3,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV0
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
pV1
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
pV2
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
pV3
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
s
[in] Weighting factor. See Remarks.

Return Value

Pointer to a D3DXVECTOR3 structure that is the result of the Catmull-Rom interpolation.

Remarks

Given four points (p1, p2, p3, p4), find a function Q(s) such that:

Q(s) is a cubic function.
Q(s) interpolates between p2 and p3 as s ranges from 0 to 1.
Q(s) is parallel to the line joining p1 to p3 when s is 0.
Q(s) is parallel to the line joining p2 to p4 when s is 1.

The Catmull-Rom spline can be derived from the Hermite spline by setting:

v1 = p2
v2 = p3
t1 = (p3 - p1) / 2
t2 = (p4 - p2) / 2

where:

v1 is the contents of pV0.

v2 is the contents of pV1.

p3 is the contents of pV2.

p4 is the contents of pV3.

Using the Hermite spline equation:

Q(s) = (2s3 - 3s2 + 1)v1 + (-2s3 + 3s2)v2 + (s3 - 2s2 + s)t1 + (s3 - s2)t2

and substituting for v1, v2, t1, t2 yields:

Q(s) = (2s3 - 3s2 + 1)p2 + (-2s3 + 3s2)p3 + (s3 - 2s2 + s)(p3 - p1) / 2 + (s3 - s2)(p4 - p2) / 2

This can be rearranged as:

Q(s) = [(-s3 + 2s2 - s)p1 + (3s3 - 5s2 + 2)p2 + (-3s3 + 4s2 + s)p3 + (s3 - s2)p4] / 2

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2CatmullRom, D3DXVec4CatmullRom


D3DXVec3Cross Function

Determines the cross-product of two 3-D vectors.

Syntax

D3DXVECTOR3 *D3DXVec3Cross(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV1,
    CONST D3DXVECTOR3 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.

Return Value

Pointer to a D3DXVECTOR3 structure that is the cross product of two 3-D vectors.

Remarks

This function determines the cross-product with the following code.

    D3DXVECTOR3 v;

    v.x = pV1->y * pV2->z - pV1->z * pV2->y;

    v.y = pV1->z * pV2->x - pV1->x * pV2->z;

    v.z = pV1->x * pV2->y - pV1->y * pV2->x;

    *pOut = v;

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Cross function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Dot


D3DXVec3Dot Function

Determines the dot-product of two 3-D vectors.

Syntax

FLOAT D3DXVec3Dot(

    CONST D3DXVECTOR3 *pV1,
    CONST D3DXVECTOR3 *pV2
);

Parameters

pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.

Return Value

The dot-product.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Cross


D3DXVec3Hermite Function

Performs a Hermite spline interpolation, using the specified 3-D vectors.

Syntax

D3DXVECTOR3 *WINAPI D3DXVec3Hermite(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV1,
    CONST D3DXVECTOR3 *pT1,
    CONST D3DXVECTOR3 *pV2,
    CONST D3DXVECTOR3 *pT2,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
pT1
[in] Pointer to a source D3DXVECTOR3 structure, a tangent vector.
pV2
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
pT2
[in] Pointer to a source D3DXVECTOR3 structure, a tangent vector.
s
[in] Weighting factor. See Remarks.

Return Value

Pointer to a D3DXVECTOR3 structure that is the result of the Hermite spline interpolation.

Remarks

The D3DXVec3Hermite function interpolates from (positionA, tangentA) to (positionB, tangentB) using Hermite spline interpolation.

The spline interpolation is a generalization of the ease-in, ease-out spline. The ramp is a function of Q(s) with the following properties.

Q(s) = As3 + Bs2 + Cs + D (and therefore, Q'(s) = 3As2 + 2Bs + C)

a) Q(0) = v1, so Q'(0) = t1
b) Q(1) = v2, so Q'(1) = t2

v1 is the contents of pV1, v2 in the contents of pV2, t1 is the contents of pT1, and t2 is the contents of pT2.

These properties are used to solve for A, B, C, D.

D = v1  (from a)
C = t1  (from a)
3A + 2B = t2 - t1 (substituting for C)
A + B = v2 - v1 - t1 (substituting for C and D)

Plug in the solutions for A,B,C and D to generate Q(s).

A = 2v1 - 2v2 + t2 + t1
B = 3v2 - 3v1 - 2t1 - t2
C = t1
D = v1

This yields:

Q(s) = (2v1 - 2v2 + t2 + t1)s3 + (3v2 - 3v1 - 2t1 - t2)s2 + t1s + v1.

// Which can be rearranged as:

Q(s) = (2s3 - 3s2 + 1)v1 + (-2s3 + 3s2)v2 + (s3 - 2s2 + s)t1 + (s3 - s2)t2.

Hermite splines are useful for controlling animation because the curve runs through all the control points. Also, because the position and tangent are explicitly specified at the ends of each segment, it is easy to create a C2 continuous curve as long as you make sure that your starting position and tangent match the ending values of the last segment.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Hermite function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXVec3Length Function

Returns the length of a 3-D vector.

Syntax

FLOAT D3DXVec3Length(

    CONST D3DXVECTOR3 *pV
);

Parameters

pV
[in] Pointer to the source D3DXVECTOR3 structure.

Return Value

The vector's length.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3LengthSq


D3DXVec3LengthSq Function

Returns the square of the length of a 3-D vector.

Syntax

FLOAT D3DXVec3LengthSq(

    CONST D3DXVECTOR3 *pV
);

Parameters

pV
[in] Pointer to the source D3DXVECTOR3 structure.

Return Value

The vector's squared length.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Length


D3DXVec3Lerp Function

Performs a linear interpolation between two 3-D vectors.

Syntax

D3DXVECTOR3 *D3DXVec3Lerp(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV1,
    CONST D3DXVECTOR3 *pV2,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.
s
[in] Parameter that linearly interpolates between the vectors.

Return Value

Pointer to a D3DXVECTOR3 structure that is the result of the linear interpolation.

Remarks

This function performs the linear interpolation based on the following formula: V1 + s(V2-V1).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Lerp function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXVec3Maximize Function

Returns a 3-D vector that is made up of the largest components of two 3-D vectors.

Syntax

D3DXVECTOR3 *D3DXVec3Maximize(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV1,
    CONST D3DXVECTOR3 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.

Return Value

Pointer to a D3DXVECTOR3 structure that is made up of the largest components of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Maximize function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Minimize


D3DXVec3Minimize Function

Returns a 3-D vector that is made up of the smallest components of two 3-D vectors.

Syntax

D3DXVECTOR3 *D3DXVec3Minimize(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV1,
    CONST D3DXVECTOR3 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.

Return Value

Pointer to a D3DXVECTOR3 structure that is made up of the smallest components of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Minimize function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Maximize


D3DXVec3Normalize Function

Returns the normalized version of a 3-D vector.

Syntax

D3DXVECTOR3 *WINAPI D3DXVec3Normalize(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.

Return Value

Pointer to a D3DXVECTOR3 structure that is the normalized version of the specified vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Normalize function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXVec3Project Function

Projects a 3-D vector from object space into screen space.

Syntax

D3DXVECTOR3 *WINAPI D3DXVec3Project(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV,
    CONST D3DVIEWPORT9 *pViewport,
    CONST D3DXMATRIX *pProjection,
    CONST D3DXMATRIX *pView,
    CONST D3DXMATRIX *pWorld
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
pViewport
[in] Pointer to a D3DVIEWPORT9 structure, representing the viewport.
pProjection
[in] Pointer to a D3DXMATRIX structure, representing the projection matrix.
pView
[in] Pointer to a D3DXMATRIX structure, representing the view matrix.
pWorld
[in] Pointer to a D3DXMATRIX structure, representing the world matrix.

Return Value

Pointer to a D3DXVECTOR3 structure that is the vector projected from object space to screen space.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Project function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Unproject


D3DXVec3ProjectArray Function

Projects an array (x, y, z, 0) from object space into screen space.

Syntax

D3DXVECTOR3 *WINAPI D3DXVec3ProjectArray(

    D3DXVECTOR3 *pOut,
    UINT OutStride,
    CONST D3DXVECTOR3 *pV,
    UINT VStride,
    CONST D3DVIEWPORT9 *pViewport,
    CONST D3DXMATRIX *pProjection,
    CONST D3DXMATRIX *pView,
    CONST D3DXMATRIX *pWorld,
    UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
VStride
[in] Stride between vectors in the input data stream.
pViewport
[in] Pointer to a D3DVIEWPORT9 structure, representing the viewport.
pProjection
[in] Pointer to a D3DXMATRIX structure, representing the projection matrix.
pView
[in] Pointer to a D3DXMATRIX structure, representing the view matrix.
pWorld
[in] Pointer to a D3DXMATRIX structure, representing the world matrix.
n
[in] Number of elements in the array.

Return Value

Pointer to a D3DXVECTOR3 structure that is the array projected from object space to screen space.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3ProjectArray function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Unproject


D3DXVec3Scale Function

Scales a 3-D vector.

Syntax

D3DXVECTOR3 *D3DXVec3Scale(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
s
[in] Scaling value.

Return Value

Pointer to a D3DXVECTOR3 structure that is the scaled vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Scale function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Add, D3DXVec3Subtract


D3DXVec3Subtract Function

Subtracts two 3-D vectors.

Syntax

D3DXVECTOR3 *D3DXVec3Subtract(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV1,
    CONST D3DXVECTOR3 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.

Return Value

Pointer to a D3DXVECTOR3 structure that is the difference of two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Subtract function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Add, D3DXVec3Scale


D3DXVec3Transform Function

Transforms vector (x, y, z, 1) by a given matrix.

Syntax

D3DXVECTOR4 *WINAPI D3DXVec3Transform(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR3 *pV,
    CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Value

Pointer to a D3DXVECTOR4 structure that is the transformed vector.

Remarks

This function transforms the vector, pV (x, y, z, 1), by the matrix pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Transform function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXVec3TransformArray Function

Transforms an array (x, y, z, 1) by a given matrix.

Syntax

D3DXVECTOR4 *WINAPI D3DXVec3TransformArray(

    D3DXVECTOR4 *pOut,
    UINT OutStride,
    CONST D3DXVECTOR3* pV,
    UINT VStride,
    CONST D3DXMATRIX* pM,
    UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 array that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR3 array.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure.
n
[in] Number of elements in the array.

Return Value

Pointer to a D3DXVECTOR4 transformed array.

Remarks

This function transforms the array pV (x, y, z, 1) by the matrix pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3TransformArray function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXVec3TransformCoord Function

Transforms a 3-D vector by a given matrix, projecting the result back into w = 1.

Syntax

D3DXVECTOR3 *WINAPI D3DXVec3TransformCoord(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV,
    CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Value

Pointer to a D3DXVECTOR3 structure that is the transformed vector.

Remarks

This function transforms the vector, pV (x, y, z, 1), by the matrix, pM, projecting the result back into w=1.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3TransformCoord function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Transform, D3DXVec3TransformNormal


D3DXVec3TransformCoordArray Function

Transforms an array (x, y, z, 1) by a given matrix, and projects the result back into w = 1.

Syntax

D3DXVECTOR3 *WINAPI D3DXVec3TransformCoordArray(

    D3DXVECTOR3* pOut,
    UINT OutStride,
    CONST D3DXVECTOR3* pV,
    UINT VStride,
    CONST D3DXMATRIX* pM,
    UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR3 array.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure.
n
[in] Number of elements in the array.

Return Value

Pointer to a D3DXVECTOR3 structure that is the transformed array.

Remarks

This function transforms the array pV (x, y, z, 1) by the matrix pM, projecting the result back into w = 1.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3TransformCoord function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXVec3TransformNormal Function

Transforms the 3-D vector normal by the given matrix.

Syntax

D3DXVECTOR3 *WINAPI D3DXVec3TransformNormal(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV,
    CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Value

Pointer to a D3DXVECTOR3 structure that is the transformed vector.

Remarks

This function transforms the vector normal (x, y, z, 0) of the vector, pV, by the matrix, pM.

If you transform a normal by a non-affine matrix, the matrix you pass to this function should be the transpose of the inverse of the matrix you would use to transform a coordinate.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3TransformNormal function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXVec3TransformNormalArray Function

Transforms an array (x, y, z, 0) by a given matrix.

Syntax

D3DXVECTOR3 *WINAPI D3DXVec3TransformNormalArray(

    D3DXVECTOR3* pOut,
    UINT OutStride,
    CONST D3DXVECTOR3* pV,
    UINT VStride,
    CONST D3DXMATRIX* pM,
    UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 array that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR3 array.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure. To transpose a normal with a non-affine matrix, this matrix should be a transposed-inverse transformation matrix.
n
[in] Number of elements in the array.

Return Value

Pointer to a D3DXVECTOR3 array that is the transformed array.

Remarks

This function transforms the vector normal pV (x, y, z, 0) by the matrix pM.

If you transform a normal by a non-affine matrix, the matrix you pass to this function should be the transpose of the inverse of the matrix you would use to transform a coordinate.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3TransformNormalArray function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXVec3Unproject Function

Projects a vector from screen space into object space.

Syntax

D3DXVECTOR3 *WINAPI D3DXVec3Unproject(

    D3DXVECTOR3 *pOut,
    CONST D3DXVECTOR3 *pV,
    CONST D3DVIEWPORT9 *pViewport,
    CONST D3DXMATRIX *pProjection,
    CONST D3DXMATRIX *pView,
    CONST D3DXMATRIX *pWorld
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
pViewport
[in] Pointer to a D3DVIEWPORT9 structure, representing the viewport.
pProjection
[in] Pointer to a D3DXMATRIX structure, representing the projection matrix.
pView
[in] Pointer to a D3DXMATRIX structure, representing the view matrix.
pWorld
[in] Pointer to a D3DXMATRIX structure, representing the world matrix.

Return Value

Pointer to a D3DXVECTOR3 structure that is the vector projected from screen space to object space.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Unproject function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Project


D3DXVec3UnprojectArray Function

Projects an array (x, y, z, 0) from screen space into object space.

Syntax

D3DXVECTOR3 *WINAPI D3DXVec3UnprojectArray(

    D3DXVECTOR3 *pOut,
    UINT OutStride,
    CONST D3DXVECTOR3 *pV,
    UINT VStride,
    CONST D3DVIEWPORT9 *pViewport,
    CONST D3DXMATRIX *pProjection,
    CONST D3DXMATRIX *pView,
    CONST D3DXMATRIX *pWorld,
    UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
VStride
[in] Stride between vectors in the input data stream.
pViewport
[in] Pointer to a D3DVIEWPORT9 structure, representing the viewport.
pProjection
[in] Pointer to a D3DXMATRIX structure, representing the projection matrix.
pView
[in] Pointer to a D3DXMATRIX structure, representing the view matrix.
pWorld
[in] Pointer to a D3DXMATRIX structure, representing the world matrix.
n
[in] Number of elements in the array.

Return Value

Pointer to a D3DXVECTOR3 structure that is the array projected from screen space to object space.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Unproject function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Project


D3DXVec4Add Function

Adds two 4-D vectors.

Syntax

D3DXVECTOR4 *D3DXVec4Add(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR4 *pV1,
    CONST D3DXVECTOR4 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.

Return Value

Pointer to a D3DXVECTOR4 structure that is the sum of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Add function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec4Subtract, D3DXVec4Scale


D3DXVec4BaryCentric Function

Returns a point in Barycentric coordinates, using the specified 4-D vectors.

Syntax

D3DXVECTOR4 *WINAPI D3DXVec4BaryCentric(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR4 *pV1,
    CONST D3DXVECTOR4 *pV2,
    CONST D3DXVECTOR4 *pV3,
    FLOAT f,
    FLOAT g
);

Parameters

pOut
[out, retval] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.
pV3
[in] Pointer to a source D3DXVECTOR4 structure.
f
[in] Weighting factor. See Remarks.
g
[in] Weighting factor. See Remarks.

Return Value

Pointer to a D3DXVECTOR4 structure in Barycentric coordinates.

Remarks

The D3DXVec4BaryCentric function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + f(V2-V1) + g(V3-V1).

Any point in the plane V1V2V3 can be represented by the Barycentric coordinate ( f,g).The parameter f controls how much V2 gets weighted into the result and the parameter g controls how much V3 gets weighted into the result. Lastly, 1- f- g controls how much V1 gets weighted into the result.

Note the following relations.

  • If (f>=0 && g>=0 && 1-f-g>=0), the point is inside the triangle V1V2V3.
  • If (f==0 && g>=0 && 1-f-g>=0), the point is on the line V1V3.
  • If (f>=0 && g==0 && 1-f-g>=0), the point is on the line V1V2.
  • If (f>=0 && g>=0 && 1-f-g==0), the point is on the line V2V3.

Barycentric coordinates are a form of general coordinates. In this context, using Barycentric coordinates represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for Barycentric coordinates.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4BaryCentric function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXVec4CatmullRom Function

Performs a Catmull-Rom interpolation, using the specified 4-D vectors.

Syntax

D3DXVECTOR4 *WINAPI D3DXVec4CatmullRom(

    D3DXVECTOR4 *pOut,
    const D3DXVECTOR4 *pV0,
    const D3DXVECTOR4 *pV1,
    const D3DXVECTOR4 *pV2,
    const D3DXVECTOR4 *pV3,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV0
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
pV1
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
pV2
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
pV3
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
s
[in] Weighting factor. See Remarks.

Return Value

Pointer to a D3DXVECTOR4 structure that is the result of the Catmull-Rom interpolation.

Remarks

Given four points (p1, p2, p3, p4), find a function Q(s) such that:

Q(s) is a cubic function.
Q(s) interpolates between p2 and p3 as s ranges from 0 to 1.
Q(s) is parallel to the line joining p1 to p3 when s is 0.
Q(s) is parallel to the line joining p2 to p4 when s is 1.

The Catmull-Rom spline can be derived from the Hermite spline by setting:

v1 = p2
v2 = p3
t1 = (p3 - p1) / 2
t2 = (p4 - p2) / 2

where:

v1 is the contents of pV0.

v2 in the contents of pV1.

p3 is the contents of pV2.

p4 is the contents of pV3.

Using the Hermite spline equation:

Q(s) = (2s3 - 3s2 + 1)v1 + (-2s3 + 3s2)v2 + (s3 - 2s2 + s)t1 + (s3 - s2)t2

and substituting for v1, v2, t1, t2 yields:

Q(s) = (2s3 - 3s2 + 1)p2 + (-2s3 + 3s2)p3 + (s3 - 2s2 + s)(p3 - p1) / 2 + (s3 - s2)(p4 - p2) / 2

This can be rearranged as:

Q(s) = [(-s3 + 2s2 - s)p1 + (3s3 - 5s2 + 2)p2 + (-3s3 + 4s2 + s)p3 + (s3 - s2)p4] / 2

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec2CatmullRom, D3DXVec3CatmullRom


D3DXVec4Cross Function

Determines the cross-product in four dimensions.

Syntax

D3DXVECTOR4 *WINAPI D3DXVec4Cross(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR4 *pV1,
    CONST D3DXVECTOR4 *pV2,
    CONST D3DXVECTOR4 *pV3
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.
pV3
[in] Pointer to a source D3DXVECTOR4 structure.

Return Value

Pointer to a D3DXVECTOR4 structure that is the cross product.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Cross function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec4Dot


D3DXVec4Dot Function

Determines the dot product of two 4-D vectors.

Syntax

FLOAT D3DXVec4Dot(

    CONST D3DXVECTOR4 *pV1,
    CONST D3DXVECTOR4 *pV2
);

Parameters

pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.

Return Value

The dot product.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec4Cross


D3DXVec4Hermite Function

Performs a Hermite spline interpolation, using the specified 4-D vectors.

Syntax

D3DXVECTOR4 *WINAPI D3DXVec4Hermite(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR4 *pV1,
    CONST D3DXVECTOR4 *pT1,
    CONST D3DXVECTOR4 *pV2,
    CONST D3DXVECTOR4 *pT2,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
pT1
[in] Pointer to a source D3DXVECTOR4 structure, a tangent vector.
pV2
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
pT2
[in] Pointer to a source D3DXVECTOR4 structure, a tangent vector.
s
[in] Weighting factor. See Remarks.

Return Value

Pointer to a D3DXVECTOR4 structure that is the result of the Hermite spline interpolation.

Remarks

The D3DXVec4Hermite function interpolates from (positionA, tangentA) to (positionB, tangentB) using Hermite spline interpolation.

The spline interpolation is a generalization of the ease-in, ease-out spline. The ramp is a function of Q(s) with the following properties.

Q(s) = As3 + Bs2 + Cs + D (and therefore, Q'(s) = 3As2 + 2Bs + C)

a) Q(0) = v1, so Q'(0) = t1
b) Q(1) = v2, so Q'(1) = t2

v1 is the contents of pV1, v2 in the contents of pV2, t1 is the contents of pT1, and t2 is the contents of pT2.

These properties are used to solve for A, B, C, D.

D = v1  (from a)
C = t1  (from a)
3A + 2B = t2 - t-1 (substituting for C)
A + B = v2 - v1 - t1 (substituting for C and D)

Plug in the solutions for A,B,C and D to generate Q(s).

A = 2v1 - 2v2 + t2 + t1
B = 3v2 - 3v1 - 2t1 - t2
C = t1
D = v1

This yields:

Q(s) = (2v1 - 2v2 + t2 + t1)s3 + (3v2 - 3v1 - 2t1 - t2)s2 + t1s + v1.

// Which can be rearranged as:

Q(s) = (2s3 - 3s2 + 1)v1 + (-2s3 + 3s2)v2 + (s3 - 2s2 + s)t1 + (s3 - s2)t2.

Hermite splines are useful for controlling animation because the curve runs through all the control points. Also, because the position and tangent are explicitly specified at the ends of each segment, it is easy to create a C2 continuous curve as long as you make sure that your starting position and tangent match the ending values of the last segment.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Hermite function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXVec4Length Function

Returns the length of a 4-D vector.

Syntax

FLOAT D3DXVec4Length(

    CONST D3DXVECTOR4 *pV
);

Parameters

pV
[in] Pointer to the source D3DXVECTOR4 structure.

Return Value

The vector's length.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec4LengthSq


D3DXVec4LengthSq Function

Returns the square of the length of a 4-D vector.

Syntax

FLOAT D3DXVec4LengthSq(

    CONST D3DXVECTOR4 *pV
);

Parameters

pV
[in] Pointer to the source D3DXVECTOR4 structure.

Return Value

The vector's squared length.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec4Length


D3DXVec4Lerp Function

Performs a linear interpolation between two 4-D vectors.

Syntax

D3DXVECTOR4 *D3DXVec4Lerp(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR4 *pV1,
    CONST D3DXVECTOR4 *pV2,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.
s
[in] Parameter that linearly interpolates between the vectors.

Return Value

Pointer to a D3DXVECTOR4 structure that is the result of the linear interpolation.

Remarks

This function performs the linear interpolation based on the following formula: V1 + s(V2-V1).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Lerp function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXVec4Maximize Function

Returns a 4-D vector that is made up of the largest components of two 4-D vectors.

Syntax

D3DXVECTOR4 *D3DXVec4Maximize(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR4 *pV1,
    CONST D3DXVECTOR4 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.

Return Value

Pointer to a D3DXVECTOR4 structure that is made up of the largest components of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Maximize function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec4Minimize


D3DXVec4Minimize Function

Returns a 4-D vector that is made up of the smallest components of two 4-D vectors.

Syntax

D3DXVECTOR4 *D3DXVec4Minimize(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR4 *pV1,
    CONST D3DXVECTOR4 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.

Return Value

Pointer to a D3DXVECTOR4 structure that is made up of the smallest components of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Minimize function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec4Maximize


D3DXVec4Normalize Function

Returns the normalized version of a 4-D vector.

Syntax

D3DXVECTOR4 *WINAPI D3DXVec4Normalize(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR4 *pV
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR4 structure.

Return Value

Pointer to a D3DXVECTOR4 structure that is the normalized version of the vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Normalize function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXVec4Scale Function

Scales a 4-D vector.

Syntax

D3DXVECTOR4 *D3DXVec4Scale(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR4 *pV,
    FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR4 structure.
s
[in] Scaling value.

Return Value

Pointer to the D3DXVECTOR4 structure that is the scaled vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Scale function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec4Add, D3DXVec4Subtract


D3DXVec4Subtract Function

Subtracts two 4-D vectors.

Syntax

D3DXVECTOR4 *D3DXVec4Subtract(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR4 *pV1,
    CONST D3DXVECTOR4 *pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.

Return Value

Pointer to a D3DXVECTOR4 structure that is the difference of two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Subtract function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXVec3Add, D3DXVec3Scale


D3DXVec4Transform Function

Transforms a 4-D vector by a given matrix.

Syntax

D3DXVECTOR4 *WINAPI D3DXVec4Transform(

    D3DXVECTOR4 *pOut,
    CONST D3DXVECTOR4 *pV,
    CONST D3DXMATRIX *pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR4 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Value

Pointer to a D3DXVECTOR4 structure that is the transformed 4-D vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Transform function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXVec4TransformArray Function

Transforms an array (x, y, 0, 1) by a given matrix.

Syntax

D3DXVECTOR4 *WINAPI D3DXVec4TransformArray(

    D3DXVECTOR4 *pOut,
    UINT OutStride,
    CONST D3DXVECTOR4* pV,
    UINT VStride,
    CONST D3DXMATRIX* pM,
    UINT n
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 array that is the result of the operation.
OutStride
[in] Stride between vectors in the output data stream.
pV
[in] Pointer to the source D3DXVECTOR4 array.
VStride
[in] Stride between vectors in the input data stream.
pM
[in] Pointer to the source D3DXMATRIX structure.
n
[in] Number of elements in the array.

Return Value

Pointer to a D3DXVECTOR4 structure that is the transformed array.

Remarks

This function transforms the array pV (x, y, 0, 1) by the matrix pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4TransformArray function can be used as a parameter for another function.

Function Information

Header | d3dx9math.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


Mesh Functions
Microsoft DirectX 9.0 SDK Update (October 2004)

Mesh Functions

D3DX supplies the following mesh functions.

Functions

  • D3DXBoxBoundProbe
  • D3DXCleanMesh
  • D3DXComputeBoundingBox
  • D3DXComputeBoundingSphere
  • D3DXComputeNormals
  • D3DXComputeTangent
  • D3DXConcatenateMeshes
  • D3DXConvertMeshSubsetToSingleStrip
  • D3DXConvertMeshSubsetToStrips
  • D3DXCreateMesh
  • D3DXCreateMeshFVF
  • D3DXCreateNPatchMesh
  • D3DXCreatePatchMesh
  • D3DXCreatePMeshFromStream
  • D3DXCreateSkinInfo
  • D3DXCreateSkinInfoFromBlendedMesh
  • D3DXCreateSkinInfoFVF
  • D3DXCreateSPMesh
  • D3DXDeclaratorFromFVF
  • D3DXFVFFromDeclarator
  • D3DXGenerateOutputDecl
  • D3DXGeneratePMesh
  • D3DXGetDeclLength
  • D3DXGetDeclVertexSize
  • D3DXIntersect
  • D3DXIntersectSubset
  • D3DXIntersectTri
  • D3DXLoadMeshFromX
  • D3DXLoadMeshFromXInMemory
  • D3DXLoadMeshFromXof
  • D3DXLoadMeshFromXResource
  • D3DXLoadPatchMeshFromXof
  • D3DXLoadSkinMeshFromXof
  • D3DXOptimizeFaces
  • D3DXOptimizeVertices
  • D3DXRectPatchSize
  • D3DXSaveMeshToX
  • D3DXSimplifyMesh
  • D3DXSphereBoundProbe
  • D3DXSplitMesh
  • D3DXTessellateNPatches
  • D3DXTessellateRectPatch
  • D3DXTessellateTriPatch
  • D3DXTriPatchSize
  • D3DXValidMesh
  • D3DXValidPatchMesh
  • D3DXWeldVertices

Related Topics

  • D3DXCreateTextureGutterHelper


D3DXBoxBoundProbe Function

Determines whether a ray intersects the volume of a box's bounding box.

Syntax

BOOL WINAPI D3DXBoxBoundProbe(

    const D3DXVECTOR3 *pMin,
    const D3DXVECTOR3 *pMax,
    const D3DXVECTOR3 *pRayPosition,
    const D3DXVECTOR3 *pRayDirection
);

Parameters

pMin
[in] Pointer to a D3DXVECTOR3 structure, describing the lower-left corner of the bounding box. See Remarks.
pMax
[in] Pointer to a D3DXVECTOR3 structure, describing the upper-right corner of the bounding box. See Remarks.
pRayPosition
[in] Pointer to a D3DXVECTOR3 structure, specifying the origin coordinate of the ray.
pRayDirection
[in] Pointer to a D3DXVECTOR3 structure, specifying the direction of the ray. This vector should not be (0,0,0) but does not need to be normalized.

Return Value

Returns TRUE if the ray intersects the volume of the box's bounding box. Otherwise, returns FALSE.

Remarks

D3DXBoxBoundProbe determines if the ray intersects the volume of the box's bounding box, not just the surface of the box.

The values passed to D3DXBoxBoundProbe are xmin, xmax, ymin, ymax, zmin, and zmax. Thus, the following defines the corners of the bounding box.

xmax, ymax, zmax
xmax, ymax, zmin
xmax, ymin, zmax
xmax, ymin, zmin
xmin, ymax, zmax
xmin, ymax, zmin
xmin, ymin, zmax
xmin, ymin, zmin

The depth of the bounding box in the z direction is zmax - zmin, in the y direction is ymax - ymin, and in the x direction is xmax - xmin. For example, with the following minimum and maximum vectors, min (-1, -1, -1) and max (1, 1, 1), the bounding box is defined in the following manner.

 1,  1,  1
 1,  1, -1
 1, -1,  1
 1, -1, -1
-1,  1,  1
-1,  1, -1
-1, -1,  1
-1, -1, -1

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXComputeBoundingBox


D3DXCleanMesh Function

Cleans a mesh, preparing it for simplification.

Syntax

HRESULT WINAPI D3DXCleanMesh(

    D3DXCLEANTYPE CleanType,
    LPD3DXMESH pMeshIn,
    const DWORD *pAdjacencyIn,
    LPD3DXMESH *ppMeshOut,
    DWORD *pAdjacencyOut,
    LPD3DXBUFFER *ppErrorsAndWarnings
);

Parameters

CleanType
[in] Vertex operations to perform in preparation for mesh cleaning. See D3DXCLEANTYPE.
pMeshIn
[in] Pointer to an ID3DXMesh interface, representing the mesh to be cleaned.
pAdjacencyIn
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh to be cleaned.
ppMeshOut
[out] Address of a pointer to an ID3DXMesh interface, representing the returned cleaned mesh. The same mesh is returned that was passed in if no cleaning was necessary.
pAdjacencyOut
[out] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the output mesh.
ppErrorsAndWarnings
[out] Returns a buffer containing a string of errors and warnings, which explain the problems found in the mesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

This method cleans the mesh by adding another vertex where two fans of triangles share the same vertex.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXComputeBoundingBox Function

Computes a coordinate-axis oriented bounding box.

Syntax

HRESULT WINAPI D3DXComputeBoundingBox(

    const D3DXVECTOR3 *pFirstPosition,
    DWORD NumVertices,
    DWORD dwStride,
    D3DXVECTOR3 *pMin,
    D3DXVECTOR3 *pMax
);

Parameters

pFirstPosition
[in] Pointer to the first position.
NumVertices
[in] Number of vertices.
dwStride
[in] Count or number of bytes between vertices.
pMin
[out] Pointer to a D3DXVECTOR3 structure, describing the returned lower-left corner of the bounding box. See Remarks.
pMax
[out] Pointer to a D3DXVECTOR3 structure, describing the returned upper-right corner of the bounding box. See Remarks.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXComputeBoundingSphere Function

Computes a bounding sphere for the mesh.

Syntax

HRESULT WINAPI D3DXComputeBoundingSphere(

    const D3DXVECTOR3 *pFirstPosition,
    DWORD NumVertices,
    DWORD dwStride,
    D3DXVECTOR3 *pCenter,
    FLOAT *pRadius
);

Parameters

pFirstPosition
[in] Pointer to first position.
NumVertices
[in] Number of vertices.
dwStride
[in] Number of bytes between position vectors. Use D3DXGetFVFVertexSize to get the stride for a flexible vertex format (FVF).
pCenter
[out] D3DXVECTOR3 structure, defining the coordinate center of the returned bounding sphere.
pRadius
[out] Radius of the returned bounding sphere.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXComputeNormals Function

Computes normals for each vertex in a mesh.

Syntax

HRESULT WINAPI D3DXComputeNormals(

    LPD3DXBASEMESH pMesh,
    const DWORD *pAdjacency
);

Parameters

pMesh
[in, out] Pointer to an ID3DXBaseMesh interface, representing the normalized mesh object.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the created progressive mesh. This parameter is optional and should be set to NULL if it is unused.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The input mesh must have the D3DFVF_NORMAL flag specified in its flexible vertex format (FVF).

A normal for a vertex is generated by averaging the normals of all faces that share that vertex.

If adjacency is provided, replicated vertices are ignored and "smoothed" over. If adjacency is not provided, replicated vertices will have normals averaged in from only the faces explicitly referencing them.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXComputeTangent Function

Computes the tangent vectors for the texture coordinates given in the texture stage.

Syntax

HRESULT WINAPI D3DXComputeTangent(

    LPD3DXMESH Mesh,
    DWORD TexStageIndex,
    DWORD TangentIndex,
    DWORD BinormIndex,
    DWORD Wrap,
    const DWORD *pAdjacency
);

Parameters

Mesh
[in] Pointer to an ID3DXMesh interface that represent the input mesh.
TexStageIndex
[in] Index that represents the texture stage.
TangentIndex
[in] Index that provides the usage index for the tangent data. The vertex declaration implies the usage; this index modifies the usage with the usage index. For more information about a vertex declaration, see Vertex Declaration.
BinormIndex
[in] Index that provides the usage index for the binormal data. The vertex declaration implies the usage; this index modifies the usage with the usage index. For more information about a vertex declaration, see Vertex Declaration.
Wrap
[in] Set this value to 0 for no wrapping, or to 1 for wrapping in the U and V directions.
pAdjacency
[in] Pointer to an array of three DWORDs per face to be filled with adjacent face indices. The number of bytes in this array must be at least ((3 * ID3DXBaseMesh::GetNumFaces) * sizeof(DWORD)).

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

If the mesh vertex declaration specifies tangent or binormal fields, D3DXComputeTangent will update any user-supplied tangent or binormal data. Alternatively, set TangentIndex to D3DX_DEFAULT to not update the user-supplied tangent data, or set BinormIndex to D3DX_DEFAULT to not update the user-supplied binormal data. TexStageIndex cannot be set to D3DX_DEFAULT.

D3DXComputeTangent depends on the mesh vertex declaration containing either the binormal field (BinormIndex), the tangent field (TangentIndex), or both. If both are missing, this function will fail.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXConcatenateMeshes Function

Concatenates a group of meshes into one common mesh. This method can optionally apply a matrix transformation to each input mesh and its texture coordinates.

Syntax

HRESULT WINAPI D3DXConcatenateMeshes(

    LPD3DXMESH *ppMeshes,
    UINT NumMeshes,
    DWORD Options,
    const D3DXMATRIX *pGeomXForms,
    const D3DXMATRIX *pTextureXForms,
    const D3DVERTEXELEMENT9 *pDecl,
    LPDIRECT3DDEVICE9 pD3DDevice,
    LPD3DXMESH *ppMeshOut
);

Parameters

ppMeshes
[in] Array of pointers to input D3DXMATRIX meshes to concatenate. These meshes can store precomputed radiance transfer (PRT) vectors.
NumMeshes
[in] Number of input meshes to concatenate.
Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the output mesh. Equivalent to the Options parameter of the D3DXCreateMesh function.
pGeomXForms
[in] Optional pointer to a D3DXMATRIX transformation matrix to apply to each submesh. May be NULL.
pTextureXForms
[in] Optional pointer to a D3DXMATRIX transformation matrix to apply to the (u, v) coordinates of each submesh. May be NULL.
pDecl
[in] Optional pointer to a D3DVERTEXELEMENT9 vertex declaration to use for merging mesh data. May be NULL.
pD3DDevice
[in] Pointer to a IDirect3DDevice9 device that is used to create the new mesh.
ppMeshOut
[in, out] Address of a pointer to the output ID3DXMesh mesh object.

Return Value

If the function succeeds, the return value is S_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

If no vertex declaration is given as part of the Options mesh creation parameter, the method will generate a union of all of the vertex declarations of the submeshes, promoting channels and types if necessary. The method will create an attribute table from attribute tables of the input meshes. To ensure creation of an attribute table, call ID3DXPMesh::Optimize with Flags set to D3DXMESHOPT_COMPACT and D3DXMESHOPT_ATTRSORT.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXConvertMeshSubsetToSingleStrip Function

Converts the specified mesh subset into a single triangle strip.

Syntax

HRESULT WINAPI D3DXConvertMeshSubsetToSingleStrip(

    LPD3DXBASEMESH MeshIn,
    DWORD AttribId,
    DWORD IBOptions,
    LPDIRECT3DINDEXBUFFER9 *ppIndexBuffer,
    DWORD *pNumIndices
);

Parameters

MeshIn
[in] Pointer to an ID3DXBaseMesh interface, representing the mesh to convert to a strip.
AttribId
[in] Attribute ID of the mesh subset to convert to strips.
IBOptions
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying options for creating the index buffer.
ppIndexBuffer
[out] Pointer to an IDirect3DIndexBuffer9 interface, representing the index buffer containing the strip.
pNumIndices
[out] Number of indices in the buffer returned in the ppIndexBuffer parameter.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

Before running this function, call ID3DXMesh::Optimize or D3DXOptimizeFaces.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXConvertMeshSubsetToStrips Function

Convert the specified mesh subset into a series of strips.

Syntax

HRESULT WINAPI D3DXConvertMeshSubsetToStrips(

    LPD3DXBASEMESH MeshIn,
    DWORD AttribId,
    DWORD IBOptions,
    LPDIRECT3DINDEXBUFFER9 *ppIndexBuffer,
    DWORD *pNumIndices,
    LPD3DXBUFFER *ppStripLengths,
    DWORD *pNumStrips
);

Parameters

MeshIn
[in] Pointer to an ID3DXBaseMesh interface, representing the mesh to convert to a strip.
AttribId
[in] Attribute ID of the mesh subset to convert to strips.
IBOptions
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying options for creating the index buffer.
ppIndexBuffer
[out] Pointer to an IDirect3DIndexBuffer9 interface, representing index buffer containing the strip.
pNumIndices
[out] Number of indices in the buffer returned in the ppIndexBuffer parameter.
ppStripLengths
[out] Buffer containing an array of one DWORD per strip, that specifies the number of triangles in the that strip.
pNumStrips
[out] Number of individual strips in the index buffer and corresponding strip length array.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

Before running this function, call ID3DXMesh::Optimize or D3DXOptimizeFaces.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXCreateMesh Function

Creates a mesh object using a declarator.

Syntax

HRESULT WINAPI D3DXCreateMesh(

    DWORD NumFaces,
    DWORD NumVertices,
    DWORD Options,
    const LPD3DVERTEXELEMENT9 *pDeclaration,
    LPDIRECT3DDEVICE9 pD3DDevice,
    LPD3DXMESH *ppMesh
);

Parameters

NumFaces
[in] Number of faces for the mesh. The valid range for this number is greater than 0, and one less than the maximum DWORD (typically 65534), because the last index is reserved.
NumVertices
[in] Number of vertices for the mesh. This parameter must be greater than 0.
Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying options for the mesh.
pDeclaration
[in] Array of D3DVERTEXELEMENT9 elements, describing the vertex format for the returned mesh. This parameter must map directly to a flexible vertex format (FVF).
pD3DDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object to be associated with the mesh.
ppMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the created mesh object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXDeclaratorFromFVF


D3DXCreateMeshFVF Function

Creates a mesh object using a flexible vertex format (FVF) code.

Syntax

HRESULT WINAPI D3DXCreateMeshFVF(

    DWORD NumFaces,
    DWORD NumVertices,
    DWORD Options,
    DWORD FVF,
    LPDIRECT3DDEVICE9 pD3DDevice,
    LPD3DXMESH *ppMesh
);

Parameters

NumFaces
[in] Number of faces for the mesh. The valid range for this number is greater than 0, and one less than the max DWORD value, typically 232-1, because the last index is reserved.
NumVertices
[in] Number of vertices for the mesh. This parameter must be greater than 0.
Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
FVF
[in] Combination of D3DFVF that describes the vertex format for the returned mesh. This function does not support D3DFVF_XYZRHW.
pD3DDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object to be associated with the mesh.
ppMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the created mesh object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXFVFFromDeclarator


D3DXCreateNPatchMesh Function

Creates an N-patch mesh from a triangle mesh.

Syntax

HRESULT WINAPI D3DXCreateNPatchMesh(

    LPD3DXMESH pMeshSysMem,
    LPD3DXPATCHMESH *pPatchMesh
);

Parameters

pMeshSysMem
[in] Address of a pointer to an ID3DXMesh interface that represents the triangle mesh object.
pPatchMesh
[in, out] Address of a pointer to an ID3DXPatchMesh interface that represents the created patch mesh object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXCreatePatchMesh Function

Creates a mesh from a control-patch mesh.

Syntax

HRESULT WINAPI D3DXCreatePatchMesh(

    const D3DXPATCHINFO *pInfo,
    DWORD dwNumPatches,
    DWORD dwNumVertices,
    DWORD dwOptions,
    CONST D3DVERTEXELEMENT9 *pDecl,
    LPDIRECT3DDEVICE9 pD3DDevice,
    LPD3DXPATCHMESH *pPatchMesh
);

Parameters

pInfo
[in] Patch information structure. For more information, see D3DXPATCHINFO.
dwNumPatches
[in] Number of patches.
dwNumVertices
[in] Number of control vertices in the patch.
dwOptions
[in] Unused. Reserved for later use.
pDecl
[in] Array of D3DVERTEXELEMENT9 elements, describing the vertex format for the returned mesh.
pD3DDevice
[in] Pointer the device that creates the patch mesh. See IDirect3DDevice9.
pPatchMesh
[out] Pointer to the ID3DXPatchMesh object that is created.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

This method takes an input patch mesh and converts it to a tessellated mesh. Patch meshes use 16-bit index buffers. Therefore, indices to ID3DXPatchMesh::LockIndexBuffer are 16 bits.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXPATCHINFO


D3DXCreatePMeshFromStream Function

Creates a progressive mesh from a stream object.

Syntax

HRESULT WINAPI D3DXCreatePMeshFromStream(

    IStream *pStream,
    DWORD Options,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXBUFFER *ppMaterials,
    LPD3DXBUFFER *ppEffectInstances,
    DWORD *pNumMaterials,
    LPD3DXPMESH *ppPMesh
);

Parameters

pStream
[in] Pointer to an IStream interface, representing the stream object from which to create the progressive mesh. The data in this stream was generated with the ID3DXPMesh::Save method.
Options
[in] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object to be associated with the progressive mesh.
ppMaterials
[out] Address of a pointer to an ID3DXBuffer interface. When this method returns, this parameter is filled with an array of D3DXMATERIAL structures, containing information saved in the stream object.
ppEffectInstances
[out] Pointer to a buffer containing an array of effect instances, one per attribute group in the returned mesh. An effect instance is a particular instance of state information used to initialize an effect. For more information about accessing the buffer, see ID3DXBuffer.
pNumMaterials
[out] Pointer to the number of D3DXMATERIAL structures in the ppMaterialsarray, when the method returns.
ppPMesh
[out] Address of a pointer to an ID3DXPMesh interface, representing the created progressive mesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

For more information about the IStream interface, see the Microsoft Platform Software Development Kit (SDK).

For mesh files that do not contain effect instance information, default effect instances will be generated from the material information in the .x file. A default effect instance will have default values that correspond to the members of the D3DMATERIAL9 structure.

The default texture name is also filled in, but is handled differently. The name will be Texture0@Name, which corresponds to an effect variable by the name of "Texture0" with an annotation called "Name." This will contain the string file name for the texture.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

ID3DXPMesh::Save


D3DXCreateSkinInfo Function

Creates an empty skin mesh object using a declarator.

Syntax

HRESULT WINAPI D3DXCreateSkinInfo(

    DWORD NumVertices,
    const D3DVERTEXELEMENT9 *pDeclaration,
    DWORD NumBones,
    LPD3DXSKININFO *ppSkinInfo
);

Parameters

NumVertices
[in] Number of vertices for the skin mesh.
pDeclaration
[in] Array of D3DVERTEXELEMENT9 elements, describing the vertex format for the returned mesh.
NumBones
[in] Number of bones for the skin mesh.
ppSkinInfo
[out, retval] Address of a pointer to an ID3DXSkinInfo interface, representing the created skin mesh object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be E_OUTOFMEMORY.

Remarks

Use ID3DXSkinInfo::SetBoneInfluence to populate the empty skin mesh object returned by this method.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

ID3DXSkinInfo::SetBoneInfluence


D3DXCreateSkinInfoFromBlendedMesh Function

Creates a skin mesh from another mesh.

Syntax

HRESULT WINAPI D3DXCreateSkinInfoFromBlendedMesh(

    LPD3DXBASEMESH pMesh,
    DWORD NumBones,
    const D3DXBONECOMBINATION *pBoneCombinationTable,
    LPD3DXSKININFO *ppSkinInfo
);

Parameters

pMesh
[in] Pointer to an ID3DXBaseMesh object, the mesh from which to create the skin mesh.
NumBones
[in] The length of the array attached to the BoneId. See D3DXBONECOMBINATION.
pBoneCombinationTable
[in] Pointer to an array of bone combinations. See D3DXBONECOMBINATION.
ppSkinInfo
[out, retval] Address of a pointer to an ID3DXSkinInfo interface representing the created skin mesh object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be the following:

E_OUTOFMEMORY Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXCreateSkinInfoFVF Function

Creates an empty skin mesh object using a flexible vertex format (FVF) code.

Syntax

HRESULT WINAPI D3DXCreateSkinInfoFVF(

    DWORD NumVertices,
    DWORD FVF,
    DWORD NumBones,
    LPD3DXSKININFO *ppSkinInfo
);

Parameters

NumVertices
[in] Number of vertices for the skin mesh.
FVF
[in] Combination of D3DFVF that describes the vertex format for the returned skin mesh.
NumBones
[in] Number of bones for the skin mesh.
ppSkinInfo
[out, retval] Address of a pointer to an ID3DXSkinInfo interface, representing the created skin information object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

Use ID3DXSkinInfo::SetBoneInfluence to populate the empty skin mesh object returned by this method.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

ID3DXSkinInfo::SetBoneInfluence


D3DXCreateSPMesh Function

Creates a simplification mesh.

Syntax

HRESULT WINAPI D3DXCreateSPMesh(

    LPD3DXMESH pMesh,
    const DWORD *pAdjacency,
    const D3DXATTRIBUTEWEIGHTS *pVertexAttributeWeights,
    const FLOAT *pVertexWeights,
    LPD3DXSPMESH *ppSMesh
);

Parameters

pMesh
[in] Pointer to an ID3DXMesh interface, representing the mesh to simplify.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the created simplification mesh.
pVertexAttributeWeights
[in] Pointer to a D3DXATTRIBUTEWEIGHTS structure, containing the weight for each vertex component. If this parameter is set to NULL, a default structure is used. See Remarks.
pVertexWeights
[in] Pointer to an array of vertex weights. If this parameter is set to NULL, all vertex weights are set to 1.0. Note that the higher the vertex weight for a given vertex, the less likely it is to be simplified away.
ppSMesh
[out] Address of a pointer to an ID3DXSPMesh interface, representing the created simplification mesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DXERR_CANNOTATTRSORT | Attribute sort (D3DXMESHOPT_ATTRSORT) is not supported as an optimization technique.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

A simplification mesh is used to simplify a mesh to a lower number of triangles and faces.

If pVertexAttributeWeights is set to NULL, the following values are assigned to the default D3DXATTRIBUTEWEIGHTS structure.

D3DXATTRIBUTEWEIGHTS AttributeWeights;
AttributeWeights.Position  = 1.0;
AttributeWeights.Boundary =  1.0;
AttributeWeights.Normal   =  1.0;
AttributeWeights.Diffuse  =  0.0;
AttributeWeights.Specular =  0.0;
AttributeWeights.Tex[8]   =  {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};

This default structure is what most applications should use because it considers only geometric and normal adjustment. Only in special cases will the other member fields need to be modified.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXDeclaratorFromFVF Function

Returns a declarator from a flexible vertex format (FVF) code.

Syntax

HRESULT WINAPI D3DXDeclaratorFromFVF(

    DWORD FVF,
    D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

FVF
[in] Combination of D3DFVF that describes the FVF from which to generate the returned declarator array.
Declaration
[in, out] An array of D3DVERTEXELEMENT9 elements describing the vertex format of the mesh vertices. The upper limit of this declarator array is MAX_FVF_DECL_SIZE.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be D3DXERR_INVALIDMESH.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXFVFFromDeclarator


D3DXFVFFromDeclarator Function

Returns a flexible vertex format (FVF) code from a declarator.

Syntax

HRESULT WINAPI D3DXFVFFromDeclarator(

    const LPD3DVERTEXELEMENT9 *pDeclaration,
    DWORD *pFVF
);

Parameters

pDeclaration
[in] Array of D3DVERTEXELEMENT9 elements, describing the FVF code.
pFVF
[out] Pointer to a DWORD value, representing the returned combination of D3DFVF that describes the vertex format returned from the declarator.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This function will fail for any declarator that does not map directly to an FVF.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXDeclaratorFromFVF


D3DXGenerateOutputDecl Function

Generates an output vertex declaration from the input declaration. The output declaration is intended for use by the mesh tessellation functions.

Syntax

HRESULT WINAPI D3DXGenerateOutputDecl(

    D3DVERTEXELEMENT9 *pOutput,
    const D3DVERTEXELEMENT9 *pInput
);

Parameters

pOutput
[out] Pointer to the output vertex declaration. See D3DVERTEXELEMENT9.
pInput
[in] Pointer to the input vertex declaration. See D3DVERTEXELEMENT9.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXGeneratePMesh Function

Generates a progressive mesh.

Syntax

HRESULT WINAPI D3DXGeneratePMesh(

    LPD3DXMESH pMesh,
    const DWORD *pAdjacency,
    const D3DXATTRIBUTEWEIGHTS *pVertexAttributeWeights,
    const FLOAT *pVertexWeights,
    DWORD MinValue,
    DWORD Options,
    LPD3DXPMESH *ppPMesh
);

Parameters

pMesh
[in] Pointer to an ID3DXMesh interface, representing the source mesh.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the created progressive mesh.
pVertexAttributeWeights
[in] Pointer to a D3DXATTRIBUTEWEIGHTS structure, containing the weight for each vertex component. If this parameter is set to NULL, a default structure is used. See Remarks.
pVertexWeights
[in] Pointer to an array of vertex weights. If this parameter is set to NULL, all vertex weights are set to 1.0. Note that the higher the vertex weight for a given vertex, the less likely it is to be simplified away.
MinValue
[in] Number of vertices or faces, depending on the flag set in the Options parameter, by which to simplify the source mesh.
Options
[in] Specifies simplification options for the mesh. One flag from the D3DXMESHSIMP enumeration can be set.
ppPMesh
[out] Address of a pointer to an ID3DXPMesh interface, representing the created progressive mesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DXERR_CANNOTATTRSORT | Attribute sort (D3DXMESHOPT_ATTRSORT) is not supported as an optimization technique.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

This function generates a mesh where the level of detail (LOD) can be adjusted from the current value to the MinValue.

If the simplification process cannot reduce the mesh to MinValue, the call still succeeds because MinValue is a desired minimum, not an absolute minimum.

If pVertexAttributeWeights is set to NULL, the following values are assigned to the default D3DXATTRIBUTEWEIGHTS structure.

D3DXATTRIBUTEWEIGHTS AttributeWeights;

AttributeWeights.Position  = 1.0;
AttributeWeights.Boundary =  1.0;
AttributeWeights.Normal   =  1.0;
AttributeWeights.Diffuse  =  0.0;
AttributeWeights.Specular =  0.0;
AttributeWeights.Tex[8]   =  {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};

This default structure is what most applications should use because it considers only geometric and normal adjustment. Only in special cases will the other member fields need to be modified.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXGetDeclLength Function

Returns the number of elements in the vertex declaration.

Syntax

UINT WINAPI D3DXGetDeclLength(

    const D3DVERTEXELEMENT9 *pDecl
);

Parameters

pDecl
[in] A pointer to the vertex declaration. See D3DVERTEXELEMENT9.

Return Value

The number of elements in the vertex declaration.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXGetDeclVertexSize Function

Returns the size of a vertex for a flexible vertex format (FVF).

Syntax

UINT WINAPI D3DXGetDeclVertexSize(

    CONST D3DVERTEXELEMENT9 *pDecl,
    DWORD Stream
);

Parameters

pDecl
[in] A pointer to the vertex declaration. See D3DVERTEXELEMENT9.
Stream
[in] The zero-based stream index.

Return Value

The vertex declaration size, in bytes.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXIntersect Function

Determines if a ray intersects with a mesh.

Syntax

HRESULT WINAPI D3DXIntersect(

    LPD3DXBASEMESH pMesh,
    const D3DXVECTOR3 *pRayPos,
    const D3DXVECTOR3 *pRayDir,
    BOOL *pHit,
    DWORD *pFaceIndex,
    FLOAT *pU,
    FLOAT *pV,
    FLOAT *pDist,
    LPD3DXBUFFER *ppAllHits,
    DWORD *pCountOfHits
);

Parameters

pMesh
[in] Pointer to an ID3DXBaseMesh interface, representing the mesh to be tested.
pRayPos
[in] Pointer to a D3DXVECTOR3 structure, specifying the point where the ray begins.
pRayDir
[in] Pointer to a D3DXVECTOR3 structure, specifying the direction of the ray.
pHit
[out] Pointer to a BOOL. If the ray intersects a triangular face on the mesh, this value will be set to TRUE. Otherwise, this value is set to FALSE.
pFaceIndex
[out] Pointer to an index value of the face closest to the ray origin, if pHit is TRUE.
pU
[out] Pointer to a barycentric hit coordinate, U.
pV
[out] Pointer to a barycentric hit coordinate, V.
pDist
[out] Pointer to a ray intersection parameter distance.
ppAllHits
[out] Pointer to an ID3DXBuffer object, containing an array of D3DXINTERSECTINFO structures.
pCountOfHits
[out] Pointer to a DWORD that contains the number of entries in the ppAllHits array.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be E_OUTOFMEMORY.

Remarks

The D3DXIntersect function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + U(V2 - V1) + V(V3 - V1).

Any point in the plane V1V2V3 can be represented by the barycentric coordinate (U,V). The parameter U controls how much V2 gets weighted into the result, and the parameter V controls how much V3 gets weighted into the result. Lastly, the value of [1 - (U + V)] controls how much V1 gets weighted into the result.

Barycentric coordinates are a form of general coordinates. In this context, using barycentric coordinates represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for barycentric coordinates.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXIntersectSubset Function

Intersects the specified ray with the given mesh subset. This provides similar functionality to D3DXIntersect.

Syntax

HRESULT WINAPI D3DXIntersectSubset(

    LPD3DXBASEMESH pMesh,
    DWORD AttribId,
    const D3DXVECTOR3 *pRayPos,
    const D3DXVECTOR3 *pRayDir,
    BOOL *pHit,
    DWORD *pFaceIndex,
    FLOAT *pU,
    FLOAT *pV,
    FLOAT *pDist,
    LPD3DXBUFFER *ppAllHits,
    DWORD *pCountOfHits
);

Parameters

pMesh
[in] Pointer to an ID3DXBaseMesh interface, representing the mesh to be tested. The mesh must be attribute sorted.
AttribId
[in] Attribute identifier of the subset to intersect with.
pRayPos
[in] Pointer to a D3DXVECTOR3 structure, specifying the point where the ray begins.
pRayDir
[in] Pointer to a D3DXVECTOR3 structure, specifying the direction of the ray.
pHit
[out] Pointer to a BOOL. If the ray intersects a triangular face on the mesh, this value will be set to TRUE. Otherwise, this value is set to FALSE.
pFaceIndex
[out] Pointer to an index value of the face closest to the ray origin, if pHit is TRUE.
pU
[out] Pointer to a barycentric hit coordinate, U.
pV
[out] Pointer to a barycentric hit coordinate, V.
pDist
[out] Pointer to a ray intersection parameter distance.
ppAllHits
[out] Array of D3DXINTERSECTINFO structures, representing all hits, not just closest hits.
pCountOfHits
[out] Number of elements in the array returned from ppAllHits.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be the following value.

E_OUTOFMEMORY Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The D3DXIntersectSubset function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + U(V2 - V1) + V(V3 - V1).

Any point in the plane V1V2V3 can be represented by the barycentric coordinate (U,V). The parameter U controls how much V2 gets weighted into the result and the parameter V controls how much V3 gets weighted into the result. Lastly, the value of [1 - (U + V)] controls how much V1 gets weighted into the result.

Barycentric coordinates are a form of general coordinates. In this context, using barycentric coordinates represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for barycentric coordinates.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXIntersectTri Function

Computes the intersection of a ray and a triangle.

Syntax

BOOL WINAPI D3DXIntersectTri(

    const D3DXVECTOR3 *p0,
    const D3DXVECTOR3 *p1,
    const D3DXVECTOR3 *p2,
    const D3DXVECTOR3 *pRayPos,
    const D3DXVECTOR3 *pRayDir,
    FLOAT *pU,
    FLOAT *pV,
    FLOAT *pDist
);

Parameters

p0
[in] Pointer to a D3DXVECTOR3 structure, describing the first triangle vertex position.
p1
[in] Pointer to a D3DXVECTOR3 structure, describing the second triangle vertex position.
p2
[in] Pointer to a D3DXVECTOR3 structure, describing the third triangle vertex position.
pRayPos
[in] Pointer to a D3DXVECTOR3 structure, specifying the point where the ray begins.
pRayDir
[in] Pointer to a D3DXVECTOR3 structure, specifying the direction of the ray.
pU
[out] Barycentric hit coordinates, U.
pV
[out] Barycentric hit coordinates, V.
pDist
[out] Ray-intersection parameter distance.

Return Value

Returns TRUE if the ray intersects the area of the triangle. Otherwise, returns FALSE.

Remarks

The D3DXIntersect function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + U(V2 - V1) + V(V3 - V1).

Any point in the plane V1V2V3 can be represented by the barycentric coordinate (U,V). The parameter U controls how much V2 gets weighted into the result, and the parameter V controls how much V3 gets weighted into the result. Lastly, the value of [1 - (U + V)] controls how much V1 gets weighted into the result.

Barycentric coordinates are a form of general coordinates. In this context, using barycentric coordinates represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for barycentric coordinates.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXLoadMeshFromX Function

Loads a mesh from a Microsoft DirectX .x file.

Syntax

HRESULT WINAPI D3DXLoadMeshFromX(

    LPCTSTR pFilename,
    DWORD Options,
    LPDIRECT3DDEVICE9 pD3DDevice,
    LPD3DXBUFFER *ppAdjacency,
    LPD3DXBUFFER *ppMaterials,
    LPD3DXBUFFER *ppEffectInstances,
    DWORD *pNumMaterials,
    LPD3DXMESH *ppMesh
);

Parameters

pFilename
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Options
[in] Combination of one or more flags from the D3DXMESH enumeration, which specifies creation options for the mesh.
pD3DDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object associated with the mesh.
ppAdjacency
[out] Pointer to a buffer that contains adjacency data. The adjacency data contains an array of three DWORDs per face that specify the three neighbors for each face in the mesh. For more information about accessing the buffer, see ID3DXBuffer.
ppMaterials
[out] Pointer to a buffer containing materials data. The buffer contains an array of D3DXMATERIAL structures, containing information from the DirectX file. For more information about accessing the buffer, see ID3DXBuffer.
ppEffectInstances
[out] Pointer to a buffer containing an array of effect instances, one per attribute group in the returned mesh. An effect instance is a particular instance of state information used to initialize an effect. See D3DXEFFECTINSTANCE. For more information about accessing the buffer, see ID3DXBuffer.
pNumMaterials
[out] Pointer to the number of D3DXMATERIAL structures in the ppMaterials array, when the method returns.
ppMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the loaded mesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXLoadMeshFromXW. Otherwise, the function call resolves to D3DXLoadMeshFromXA because ANSI strings are being used.

All the meshes in the file will be collapsed into one output mesh. If the file contains a frame hierarchy, all the transformations will be applied to the mesh.

For mesh files that do not contain effect instance information, default effect instances will be generated from the material information in the .x file. A default effect instance will have default values that correspond to the members of the D3DMATERIAL9 structure.

The default texture name is also filled in, but is handled differently. The name will be Texture0@Name, which corresponds to an effect variable by the name of "Texture0" with an annotation called "Name." This will contain the string file name for the texture.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXEFFECTDEFAULT, D3DXEFFECTINSTANCE


D3DXLoadMeshFromXInMemory Function

Loads a mesh from memory.

Syntax

HRESULT WINAPI D3DXLoadMeshFromXInMemory(

    LPCVOID Memory,
    DWORD SizeOfMemory,
    DWORD Options,
    LPDIRECT3DDEVICE9 pD3DDevice,
    LPD3DXBUFFER *ppAdjacency,
    LPD3DXBUFFER *ppMaterials,
    LPD3DXBUFFER *ppEffectInstances,
    DWORD *pNumMaterials,
    LPD3DXMESH *ppMesh
);

Parameters

Memory
[in] Pointer to the memory buffer which contains the mesh data.
SizeOfMemory
[in] Size of the file in memory, in bytes.
Options
[out] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
pD3DDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object associated with the mesh.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh.
ppMaterials
[out] Address of a pointer to an ID3DXBuffer interface. When this method returns, this parameter is filled with an array of D3DXMATERIAL structures, containing information saved in the Microsoft DirectX file.
ppEffectInstances
[out] Pointer to a buffer containing an array of effect instances, one per attribute group in the returned mesh. An effect instance is a particular instance of state information used to initialize an effect. See D3DXEFFECTINSTANCE. For more information about accessing the buffer, see ID3DXBuffer.
pNumMaterials
[out] Pointer to the number of D3DXMATERIAL structures in the ppMaterials array, when the method returns.
ppMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the loaded mesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

All the meshes in the file will be collapsed into one output mesh. If the file contains a frame hierarchy, all the transformations will be applied to the mesh.

For mesh files that do not contain effect instance information, default effect instances will be generated from the material information in the .x file. A default effect instance will have default values that correspond to the members of the D3DMATERIAL9 structure.

The default texture name is also filled in, but is handled differently. The name will be Texture0@Name, which corresponds to an effect variable by the name of "Texture0" with an annotation called "Name." This will contain the string file name for the texture.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXEFFECTDEFAULT, D3DXEFFECTINSTANCE


D3DXLoadMeshFromXof Function

Loads a mesh from an ID3DXFileData object.

Syntax

HRESULT WINAPI D3DXLoadMeshFromXof(

    LPD3DXFILEDATA pxofMesh,
    DWORD Options,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXBUFFER *ppAdjacency,
    LPD3DXBUFFER *ppMaterials,
    LPD3DXBUFFER *ppEffectInstances,
    DWORD *pNumMaterials,
    LPD3DXMESH *ppMesh
);

Parameters

pxofMesh
[in] Pointer to an ID3DXFileData interface, representing the file data object to load.
Options
[out] Combination of one or more flags from the D3DXMESH enumeration, specifying creation options for the mesh.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object associated with the mesh.
ppAdjacency
[out] Pointer to a buffer that contains adjacency data. The adjacency data contains an array of three DWORDs per face that specify the three neighbors for each face in the mesh. For more information about accessing the buffer, see ID3DXBuffer.
ppMaterials
[in, out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of D3DXMATERIAL structures.
ppEffectInstances
[out] Pointer to a buffer containing an array of effect instances, one per attribute group in the returned mesh. An effect instance is a particular instance of state information used to initialize an effect. See D3DXEFFECTINSTANCE. For more information about accessing the buffer, see ID3DXBuffer.
pNumMaterials
[in, out] Pointer to the number of D3DXMATERIAL structures in the ppMaterials array, when the method returns.
ppMesh
[out, retval] Address of a pointer to an ID3DXMesh interface, representing the loaded mesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

For mesh files that do not contain effect instance information, default effect instances will be generated from the material information in the .x file. A default effect instance will have default values that correspond to the members of the D3DMATERIAL9 structure.

The default texture name is also filled in, but is handled differently. The name will be Texture0@Name, which corresponds to an effect variable by the name of "Texture0" with an annotation called "Name." This will contain the string file name for the texture.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXEFFECTDEFAULT, D3DXEFFECTINSTANCE


D3DXLoadMeshFromXResource Function

Loads a mesh from a resource.

Syntax

HRESULT WINAPI D3DXLoadMeshFromXResource(

    HMODULE Module,
    LPCSTR Name,
    LPCSTR Type,
    DWORD Options,
    LPDIRECT3DDEVICE9 pD3DDevice,
    LPD3DXBUFFER *ppAdjacency,
    LPD3DXBUFFER *ppMaterials,
    LPD3DXBUFFER *ppEffectInstances,
    DWORD *pNumMaterials,
    LPD3DXMESH *ppMesh
);

Parameters

Module
[in] Handle to the module where the resource is located, or NULL for the module associated with the image the operating system used to create the current process.
Name
[in] Pointer to a string that specifies the resource to create the mesh from.
Type
[in] Pointer to a string that specifies the resource type.
Options
[in] Combination of one or more flags from the D3DXMESH enumeration that specify creation options for the mesh.
pD3DDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object associated with the mesh.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh.
ppMaterials
[out] Address of a pointer to an ID3DXBuffer interface. When this method returns, this parameter is filled with an array of D3DXMATERIAL structures, containing information saved in the Microsoft DirectX file.
ppEffectInstances
[out] Pointer to a buffer containing an array of effect instances, one per attribute group in the returned mesh. An effect instance is a particular instance of state information used to initialize an effect. See D3DXEFFECTINSTANCE. For more information about accessing the buffer, see ID3DXBuffer.
pNumMaterials
[out] Pointer to the number of D3DXMATERIAL structures in the ppMaterials array, when the method returns.
ppMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the loaded mesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

All the meshes in the file will be collapsed into one output mesh. If the file contains a frame hierarchy, all the transformations will be applied to the mesh.

For mesh files that do not contain effect instance information, default effect instances will be generated from the material information in the .x file. A default effect instance will have default values that correspond to the members of the D3DMATERIAL9 structure.

The default texture name is also filled in, but is handled differently. The name will be Texture0@Name, which corresponds to an effect variable by the name of "Texture0" with an annotation called "Name." This will contain the string file name for the texture.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXEFFECTDEFAULT, D3DXEFFECTINSTANCE


D3DXLoadPatchMeshFromXof Function

Loads a patch mesh from an ID3DXFileData object.

Syntax

HRESULT WINAPI D3DXLoadPatchMeshFromXof(

    LPD3DXFILEDATA pxofMesh,
    DWORD Options,
    LPDIRECT3DDEVICE9 pD3DDevice,
    LPD3DXBUFFER *ppMaterials,
    LPD3DXBUFFER *ppEffectInstances,
    PDWORD pNumMaterials,
    LPD3DXPATCHMESH* ppMesh
);

Parameters

pxofMesh
[in] Pointer to an ID3DXFileData interface, representing the file data object to load.
Options
[in] Combination of one or more D3DXMESH flags, specifying creation options for the mesh.
pD3DDevice
[in] Pointer to the device that the mesh is created from.
ppMaterials
[out] Array of materials contained in the mesh. Each material is indexed by an ID3DXBuffer interface.
ppEffectInstances
[out] Pointer to a buffer containing an array of effect instances, one per attribute group in the returned mesh. An effect instance is a particular instance of state information used to initialize an effect. See D3DXEFFECTINSTANCE. For more information about accessing the buffer, see ID3DXBuffer.
pNumMaterials
[out] Pointer that contains the number of materials in the mesh.
ppMesh
[out, retval] Address of a pointer to an ID3DXPatchMesh interface, representing the loaded mesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

For mesh files that do not contain effect instance information, default effect instances will be generated from the material information in the .x file. A default effect instance will have default values that correspond to the members of the D3DMATERIAL9 structure.

The default texture name is also filled in, but is handled differently. The name will be Texture0@Name, which corresponds to an effect variable by the name of "Texture0" with an annotation called "Name." This will contain the string file name for the texture.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXEFFECTDEFAULT, D3DXEFFECTINSTANCE


D3DXLoadSkinMeshFromXof Function

Loads a skin mesh from a Microsoft DirectX .x file data object.

Syntax

HRESULT WINAPI D3DXLoadSkinMeshFromXof(

    LPD3DXFILEDATA pxofMesh,
    DWORD Options,
    LPDIRECT3DDEVICE9 pD3DDevice,
    LPD3DXBUFFER *ppAdjacency,
    LPD3DXBUFFER *ppMaterials,
    LPD3DXBUFFER *ppEffectInstances,
    DWORD *pMatOut,
    LPD3DXSKININFO *ppSkinInfo,
    LPD3DXMESH *ppMesh
);

Parameters

pxofMesh
[in] Pointer to an ID3DXFileData interface, representing the file data object to load.
Options
[in] Combination of one or more flags, from the D3DXMESH enumeration, specifying creation options for the mesh.
pD3DDevice
[in] Pointer to an IDirect3DDevice9 interface, the device object associated with the mesh.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When this method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh.
ppMaterials
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of D3DXMATERIAL structures.
ppEffectInstances
[out] Pointer to a buffer containing an array of effect instances, one per attribute group in the returned mesh. An effect instance is a particular instance of state information used to initialize an effect. See D3DXEFFECTINSTANCE. For more information about accessing the buffer, see ID3DXBuffer.
pMatOut
[out] Pointer to the number of D3DXMATERIAL structures in the ppMaterials array, when the method returns.
ppSkinInfo
[out] Address of a pointer to an ID3DXSkinInfo interface, which represents the skinning information.
ppMesh
[out] Address of a pointer to an ID3DXMesh interface, which represents the loaded mesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

This method takes a pointer to an internal object in the .x file, enabling you to load the frame hierarchy.

For mesh files that do not contain effect instance information, default effect instances will be generated from the material information in the .x file. A default effect instance will have default values that correspond to the members of the D3DMATERIAL9 structure.

The default texture name is also filled in, but is handled differently. The name will be Texture0@Name, which corresponds to an effect variable by the name of "Texture0" with an annotation called "Name." This will contain the string file name for the texture.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXEFFECTDEFAULT, D3DXEFFECTINSTANCE


D3DXOptimizeFaces Function

Generates an optimized face remapping for a triangle list.

Syntax

HRESULT WINAPI D3DXOptimizeFaces(

    LPCVOID pIndices,
    UINT NumFaces,
    UINT NumVertices,
    BOOL Indices32Bit,
    DWORD *pFaceRemap
);

Parameters

pIndices
[in] Pointer to triangle list indices to use for ordering vertices.
NumFaces
[in] Number of faces in the triangle list.
NumVertices
[in] Number of vertices referenced by the triangle list.
Indices32Bit
[in] Flag indicating index type: TRUE if indices are 32-bit (more than 65535 vertices), FALSE if indices are 16-bit (65535 or fewer vertices).
pFaceRemap
[in, out] Pointer to a destination buffer that will contain the new index for each face. The value stored in pFaceRemap for a given element is the source face location in the new face ordering.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

This function's optimization procedure is functionally equivalent to calling ID3DXMesh::Optimize with the D3DXMESHOPT_DEVICEINDEPENDENT flag, but this function makes more efficient use of vertex caches.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXOptimizeVertices Function

Generates an optimized vertex remapping for a triangle list. This function is commonly used after applying the face remapping generated by D3DXOptimizeFaces.

Syntax

HRESULT WINAPI D3DXOptimizeVertices(

    LPCVOID pIndices,
    UINT NumFaces,
    UINT NumVertices,
    BOOL Indices32Bit,
    DWORD *pVertexRemap
);

Parameters

pIndices
[in] Pointer to triangle list indices to use for ordering vertices.
NumFaces
[in] Number of faces in the triangle list.
NumVertices
[in] Number of vertices referenced by the triangle list.
Indices32Bit
[in] Flag indicating index type: TRUE if indices are 32-bit (more than 65535 vertices), FALSE if indices are 16-bit (65535 or fewer vertices).
pVertexRemap
[in, out] Pointer to a destination buffer that will contain the new index for each vertex. The value stored in pVertexRemap for a given element is the source vertex location in the new vertex ordering.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXRectPatchSize Function

Gets the size of the rectangle patch.

Syntax

HRESULT WINAPI D3DXRectPatchSize(

    const FLOAT *pfNumSegs,
    DWORD *pdwTriangles,
    DWORD *pwdVertices
);

Parameters

pfNumSegs
[in] Number of segments per edge to tessellate.
pdwTriangles
[out] Pointer to a DWORD that contains the number of triangles in the patch.
pwdVertices
[out] Pointer to a DWORD that contains the number of vertices in the patch.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXTessellateRectPatch


D3DXSaveMeshToX Function

Saves a mesh to a .x file.

Syntax

HRESULT WINAPI D3DXSaveMeshToX(

    LPCTSTR pFilename,
    LPD3DXMESH pMesh,
    const DWORD *pAdjacency,
    const D3DXMATERIAL *pMaterials,
    const D3DXEFFECTINSTANCE *pEffectInstances,
    DWORD NumMaterials,
    DWORD Format
);

Parameters

pFilename
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pMesh
[in] Pointer to an ID3DXMesh interface, representing the mesh to save to a .x file.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh. This parameter may be NULL.
pMaterials
[in] Pointer to an array of D3DXMATERIAL structures, containing material information to be saved in the .x file.
pEffectInstances
[in] Pointer to an array of effect instances, one per attribute group in the mesh. This parameter may be NULL. An effect instance is a particular instance of state information used to initialize an effect. For more information, see D3DXEFFECTINSTANCE.
NumMaterials
[in] Number of D3DXMATERIAL structures in the pMaterials array.
Format
[in] Indicates the format to use when saving the .x file. For more information, see Remarks.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be:

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXSaveMeshToXW. Otherwise, the function call resolves to D3DXSaveMeshToXA because ANSI strings are being used.

The default file format is binary; however, if a file is specified as both a binary and a text file, it will be saved as a text file. Regardless of the file format, you may also use the compressed format to reduce the file size.

The following is a typical code example of how to use this function.

ID3DXMesh*    m_pMesh;           // Mesh object to be saved to a .x file
D3DXMATERIAL* m_pMaterials;      // Array of material structs in the mesh
DWORD         m_dwNumMaterials;  // Number of material structs in the mesh

DWORD dwFormat = D3DXF_FILEFORMAT_BINARY;  // Binary-format .x file (default)
// DWORD dwFormat = D3DXF_FILEFORMAT_TEXT; // Text-format .x file

// Load mesh into m_pMesh and determine values of m_pMaterials and
// m_dwNumMaterials with calls to D3DXLoadMeshxxx or other D3DX functions

// ...

D3DXSaveMeshToX(
    L"outputxfilename.x",
    m_pMesh,
    NULL,
    m_pMaterials,
    NULL,
    m_dwNumMaterials,
    dwFormat );

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXEFFECTDEFAULT, D3DXEFFECTINSTANCE


D3DXSimplifyMesh Function

Generates a simplified mesh using the provided weights that come as close as possible to the given MinValue.

Syntax

HRESULT WINAPI D3DXSimplifyMesh(

    LPD3DXMESH pMesh,
    const DWORD *pAdjacency,
    const D3DXATTRIBUTEWEIGHTS *pVertexAttributeWeights,
    const FLOAT *pVertexWeights,
    DWORD MinValue,
    DWORD Options,
    LPD3DXMESH *ppMesh
);

Parameters

pMesh
[in] Pointer to an ID3DXMesh interface, representing the source mesh.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh to be simplified.
pVertexAttributeWeights
[in] Pointer to a D3DXATTRIBUTEWEIGHTS structure, containing the weight for each vertex component. If this parameter is set to NULL, a default structure is used. See Remarks.
pVertexWeights
[in] Pointer to an array of vertex weights. If this parameter is set to NULL, all vertex weights are set to 1.0.
MinValue
[in] Number of vertices or faces, depending on the flag set in the Options parameter, by which to simplify the source mesh.
Options
[in] Specifies simplification options for the mesh. One of the flags in D3DXMESHSIMP can be set.
ppMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the returned simplification mesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

This function generates a mesh that has MinValue vertices or faces.

If the simplification process cannot reduce the mesh to MinValue, the call still succeeds because MinValue is a desired minimum, not an absolute minimum.

If pVertexAttributeWeights is set to NULL, the following values are assigned to the default D3DXATTRIBUTEWEIGHTS structure.

D3DXATTRIBUTEWEIGHTS AttributeWeights;

AttributeWeights.Position  = 1.0;
AttributeWeights.Boundary =  1.0;
AttributeWeights.Normal   =  1.0;
AttributeWeights.Diffuse  =  0.0;
AttributeWeights.Specular =  0.0;
AttributeWeights.Tex[8]   =  {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};

This default structure is what most applications should use because it considers only geometric and normal adjustment. Only in special cases will the other member fields need to be modified.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXSphereBoundProbe Function

Determines if a ray intersects the volume of a sphere's bounding box.

Syntax

BOOL WINAPI D3DXSphereBoundProbe(

    const D3DXVECTOR3 *pCenter,
    FLOAT Radius,
    const D3DXVECTOR3 *pRayPosition,
    const D3DXVECTOR3 *pRayDirection
);

Parameters

pCenter
[in] Pointer to a D3DXVECTOR3 structure, specifying the center coordinate of the sphere.
Radius
[in] Radius of the sphere.
pRayPosition
[in] Pointer to a D3DXVECTOR3 structure, specifying the origin coordinate of the ray.
pRayDirection
[in] Pointer to a D3DXVECTOR3 structure, specifying the direction of the ray. This vector should not be (0,0,0) but does not need to be normalized.

Return Value

Returns TRUE if the ray intersects the volume of the sphere's bounding box. Otherwise, returns FALSE.

Remarks

D3DXSphereBoundProbe determines if the ray intersects the volume of the sphere's bounding box, not just the surface of the sphere.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXSplitMesh Function

Splits a mesh into meshes smaller than the specified size.

Syntax

void WINAPI D3DXSplitMesh(

    LPD3DXMESH pMeshIn,
    const DWORD *pAdjacencyIn,
    const DWORD MaxSize,
    const DWORD Options,
    DWORD *pMeshesOut,
    LPD3DXBUFFER *ppMeshArrayOut,
    LPD3DXBUFFER *ppAdjacencyArrayOut,
    LPD3DXBUFFER *ppFaceRemapArrayOut,
    LPD3DXBUFFER *ppVertRemapArrayOut
);

Parameters

pMeshIn
[in] Pointer to an ID3DXMesh interface, representing the source mesh.
pAdjacencyIn
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh to be simplified.
MaxSize
[in] Maximum number of vertices in the resulting mesh.
Options
[in] Option flags for the new meshes.
pMeshesOut
[out, retval] Number of meshes returned.
ppMeshArrayOut
[out, retval] Buffer containing an array of ID3DXMesh interfaces for the new meshes. For a source mesh split into n meshes, ppMeshArrayOut is an array of n ID3DXMesh pointers.
ppAdjacencyArrayOut
[out, retval] Buffer containing an array of adjacency arrays (DWORDs) for the new meshes. See ID3DXBuffer. This parameter is optional.
ppFaceRemapArrayOut
[out, retval] Buffer containing an array of face remap arrays (DWORDs) for the new meshes. See ID3DXBuffer. This parameter is optional.
ppVertRemapArrayOut
[out, retval] Buffer containing an array of vertex remap arrays for the new meshes. See ID3DXBuffer. This parameter is optional.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

A common use of this function is to split a mesh with 32-bit indices (more than 65535 vertices) into more than one mesh, each of which has 16-bit indices.

The adjacency, vertex remap and face remap arrays are arrays are DWORDs where each array contains n DWORD pointers, followed by the DWORD data referenced by the pointers. For example, to obtain the face remap information for face 3 in mesh 2, the following code could be used, assuming the face remap data was returned in a variable named ppFaceRemapArrayOut.

const DWORD **face_remaps =
    static_cast<DWORD **>(ppFaceRemapArrayOut->GetBufferPointer());
const DWORD remap = face_remaps[2][3];

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXTessellateNPatches Function

Tessellates the given mesh using the N-patch tessellation scheme.

Syntax

HRESULT WINAPI D3DXTessellateNPatches(

    LPD3DXMESH pMeshIn,
    const DWORD *pAdjacencyIn,
    FLOAT NumSegs,
    BOOL QuadraticInterpNormals,
    LPD3DXMESH *ppMeshOut,
    LPD3DXBUFFER *ppAdjacencyOut
);

Parameters

pMeshIn
[in] Pointer to an ID3DXMesh interface, representing the mesh to tessellate.
pAdjacencyIn
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the source mesh. This parameter may be NULL.
NumSegs
[in] Number of segments per edge to tessellate.
QuadraticInterpNormals
[in] If set to TRUE, use quadratic interpolation for normals. If set to FALSE, use linear interpolation.
ppMeshOut
[out] Address of a pointer to an ID3DXMesh interface, representing the returned tessellated mesh.
ppAdjacencyOut
[out] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the output mesh. This parameter may be NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

This function tessellates by using the N-patch algorithm.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXTessellateRectPatch Function

Tessellates a rectangular higher-order surface patch into a triangle mesh.

Syntax

HRESULT WINAPI D3DXTessellateRectPatch(

    LPDIRECT3DVERTEXBUFFER9 pVB,
    const FLOAT *pNumSegs,
    const D3DVERTEXELEMENT9 *pInDecl,
    const D3DRECTPATCH_INFO *pRectPatchInfo,
    LPD3DXMESH pMesh
);

Parameters

pVB
[in] Vertex buffer containing the patch data.
pNumSegs
[in] Pointer to an array of four floating-point values that identify the number of segments into which each edge of the rectangle patch should be divided when tessellated. See D3DRECTPATCH_INFO.
pInDecl
[in] Vertex declaration structure that defines the vertex data. See D3DVERTEXELEMENT9.
pRectPatchInfo
[in] Describes a rectangular patch. See D3DRECTPATCH_INFO.
pMesh
[in, out] Pointer to the created mesh. See ID3DXMesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

Use D3DXRectPatchSize to get the number of output vertices and indices that the tessellation function needs.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXTessellateTriPatch


D3DXTessellateTriPatch Function

Tessellates a triangular higher-order surface patch into a triangle mesh.

Syntax

HRESULT WINAPI D3DXTessellateTriPatch(

    LPDIRECT3DVERTEXBUFFER9 pVB,
    const FLOAT *pNumSegs,
    const D3DVERTEXELEMENT9 *pInDecl,
    const D3TRIPATCH_INFO *pTriPatchInfo,
    LPD3DXMESH pMesh
);

Parameters

pVB
[in] Vertex buffer containing the patch data.
pNumSegs
[in] Pointer to an array of three floating-point values that identify the number of segments into which each edge of the triangle patch should be divided when tessellated. See D3DTRIPATCH_INFO.
pInDecl
[in] Vertex declaration structure that defines the vertex data. See D3DVERTEXELEMENT9.
pTriPatchInfo
[in] Describes a triangle patch. See D3DTRIPATCH_INFO.
pMesh
[in, out] Pointer to the created mesh. See ID3DXMesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

Use D3DXTriPatchSize to get the number of output vertices and indices that the tessellation function needs.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXTessellateRectPatch


D3DXTriPatchSize Function

Gets the size of the triangle patch.

Syntax

HRESULT WINAPI D3DXTriPatchSize(

    const LOAT *pfNumSegs,
    DWORD *pdwTriangles,
    DWORD *pdwVertices
);

Parameters

pfNumSegs
[in] Number of segments per edge to tessellate.
pdwTriangles
[out] Pointer to a DWORD that contains the number of triangles in the patch.
pdwVertices
[out] Pointer to a DWORD that contains the number of vertices in the triangle patch.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXTessellateTriPatch


D3DXValidMesh Function

Validates a mesh.

Syntax

HRESULT WINAPI D3DXValidMesh(

    LPD3DXMESH pMeshIn,
    const DWORD *pAdjacency,
    LPD3DXBUFFER *ppErrorsAndWarnings
);

Parameters

pMeshIn
[in] Pointer to an ID3DXMesh interface, representing the mesh to be tested.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh to be tested.
ppErrorsAndWarnings
[out] Returns a buffer containing a string of errors and warnings, which explain the problems found in the mesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DXERR_INVALIDMESH | The mesh is invalid.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

This method validates the mesh by checking for invalid indices. Error information is available from the debugger output.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXValidPatchMesh Function

Validates a patch mesh, returning the number of degenerate vertices and patches.

Syntax

HRESULT WINAPI D3DXValidPatchMesh(

    LPD3DXPATCHMESH pMeshIn,
    DWORD *pNumDegenerateVertices,
    DWORD *pNumDegeneratePatches,
    LPD3DXBUFFER *ppErrorsAndWarnings
);

Parameters

pMeshIn
[in] Pointer to an ID3DXPatchMesh interface, representing the patch mesh to be tested.
pNumDegenerateVertices
[out] Returns the number of degenerate vertices in the patch mesh.
pNumDegeneratePatches
[out] Returns the number of degenerate patches in the patch mesh.
ppErrorsAndWarnings
[out] Returns a pointer to a buffer containing a string of errors and warnings that explain the problems found in the patch mesh.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

This method validates the mesh by checking for invalid indices. Error information is available from the debugger output.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXWeldVertices Function

Welds together replicated vertices that have equal attributes. This method uses specified epsilon values for equality comparisons.

Syntax

HRESULT WINAPI D3DXWeldVertices(

    LPD3DXMESH pMesh,
    DWORD Flags,
    const D3DXWELDEPSILONS *pEpsilons,
    const DWORD *pAdjacencyIn,
    DWORD *pAdjacencyOut,
    DWORD *pFaceRemap,
    LPD3DXBUFFER *ppVertexRemap
);

Parameters

pMesh
[in] Pointer to an ID3DXMesh object, the mesh from which to weld vertices.
Flags
[in] Combination of one or more flags from D3DXWELDEPSILONSFLAGS.
pEpsilons
[in] Pointer to a D3DXWELDEPSILONS structure, specifying the epsilon values to be used for this method. If NULL, a default value of 1.0e-6f is used for all members of D3DXWELDEPSILONS.
pAdjacencyIn
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the source mesh. If the edge has no adjacent faces, the value is 0xffffffff. If this parameter is set to NULL, ID3DXBaseMesh::GenerateAdjacency will be called to create logical adjacency information.
pAdjacencyOut
[in, out] Pointer to a destination buffer for the face adjacency array of the optimized mesh. The face adjacency is stored as an array of arrays. The innermost array is three indices of adjacent triangles, and the outer array is one set of face adjacency per triangle in the mesh.
pFaceRemap
[out] Pointer to a destination array containing the new index for each face. The array has the same number of elements as the original number of faces. Each element of the array contains either the index of the original face, or 0xffffffff if the original face has been removed in the vertex welding.
ppVertexRemap
[out] Address of a pointer to an ID3DXBuffer interface, containing the new index for each vertex.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

This function uses supplied adjacency information to determine the points that are replicated. Vertices are merged based upon an epsilon comparison. Vertices with equal position must already have been calculated and represented by point-representative data.

This function combines logically-welded vertices that have similar components, such as normals within pEpsilons or texture coordinates within pEpsilons.

The following example code calls this function with welding enabled. Vertices are compared using epsilon values for normal vector and vertex position. A pointer is returned to a face remapping array, pFaceRemap.

TCHAR            strMediaPath[512];       // X-file path
LPD3DXBUFFER     pAdjacencyBuffer = NULL; // adjacency data buffer
LPD3DXBUFFER     pD3DXMtrlBuffer  = NULL; // material buffer
LPD3DXMESH       pMesh            = NULL; // mesh object
DWORD            m_dwNumMaterials;        // number of materials
D3DXWELDEPSILONS Epsilons;                // structure with epsilon values
DWORD            *pFaceRemap[65536];      // face remapping array
DWORD            i;                       // internal variable

// Load the mesh from the specified file

hr = D3DXLoadMeshFromX ( strMediaPath,
                         D3DXMESH_MANAGED,
                         m_pd3dDevice,
                         &pAdjacencyBuffer,
                         &pD3DXMtrlBuffer,
                         NULL,
                         &m_dwNumMaterials,
                         &pMesh ) )

if( FAILED( hr ) ) goto End;              // Go to error handling

// Set epsilon values

Epsilons.Normal = 0.001;
Epsilons.Position = 0.1;

// Weld the vertices

for( i=0; i<65536; i++ ) { pFaceRemap[i] = 0; }

hr = D3DXWeldVertices ( pMesh,
                        D3DXWELDEPSILONS_WELDPARTIALMATCHES,
                        &Epsilons,
                        (DWORD*)pAdjacencyBuffer->GetBufferPointer(),
                        (DWORD*)pAdjacencyBuffer->GetBufferPointer(),
                        (DWORD*)pFaceRemap,
                        NULL )

if( FAILED( hr ) ) goto End;              // Go to error handling
.
.
.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


Precomputed Radiance Transfer Functions
Microsoft DirectX 9.0 SDK Update (October 2004)

Precomputed Radiance Transfer Functions

D3DX supplies the following precomputed radiance transfer (PRT) functions:

  • D3DXCreatePRTBuffer
  • D3DXCreatePRTBufferTex
  • D3DXCreatePRTCompBuffer
  • D3DXCreatePRTEngine
  • D3DXCreateTextureGutterHelper
  • D3DXLoadPRTBufferFromFile
  • D3DXLoadPRTCompBufferFromFile
  • D3DXSavePRTBufferToFile
  • D3DXSavePRTCompBufferToFile
  • D3DXSHPRTCompSplitMeshSC
  • D3DXSHPRTCompSuperCluster

For more information about using PRT, see Precomputed Radiance Transfer.

The D3DXSHxxx functions are also used for PRT spherical harmonic (SH) operations.

Related Topics

  • D3DXConcatenateMeshes


D3DXCreatePRTBuffer Function

Creates a precomputed radiance transfer (PRT) buffer that can be compressed or filled by a simulator. This function should be used to create per-vertex or volume buffers.

Syntax

HRESULT WINAPI D3DXCreatePRTBuffer(

    UINT NumSamples,
    UINT NumCoeffs,
    UINT NumChannels,
    LPD3DXPRTBUFFER *ppBuffer
);

Parameters

NumSamples
[in] Number of vertices (or texels) sampled.
NumCoeffs
[in] Number of coefficients per sample location. When using spherical harmonic (SH) PRT, the number of coefficients should be Order2, where Order is the order of the SH evaluation. Order must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The degree of the evaluation is Order - 1.
NumChannels
[in] Number of color channels to set in the mesh. Set to 1 to specify gray materials (R = G = B), or 3 to enable color bleeding effects.
ppBuffer
[in, out] Address of a pointer to the created ID3DXPRTBuffer object.

Return Value

If the function succeeds, the return value is S_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

When the buffer is created, all values are initialized to zero.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreatePRTBufferTex


D3DXCreatePRTBufferTex Function

Creates a precomputed radiance transfer (PRT) buffer that can be compressed or filled by a simulator. This function should be used to create per-pixel buffers.

Syntax

HRESULT WINAPI D3DXCreatePRTBufferTex(

    UINT Width,
    UINT Height,
    UINT NumCoeffs,
    UINT NumChannels,
    LPD3DXPRTBUFFER *ppBuffer
);

Parameters

Width
[in] Width of the texture, in pixels.
Height
[in] Height of the texture, in pixels.
NumCoeffs
[in] Number of coefficients per sample location. When using spherical harmonic (SH) PRT, the number of coefficients should be Order2, where Order is the order of the SH evaluation. Order must be in the range of D3DXSH_MINORDER to D3DXSH_MAXORDER, inclusive. The degree of the evaluation is Order - 1.
NumChannels
[in] Number of color channels to set in the mesh. Set to 1 to specify gray materials (R = G = B), or 3 to enable color bleeding effects.
ppBuffer
[in, out] Address of a pointer to the created ID3DXPRTBuffer object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

When the buffer is created, all values are initialized to zero.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreatePRTBuffer


D3DXCreatePRTCompBuffer Function

Creates a compressed precomputed radiance transfer (PRT) buffer from an uncompressed ID3DXPRTBuffer object. This function should be used with per-vertex or volume buffers.

Syntax

HRESULT WINAPI D3DXCreatePRTCompBuffer(

    D3DXSHCOMPRESSQUALITYTYPE Quality,
    UINT NumClusters,
    UINT NumPCA,
    LPD3DXPRTBUFFER pBuffer,
    LPD3DXPRTCOMPBUFFER *ppBuffer
);

Parameters

Quality
[in] Quality of spherical harmonic (SH) compression. See D3DXSHCOMPRESSQUALITYTYPE.
NumClusters
[in] Number of clusters to use for compression.
NumPCA
[in] Number of principal component analysis (PCA) basis vectors to use in each cluster.
pBuffer
[in] Address of a pointer to the uncompressed ID3DXPRTBuffer object that will be compressed.
ppBuffer
[in, out] Address of a pointer to the output ID3DXPRTCompBuffer object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreatePRTBufferTex


D3DXCreatePRTEngine Function

Creates an ID3DXPRTEngine object that can efficiently generate precomputed radiance transfer (PRT) simulations of a 3-D scene.

Syntax

HRESULT WINAPI D3DXCreatePRTEngine(

    LPD3DXMESH pMesh,
    BOOL ExtractUVs,
    LPD3DXMESH pBlockerMesh,
    LPD3DXPRTENGINE ppEngine
);

Parameters

pMesh
[in] Pointer to an input ID3DXMesh mesh object that models the 3-D scene. This mesh must have an attribute table in which vertices are in a unique attribute.
ExtractUVs
[in] If TRUE, textures will be used to store albedos or PRT vectors.
pBlockerMesh
[in] Pointer to an optional ID3DXMesh mesh object that blocks the 3-D scene. May be NULL.
ppEngine
[in, out] Pointer to an output ID3DXPRTEngine object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

Use D3DXConcatenateMeshes to transform a scene to new coordinates.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXCreateTextureGutterHelper Function

Creates an ID3DXTextureGutterHelper object from an input mesh and texture data.

Syntax

HRESULT WINAPI D3DXCreateTextureGutterHelper(

    UINT Width,
    UINT Height,
    LPD3DXMESH pMesh,
    FLOAT GutterSize,
    LPD3DXTEXTUREGUTTERHELPER *ppBuffer
);

Parameters

Width
[in] Width of the texture, in pixels.
Height
[in] Height of the texture, in pixels.
pMesh
[in] Pointer to an input ID3DXMesh mesh object.
GutterSize
[in] Number of texels by which to over-sample the texture and create the gutter region. Must be at least 1.
ppBuffer
[in, out] Pointer to an ID3DXTextureGutterHelper object to be created.

Return Value

If the function succeeds, the return value is S_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Use D3DXConcatenateMeshes to transform a scene to new coordinates.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXLoadPRTBufferFromFile Function

Loads into memory a precomputed radiance transfer (PRT) buffer that was saved to disk.

Syntax

HRESULT WINAPI D3DXLoadPRTBufferFromFile(

    LPCSTR pFileName,
    LPD3DXPRTBUFFER *ppBuffer
);

Parameters

pFileName
[in] Name of the file from which to load the buffer data.
ppBuffer
[in, out] Address of a pointer to the output ID3DXPRTBuffer object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXLoadPRTBufferFromFileW. Otherwise, the function call resolves to D3DXLoadPRTBufferFromFileA.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXLoadPRTCompBufferFromFile Function

Loads into memory a compressed precomputed radiance transfer (PRT) buffer that was saved to disk.

Syntax

HRESULT WINAPI D3DXLoadPRTCompBufferFromFile(

    LPCSTR pFileName,
    LPD3DXPRTCOMPBUFFER *ppBuffer
);

Parameters

pFileName
[in] Name of the file from which to load the compressed buffer data.
ppBuffer
[in, out] Address of a pointer to the output ID3DXPRTCompBuffer object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXLoadPRTCompBufferFromFileW. Otherwise, the function call resolves to D3DXLoadPRTCompBufferFromFileA.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXSavePRTBufferToFile Function

Saves a precomputed radiance transfer (PRT) buffer to disk.

Syntax

HRESULT WINAPI D3DXSavePRTBufferToFile(

    LPCSTR pFileName,
    LPD3DXPRTBUFFER pBuffer
);

Parameters

pFileName
[in] Name of the file to which the buffer is to be saved.
pBuffer
[in] Address of a pointer to the input ID3DXPRTBuffer object.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXSavePRTBufferToFileW. Otherwise, the function call resolves to D3DXSavePRTBufferToFileA.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXSavePRTCompBufferToFile Function

Saves a compressed precomputed radiance transfer (PRT) buffer to disk.

Syntax

HRESULT WINAPI D3DXSavePRTCompBufferToFile(

    LPCSTR pFileName,
    LPD3DXPRTCOMPBUFFER pBuffer
);

Parameters

pFileName
[in] Name of the file to which the compressed buffer is to be saved.
pBuffer
[in] Address of a pointer to the input ID3DXPRTCompBuffer object.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXSavePRTCompBufferToFileW. Otherwise, the function call resolves to D3DXSavePRTCompBufferToFileA.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXSHPRTCompSplitMeshSC Function

Used with compressed results of the vertex version of the precomputed radiance transfer (PRT) simulator. After D3DXSHPRTCompSuperCluster has been called, this function can be used to split the mesh into a group of faces/vertices per super cluster. Each super cluster contains all of the faces that contain any vertex classified in one of its clusters. All of the vertices connected to this set of faces are also included with the returned array ppVertStatus indicating whether or not the vertex belongs to the super cluster.

Syntax

HRESULT WINAPI D3DXSHPRTCompSplitMeshSC(

    UINT *pClusterIDs,
    UINT NumVertices,
    UINT NumCs,
    UINT *pSClusterIDs,
    UINT NumSCs,
    LPVOID pInputIB,
    BOOL InputIBIs32Bit,
    UINT NumFaces,
    LPD3DXBUFFER *ppIBData,
    UINT *pIBDataLength,
    BOOL OutputIBIs32Bit,
    LPD3DXBUFFER *ppFaceRemap,
    LPD3DXBUFFER *ppVertData,
    UINT *pVertDataLength,
    UINT *pSCClusterList,
    D3DXSHPRTSPLITMESHCLUSTERDATA* pSCData
);

Parameters

pClusterIDs
[in] uNumVerts cluster identifiers (IDs) (extracted from a compressed buffer.)
NumVertices
[in] Number of vertices in original mesh.
NumCs
[in] Number of clusters (input parameter to compression.)
pSClusterIDs
[in] Array of size uNumC that will contain super cluster IDs.
NumSCs
[in] Number of super clusters allocated in D3DXSHPRTCompSuperCluster.
pInputIB
[in] Raw index buffer for mesh. The format depends on InputIBIs32Bit.
InputIBIs32Bit
[in] If TRUE, the index buffer is set to 32 bit; otherwise, 16 bit.
NumFaces
[in] Number of faces in the original mesh (pInputIB is 3 times this length.)
ppIBData
[in, out] Raw index buffer that will contain the resulting split faces. Format determined by bIBIs32Bit. Allocated by function.
pIBDataLength
[in, out] Length of ppIBData, assigned in function.
OutputIBIs32Bit
[in, out] If TRUE, allocates an unsigned integer array; otherwise, allocates an unsigned short array.
ppFaceRemap
[in, out] Mapping of each face in ppIBData to original faces. Length is *pIBDataLength/3.
ppVertData
[in, out] New vertex data structure. Size of pVertDataLength.
pVertDataLength
[in, out] Number of new vertices in split mesh. Assigned in function.
pSCClusterList
[in, out] Array of length uNumC which pSCData indexes into (Cluster* fields) for each supercluster, contains clusters sorted by supercluster.
pSCData
[in, out] Structure per super cluster. Contains indices into ppIBData, pSCClusterList, and ppVertData.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXSHPRTCompSuperCluster Function

Used with compressed results of the vertex version of the precomputed radiance transfer (PRT) simulator. Generates "superclusters," which are groups of clusters that can be drawn in the same draw call. A greedy algorithm that minimizes overdraw is used to group the clusters.

Syntax

HRESULT WINAPI D3DXSHPRTCompSuperCluster(

    UINT *pClusterIDs,
    LPD3DXMESH pScene,
    UINT MaxNumClusters,
    UINT NumClusters,
    UINT *pSClusterIDs,
    UINT *pNumSCs
);

Parameters

pClusterIDs
[in] Pointer to a NumVerts cluster identifiers (IDs) (extracted from a compressed buffer.)
pScene
[in] Pointer to a mesh that represents composite scene passed to the simulator. See ID3DXMesh.
MaxNumClusters
[in] Maximum number of clusters allocated per super cluster.
NumClusters
[in] Number of clusters computed in the simulator.
pSClusterIDs
[in, out] Pointer to an array of length NumClusters. Contains the index of the super cluster to which the corresponding cluster was assigned.
pNumSCs
[in, out] Number of super clusters allocated.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9mesh.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


Shader Functions
Microsoft DirectX 9.0 SDK Update (October 2004)

Shader Functions

D3DX supplies the following shader functions.

  • D3DXAssembleShader
  • D3DXAssembleShaderFromFile
  • D3DXAssembleShaderFromResource
  • D3DXCompileShader
  • D3DXCompileShaderFromFile
  • D3DXCompileShaderFromResource
  • D3DXCreateFragmentLinker
  • D3DXCreateTextureShader
  • D3DXDisassembleShader
  • D3DXFindShaderComment
  • D3DXGatherFragments
  • D3DXGatherFragmentsFromFile
  • D3DXGatherFragmentsFromResource
  • D3DXGetPixelShaderProfile
  • D3DXGetShaderConstantTable
  • D3DXGetShaderSize
  • D3DXGetShaderVersion
  • D3DXGetShaderInputSemantics
  • D3DXGetShaderOutputSemantics
  • D3DXGetShaderSamplers
  • D3DXGetVertexShaderProfile


D3DXAssembleShader Function

Assemble a shader.

Syntax

HRESULT WINAPI D3DXAssembleShader(

    LPCSTR pSrcData,
    UINT SrcDataLen,
    CONST D3DXMACRO* pDefines,
    LPD3DXINCLUDE pInclude,
    DWORD Flags,
    LPD3DXBUFFER* ppShader,
    LPD3DXBUFFER *ppErrorMsgs
);

Parameters

pSrcData
[in] Pointer to a memory buffer that contains the shader data.
SrcDataLen
[in] Length of the effect data, in bytes.
pDefines
[in] An optional NULL terminated array of D3DXMACRO structures. This value may be NULL.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by D3DXSHADER Compile Options.
ppShader
[out] Returns a buffer containing the created shader. This buffer contains the compiled shader code, as well as any embedded debug and symbol table information.
ppErrorMsgs
[out] Returns a buffer containing a listing of errors and warnings that were encountered during the compile. These are the same messages the debugger displays when running in debug mode. This value may be NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXAssembleShaderFromFile, D3DXAssembleShaderFromResource


D3DXAssembleShaderFromFile Function

Assemble a shader.

Syntax

HRESULT WINAPI D3DXAssembleShaderFromFile(

    LPCTSTR pSrcFile,
    CONST D3DXMACRO* pDefines,
    LPD3DXINCLUDE pInclude,
    DWORD Flags,
    LPD3DXBUFFER* ppShader,
    LPD3DXBUFFER *ppErrorMsgs
);

Parameters

pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pDefines
[in] An optional NULL terminated array of D3DXMACRO structures. This value may be NULL.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by D3DXSHADER Compile Options.
ppShader
[out] Returns a buffer containing the created shader. This buffer contains the compiled shader code, as well as any embedded debug and symbol table information.
ppErrorMsgs
[out] Returns a buffer containing a listing of errors and warnings that were encountered during the compile. These are the same messages the debugger displays when running in debug mode. This value may be NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXAssembleShaderFromFileW. Otherwise, the function call resolves to D3DXAssembleShaderFromFileA because ANSI strings are being used.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCompileShader, D3DXCompileShaderFromResource


D3DXAssembleShaderFromResource Function

Assemble a shader.

Syntax

HRESULT WINAPI D3DXAssembleShaderFromResource(

    HMODULE hSrcModule,
    LPCTSTR pSrcResource,
    CONST D3DXMACRO* pDefines,
    LPD3DXINCLUDE pInclude,
    DWORD Flags,
    LPD3DXBUFFER* ppShader,
    LPD3DXBUFFER *ppErrorMsgs
);

Parameters

hSrcModule
[in] Handle to a module containing the effect description. If this parameter is NULL, the current module will be used.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pDefines
[in] An optional NULL terminated array of D3DXMACRO structures. This value may be NULL.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by D3DXSHADER Compile Options.
ppShader
[out] Returns a buffer containing the created shader. This buffer contains the compiled shader code, as well as any embedded debug and symbol table information.
ppErrorMsgs
[out] Returns a buffer containing a listing of errors and warnings that were encountered during the compile. These are the same messages the debugger displays when running in debug mode. This value may be NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXAssembleShaderFromResourceW. Otherwise, the function call resolves to D3DXAssembleShaderFromResourceA because ANSI strings are being used.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCompileShader, D3DXCompileShaderFromResource


D3DXCompileShader Function

Compile a shader file.

Syntax

HRESULT WINAPI D3DXCompileShader(

    LPCTSTR pSrcData,
    UINT srcDataLen,
    CONST D3DXMACRO* pDefines,
    LPD3DXINCLUDE pInclude,
    LPCSTR pFunctionName,
    LPCSTR pProfile,
    DWORD Flags,
    LPD3DXBUFFER* ppShader,
    LPD3DXBUFFER* ppErrorMsgs,
    LPD3DXCONSTANTTABLE *ppConstantTable
);

Parameters

pSrcData
[in] Pointer to a string that contains the shader. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
srcDataLen
[in] Length of the data in bytes.
pDefines
[in] An optional NULL terminated array of D3DXMACRO structures. This value may be NULL.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
pFunctionName
[in] Pointer to a string that contains the name of the shader entry point function where execution begins. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pProfile
[in] Pointer to a shader profile which detemines the shader instruction set. See D3DXGetVertexShaderProfile or D3DXGetPixelShaderProfile for a list of the profiles available.
Flags
[in] Compile options identified by D3DXSHADER Compile Options.
ppShader
[out] Returns a buffer containing the created shader. This buffer contains the compiled shader code, as well as any embedded debug and symbol table information.
ppErrorMsgs
[out] Returns a buffer containing a listing of errors and warnings that were encountered during the compile. These are the same messages the debugger displays when running in debug mode. This value may be NULL.
ppConstantTable
[out] Returns an ID3DXConstantTable interface, which can be used to access shader constants. This value may be NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR.

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCompileShaderW. Otherwise, the function call resolves to D3DXCompileShaderA because ANSI strings are being used.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCompileShader, D3DXCompileShaderFromResource


D3DXCompileShaderFromFile Function

Compile a shader file.

Syntax

HRESULT WINAPI D3DXCompileShaderFromFile(

    LPCTSTR pSrcFile,
    CONST D3DXMACRO* pDefines,
    LPD3DXINCLUDE pInclude,
    LPCSTR pFunctionName,
    LPCSTR pProfile,
    DWORD Flags,
    LPD3DXBUFFER* ppShader,
    LPD3DXBUFFER *ppErrorMsgs,
    LPD3DXCONSTANTTABLE *ppConstantTable
);

Parameters

pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pDefines
[in] An optional NULL terminated array of D3DXMACRO structures. This value may be NULL.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
pFunctionName
[in] Pointer to the shader entry point function where execution begins. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pProfile
[in] Pointer to a shader profile which detemines the shader instruction set. See D3DXGetVertexShaderProfile or D3DXGetPixelShaderProfile for a list of the profiles available.
Flags
[in] Compile options identified by D3DXSHADER Compile Options.
ppShader
[out] Returns a buffer containing the created shader. This buffer contains the compiled shader code, as well as any embedded debug and symbol table information.
ppErrorMsgs
[out] Returns a buffer containing a listing of errors and warnings that were encountered during the compile. These are the same messages the debugger displays when running in debug mode. This value may be NULL.
ppConstantTable
[out] Returns an ID3DXConstantTable interface, which can be used to access shader constants. This value may be NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR.

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCompileShaderFromFileW. Otherwise, the function call resolves to D3DXCompileShaderFromFileA because ANSI strings are being used.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCompileShader, D3DXCompileShaderFromResource


D3DXCompileShaderFromResource Function

Compile a shader file.

Syntax

HRESULT WINAPI D3DXCompileShaderFromResource(

    HMODULE hSrcModule,
    LPCTSTR pSrcResource,
    CONST D3DXMACRO* pDefines,
    LPD3DXINCLUDE pInclude,
    LPCSTR pFunctionName,
    LPCSTR pProfile,
    DWORD Flags,
    LPD3DXBUFFER* ppShader,
    LPD3DXBUFFER *ppErrorMsgs,
    LPD3DXCONSTANTTABLE *ppConstantTable
);

Parameters

hSrcModule
[in] Handle to a module containing the effect description. If this parameter is NULL, the current module will be used.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pDefines
[in] An optional NULL terminated array of D3DXMACRO structures. This value may be NULL.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file, or will error when compiled from a resource or memory.
pFunctionName
[in] Pointer to the shader entry point function where execution begins.
pProfile
[in] Pointer to a shader profile which detemines the shader instruction set. See D3DXGetVertexShaderProfile or D3DXGetPixelShaderProfile for a list of the profiles available.
Flags
[in] Compile options identified by D3DXSHADER Compile Options.
ppShader
[out] Returns a buffer containing the created shader. This buffer contains the compiled shader code, as well as any embedded debug and symbol table information.
ppErrorMsgs
[out] Returns a buffer containing a listing of errors and warnings that were encountered during the compile. These are the same messages the debugger displays when running in debug mode. This value may be NULL.
ppConstantTable
[out] Returns an ID3DXConstantTable interface, which can be used to access shader constants. This value may be NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR.

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCompileShaderFromResourceW. Otherwise, the function call resolves to D3DXCompileShaderFromResourceA because ANSI strings are being used.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCompileShader, D3DXCompileShaderFromFile


D3DXDisassembleShader Function

Disassemble a shader.

Syntax

HRESULT WINAPI D3DXDisassembleShader(

    const DWORD *pShader,
    BOOL EnableColorCode,
    LPCSTR pComments,
    LPD3DXBUFFER *ppDisassembly
);

Parameters

pShader
[in] Pointer to a memory buffer that contains the shader data.
EnableColorCode
[in] Enable color code to make it easier to read the disassembly.
pComments
[in] An optional NULL-terminated comment string. This value may be NULL.
ppDisassembly
[out] Returns a buffer containing the disassembled shader. See ID3DXBuffer.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXCreateFragmentLinker Function

Create a fragment linker. This can be used to link one or more shader fragments together.

Syntax

HRESULT WINAPI D3DXCreateFragmentLinker(

    LPDIRECT3DDEVICE9 pDevice,
    UINT ShaderCacheSize,
    LPD3DXFRAGMENTLINKER *ppFragmentLinker
);

Parameters

pDevice
[in] Pointer to the current device. See IDirect3DDevice9.
ShaderCacheSize
[in] Shader cache size in bytes. This can be used for optimization.
ppFragmentLinker
[out] Returns a pointer to the new fragment linker interface. See ID3DXFragmentLinker.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

Here is an example taken from the FragmentLinker Sample that creates a fragment linker:

ID3DXFragmentLinker* g_pFragmentLinker = NULL;
IDirect3DDevice9*    pd3dDevice        = NULL;

    // Initialize the device before using it
    ...

    // Create the fragment linker interface
    D3DXCreateFragmentLinker( pd3dDevice, 0, &g_pFragmentLinker );

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXCreateTextureShader Function

Creates a texture shader object from the compiled shader.

Syntax

HRESULT D3DXCreateTextureShader(

    CONST DWORD *pFunction,
    LPD3DXTEXTURESHADER *ppTextureShader
);

Parameters

pFunction
[in] Pointer to the function DWORD stream.
ppTextureShader
[out] Returns an ID3DXTextureShader object which can be used to procedurally fill the contents of a texture using the D3DXFillTextureTX functions.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum availability | DirectX 9.0
Minimum operating systems | Windows 2000, Windows 98


D3DXFindShaderComment Function

Searches through a shader for a particular comment. The comment is identified by a four-character code (FOURCC) in the first DWORD of the comment.

Syntax

HRESULT WINAPI D3DXFindShaderComment(

    CONST DWORD* pFunction,
    DWORD FourCC,
    LPCVOID* ppData,
    UINT* pSizeInBytes
);

Parameters

pFunction
[in] Pointer to the shader function DWORD stream.
FourCC
[in] FOURCC code that identifies the comment block. See FourCC Formats.
ppData
[in] Returns a pointer to the comment data (not including the comment token and FOURCC code). This value can be NULL.
pSizeInBytes
[out] Returns the size of the comment data in bytes. This value can be NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the comment is not found, and no other error has occurred, S_FALSE is returned.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXGatherFragments Function

Gathers shader fragments into a buffer to be passed to the fragment linker.

Syntax

HRESULT WINAPI D3DXGatherFragments(

    LPCSTR pSrcData,
    UINT SrcDataLen,
    CONST D3DXMACRO* pDefines,
    LPD3DXINCLUDE pInclude,
    DWORD Flags,
    LPD3DXBUFFER* ppShader,
    LPD3DXBUFFER *ppErrorMsgs
);

Parameters

pSrcData
[in] Pointer to a ANSI string that contains the shader code.
SrcDataLen
[in] Length of the shader code, in bytes.
pDefines
[in] An optional NULL terminated array of D3DXMACRO structures. This value may be NULL.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by D3DXSHADER Compile Options.
ppShader
[in, out] Returns a buffer containing the created shader fragments, as well as any embedded debug info.
ppErrorMsgs
[in, out] Returns a buffer containing a listing of errors and warnings that were encountered during the creation of shader fragments. These are the same messages the debugger displays when running in debug mode. This value may be NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateFragmentLinker, Writing Shader Fragments


D3DXGatherFragmentsFromFile Function

Gathers shader fragments into a buffer to be passed to the fragment linker.

Syntax

HRESULT WINAPI D3DXGatherFragmentsFromFile(

    LPCTSTR pSrcFile,
    CONST D3DXMACRO* pDefines,
    LPD3DXINCLUDE pInclude,
    DWORD Flags,
    LPD3DXBUFFER* ppShader,
    LPD3DXBUFFER *ppErrorMsgs
);

Parameters

pSrcFile
[in] Pointer to the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pDefines
[in] An optional NULL terminated array of D3DXMACRO structures. This value may be NULL.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by D3DXSHADER Compile Options.
ppShader
[in, out] Returns a buffer containing the created shader fragments, as well as any embedded debug info.
ppErrorMsgs
[in, out] Returns a buffer containing a listing of errors and warnings that were encountered during the creation of shader fragments. These are the same messages the debugger displays when running in debug mode. This value may be NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXGatherFragmentsFromFileW. Otherwise, the function call resolves to D3DXGatherFragmentsFromFileA because ANSI strings are being used.

To compile a fragment within an effect call D3DXGatherFragmentsFromFile as shown here:

DWORD         g_dwShaderFlags; // Shader compilation/linking flags
LPD3DXBUFFER  g_pCompiledFragments = NULL;

    // Compile the fragments to a buffer. The fragments must be linked together to form
    // a shader before they can be used for rendering.
    V_RETURN( D3DXGatherFragmentsFromFile( L"FragmentLinker.fx", NULL,
                      NULL, g_dwShaderFlags, &g_pCompiledFragments, NULL ) );

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum availability | DirectX 9.0
Minimum operating systems | Windows 2000, Windows 98

See Also

D3DXCreateFragmentLinker, Writing Shader Fragments


D3DXGatherFragmentsFromResource Function

Gather shader fragments into a buffer to be passed to the fragment linker.

Syntax

HRESULT WINAPI D3DXGatherFragmentsFromResource(

    HMODULE hSrcModule,
    LPCTSTR pSrcResource,
    CONST D3DXMACRO* pDefines,
    LPD3DXINCLUDE pInclude,
    DWORD Flags,
    LPD3DXBUFFER* ppShader,
    LPD3DXBUFFER *ppErrorMsgs
);

Parameters

hSrcModule
[in] Handle to the module where the resource is located, or NULL for the module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pDefines
[in] An optional NULL terminated array of D3DXMACRO structures. This value may be NULL.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by D3DXSHADER Compile Options.
ppShader
[in, out] Returns a buffer containing the created shader fragments, as well as any embedded debug info.
ppErrorMsgs
[in, out] Returns a buffer containing a listing of errors and warnings that were encountered during the creation of shader fragments. These are the same messages the debugger displays when running in debug mode. This value may be NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXGatherFragmentsFromResourceW. Otherwise, the function call resolves to D3DXGatherFragmentsFromResourceA because ANSI strings are being used.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum availability | DirectX 9.0
Minimum operating systems | Windows 2000, Windows 98

See Also

D3DXCreateFragmentLinker, Writing Shader Fragments


D3DXGetPixelShaderProfile Function

Returns the name of the highest high-level shader language (HLSL) profile supported by a given device.

Syntax

LPCSTR WINAPI D3DXGetPixelShaderProfile(

    LPDIRECT3DDEVICE9 pDevice
);

Parameters

pDevice
[in] Pointer to the device. See IDirect3DDevice9.

Return Value

The HLSL profile name.

Remarks

A shader profile specifies the assembly shader version to use and the capabilities available to the HLSL compiler when compiling a shader. The following table lists the pixel shader profiles that are supported.

Shader Profile | Description
ps_1_1 | Compile to ps_1_1 version.
ps_1_2 | Compile to ps_1_2 version.
ps_1_3 | Compile to ps_1_3 version.
ps_1_4 | Compile to ps_1_4 version.
ps_2_0 | Compile to ps_2_0 version.
ps_2_a Same as the ps_2_0 profile, with the following additional capabilities available for the compiler to target:
  • Number of Temporary Registers (r#) is greater than or equal to 22.
  • Arbitrary source swizzle.
  • Gradient instructions: dsx, dsy.
  • Predication.
  • No dependent texture read limit.
  • No limit for the number of texture instructions.

For more information about the differences between shader versions, see Pixel Shader Differences.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXGetShaderConstantTable Function

Gets the shader constant table embedded inside shader.

Syntax

HRESULT WINAPI D3DXGetShaderConstantTable(

    CONST DWORD* pFunction,
    LPD3DXCONSTANTTABLE* ppConstantTable
);

Parameters

pFunction
[in] Pointer to the function DWORD stream.
ppConstantTable
[out, retval] Returns the constant table interface that manages the constant table. See ID3DXConstantTable.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

A constant table is generated by D3DXCompileShader and embedded in the body of the shader.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXGetShaderSize Function

Returns the size of the shader byte code, in bytes.

Syntax

UINT D3DXGetShaderSize(

    CONST DWORD *pFunction
);

Parameters

pFunction
[in] Pointer to the function DWORD stream.

Return Value

Returns the size of the shader byte code, in bytes.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum availability | DirectX 9.0
Minimum operating systems | Windows 2000, Windows 98


D3DXGetShaderVersion Function

Returns the shader version of the compiled shader.

Syntax

DWORD WINAPI D3DXGetShaderVersion(

    CONST DWORD* pFunction
);

Parameters

pFunction
[in] Pointer to the function DWORD stream.

Return Value

Returns the shader version of the given shader, or zero if the shader function is NULL.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXGetShaderInputSemantics Function

Get the semantics for all shader input elements.

Syntax

HRESULT WINAPI D3DXGetShaderInputSemantics(

    CONST DWORD* pFunction,
    D3DXSEMANTIC* pSemantics,
    UINT* pCount
);

Parameters

pFunction
[in] Pointer to the shader function DWORD stream.
pSemantics
[in] Pointer to an array of D3DXSEMANTIC structures. The function will fill this array with the semantics for each input element referenced by the shader. This array is assumed to contain at least MAXD3DDECLLENGTH elements. However, calling D3DXGetShaderInputSemantics with pSemantics = NULL will return the number of elements needed for pCount.
pCount
[out] Returns the number of elements in pSemantics.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXGetShaderOutputSemantics Function

Get the semantics for all shader output elements.

Syntax

HRESULT WINAPI D3DXGetShaderOutputSemantics(

    CONST DWORD* pFunction,
    D3DXSEMANTIC* pSemantics,
    UINT* pCount
);

Parameters

pFunction
[in] Pointer to the shader function DWORD stream.
pSemantics
[in] Pointer to an array of D3DXSEMANTIC structures. The function will fill this array with the semantics for each output element referenced by the shader. This array is assumed to contain at least MAXD3DDECLLENGTH elements. However, calling D3DXGetShaderOutputSemantics with pSemantics = NULL will return the number of elements needed for pCount.
pCount
[out] Returns the number of elements in pSemantics.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXGetShaderSamplers Function

Get the sampler names referenced in a shader.

Syntax

HRESULT WINAPI D3DXGetShaderSamplers(

    CONST DWORD* pFunction,
    LPCSTR* pSamplers,
    UINT* pCount
);

Parameters

pFunction
[in] Pointer to the shader function DWORD stream.
pSamplers
[in, out] Pointer to an array of LPCSTRs. The function will fill this array with pointers to the sampler names contained within pFunction. The maximum array size is the maximum number of sampler registers (16 for vs_3_0 and ps_3_0).

To find the number of samplers used, check pCount after calling D3DXGetShaderSamplers with pSamplers = NULL.

pCount
[out] Returns the number of samplers referenced by the shader.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXGetVertexShaderProfile Function

Returns the name of the highest high-level shader language (HLSL) profile supported by a given device.

Syntax

LPCSTR WINAPI D3DXGetVertexShaderProfile(

    LPDIRECT3DDEVICE9 pDevice
);

Parameters

pDevice
[in] Pointer to the device. See IDirect3DDevice9.

Return Value

The HLSL profile name.

Remarks

A shader profile specifies the assembly shader version to use and the capabilities available to the HLSL compiler when compiling a shader. The following table lists the vertex shader profiles that are supported.

Shader Profile | Description
vs_1_1 | Compile to vs_1_1 version.
vs_2_0 | Compile to vs_2_0 version.
vs_2_a Same as the vs_2_0 profile, with the following additional capabilities available for the compiler to target:
  • Number of Temporary Registers (r#) is greater than or equal to 13.
  • Dynamic flow control instruction.
  • Predication.

For more information about the differences between shader versions, see Vertex Shader Differences.

Function Information

Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


Shape Drawing Functions
Microsoft DirectX 9.0 SDK Update (October 2004)

Shape Drawing Functions

D3DX supplies the following shape-drawing functions.

  • D3DXCreateBox
  • D3DXCreateCylinder
  • D3DXCreatePolygon
  • D3DXCreateSphere
  • D3DXCreateTeapot
  • D3DXCreateText
  • D3DXCreateTorus

All shapes are returned as mesh objects.

These functions can be used in either a left-handed or right-handed coordinate system.


D3DXCreateBox Function

Uses a left-handed coordinate system to create a mesh containing an axis-aligned box.

Syntax

HRESULT WINAPI D3DXCreateBox(

    LPDIRECT3DDEVICE9 pDevice,
    FLOAT Width,
    FLOAT Height,
    FLOAT Depth,
    LPD3DXMESH *ppMesh,
    LPD3DXBUFFER *ppAdjacency
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the created box mesh.
Width
[in] Width of the box, along the x-axis.
Height
[in] Height of the box, along the y-axis.
Depth
[in] Depth of the box, along the z-axis.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The created box is centered at the origin.

This function creates a mesh with the D3DXMESH_MANAGED creation option and D3DFVF_XYZ | D3DFVF_NORMAL flexible vertex format (FVF).

Function Information

Header | d3dx9shape.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXCreateCylinder Function

Uses a left-handed coordinate system to create a mesh containing a cylinder.

Syntax

HRESULT WINAPI D3DXCreateCylinder(

    LPDIRECT3DDEVICE9 pDevice,
    FLOAT Radius1,
    FLOAT Radius2,
    FLOAT Length,
    UINT Slices,
    UINT Stacks,
    LPD3DXMESH *ppMesh,
    LPD3DXBUFFER *ppAdjacency
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the created cylinder mesh.
Radius1
[in] Radius at the negative Z end. Value should be greater than or equal to 0.0f.
Radius2
[in] Radius at the positive Z end. Value should be greater than or equal to 0.0f.
Length
[in] Length of the cylinder along the z-axis.
Slices
[in] Number of slices about the main axis.
Stacks
[in] Number of stacks along the main axis.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The created cylinder is centered at the origin, and its axis is aligned with the z-axis.

This function creates a mesh with the D3DXMESH_MANAGED creation option and D3DFVF_XYZ | D3DFVF_NORMAL flexible vertex format (FVF).

Function Information

Header | d3dx9shape.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXCreatePolygon Function

Uses a left-handed coordinate system to create a mesh containing an n-sided polygon.

Syntax

HRESULT WINAPI D3DXCreatePolygon(

    LPDIRECT3DDEVICE9 pDevice,
    FLOAT Length,
    UINT Sides,
    LPD3DXMESH *ppMesh,
    LPD3DXBUFFER *ppAdjacency
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the created polygon mesh.
Length
[in] Length of each side.
Sides
[in] Number of sides for the polygon. Value must be greater than or equal to 3.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The created polygon is centered at the origin.

This function creates a mesh with the D3DXMESH_MANAGED creation option and D3DFVF_XYZ | D3DFVF_NORMAL flexible vertex format (FVF).

Function Information

Header | d3dx9shape.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXCreateSphere Function

Uses a left-handed coordinate system to create a mesh containing a sphere.

Syntax

HRESULT WINAPI D3DXCreateSphere(

    LPDIRECT3DDEVICE9 pDevice,
    FLOAT Radius,
    UINT Slices,
    UINT Stacks,
    LPD3DXMESH *ppMesh,
    LPD3DXBUFFER *ppAdjacency
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the created sphere mesh.
Radius
[in] Radius of the sphere. This value should be greater than or equal to 0.0f.
Slices
[in] Number of slices about the main axis.
Stacks
[in] Number of stacks along the main axis.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The created sphere is centered at the origin, and its axis is aligned with the z-axis.

This function creates a mesh with the D3DXMESH_MANAGED creation option and D3DFVF_XYZ | D3DFVF_NORMAL flexible vertex format (FVF).

Function Information

Header | d3dx9shape.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXCreateTeapot Function

Uses a left-handed coordinate system to create a mesh containing a teapot.

Syntax

HRESULT WINAPI D3DXCreateTeapot(

    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXMESH *ppMesh,
    LPD3DXBUFFER *ppAdjacency
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the created teapot mesh.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

This function creates a mesh with the D3DXMESH_MANAGED creation option and D3DFVF_XYZ | D3DFVF_NORMAL flexible vertex format (FVF).

Function Information

Header | d3dx9shape.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXCreateText Function

Creates a mesh containing the specified text, using the font associated with the device context.

Syntax

HRESULT WINAPI D3DXCreateText(

    LPDIRECT3DDEVICE9 pDevice,
    HDC hDC,
    LPCTSTR pText,
    FLOAT Deviation,
    FLOAT Extrusion,
    LPD3DXMESH *ppMesh,
    LPD3DXBUFFER *ppAdjacency,
    LPGLYPHMETRICSFLOAT pGlyphMetrics
);

Parameters

pDevice
[in] Pointer to the device that created the mesh.
hDC
[in] Device context, containing the font for output. The font selected by the device context must be a TrueType® font.
pText
[in] Pointer to a string that specifies the text to generate. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Deviation
[in] Maximum chordal deviation from TrueType font outlines.
Extrusion
[in] Amount to extrude text in the negative z-direction.
ppMesh
[out] Pointer to the returned mesh.
ppAdjacency
[out] Pointer to a buffer containing adjacency information. May be NULL.
pGlyphMetrics
[out] Pointer to an array of GLYPHMETRICSFLOAT World Wide Web link structures that contain the glyph metric data. Each element contains information about the position and orientation of the corresponding glyph in the string. The number of elements in the array should be equal to the number of characters in the string. Note that the origin in each structure is not relative to the entire string, but rather is relative to that character cell. To compute the entire bounding box, add the increment for each glyph while traversing the string.

If you are not concerned with the glyph sizes, set this parameter to NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateTextW. Otherwise, the function call resolves to D3DXCreateTextA because ANSI strings are being used.

This function creates a mesh with the D3DXMESH_MANAGED creation option and D3DFVF_XYZ | D3DFVF_NORMAL flexible vertex format (FVF).

Function Information

Header | d3dx9shape.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXCreateTorus Function

Uses a left-handed coordinate system to create a mesh containing a torus.

Syntax

HRESULT WINAPI D3DXCreateTorus(

    LPDIRECT3DDEVICE9 pDevice,
    FLOAT InnerRadius,
    FLOAT OuterRadius,
    UINT Sides,
    UINT Rings,
    LPD3DXMESH *ppMesh,
    LPD3DXBUFFER *ppAdjacency
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the created torus mesh.
InnerRadius
[in] Inner-radius of the torus. Value should be greater than or equal to 0.0f.
OuterRadius
[in] Outer-radius of the torus. Value should be greater than or equal to 0.0f.
Sides
[in] Number of sides in a cross-section. Value must be greater than or equal to 3.
Rings
[in] Number of rings making up the torus. Value must be greater than or equal to 3.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The created torus is centered at the origin, and its axis is aligned with the z-axis. The inner radius of the torus is the radius of the cross-section (the minor radius), and the outer radius of the torus is the radius of the central hole.

This function returns a mesh that can be used later for drawing or manipulation by the application.

This function creates a mesh with the D3DXMESH_MANAGED creation option and D3DFVF_XYZ | D3DFVF_NORMAL flexible vertex format (FVF).

Function Information

Header | d3dx9shape.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


Texturing Functions
Microsoft DirectX 9.0 SDK Update (October 2004)

Texturing Functions

D3DX supplies the following texturing functions.

Functions

  • D3DXCheckCubeTextureRequirements
  • D3DXCheckTextureRequirements
  • D3DXCheckVolumeTextureRequirements
  • D3DXComputeNormalMap
  • D3DXCreateCubeTexture
  • D3DXCreateCubeTextureFromFile
  • D3DXCreateCubeTextureFromFileEx
  • D3DXCreateCubeTextureFromFileInMemory
  • D3DXCreateCubeTextureFromFileInMemoryEx
  • D3DXCreateCubeTextureFromResource
  • D3DXCreateCubeTextureFromResourceEx
  • D3DXCreateTexture
  • D3DXCreateTextureFromFile
  • D3DXCreateTextureFromFileEx
  • D3DXCreateTextureFromFileInMemory
  • D3DXCreateTextureFromFileInMemoryEx
  • D3DXCreateTextureFromResource
  • D3DXCreateTextureFromResourceEx
  • D3DXCreateVolumeTexture
  • D3DXCreateVolumeTextureFromFile
  • D3DXCreateVolumeTextureFromFileEx
  • D3DXCreateVolumeTextureFromFileInMemory
  • D3DXCreateVolumeTextureFromFileInMemoryEx
  • D3DXCreateVolumeTextureFromResource
  • D3DXCreateVolumeTextureFromResourceEx
  • D3DXFillCubeTexture
  • D3DXFillCubeTextureTX
  • D3DXFillTexture
  • D3DXFillTextureTX
  • D3DXFillVolumeTexture
  • D3DXFillVolumeTextureTX
  • D3DXFilterTexture
  • D3DXGetImageInfoFromFile
  • D3DXGetImageInfoFromFileInMemory
  • D3DXGetImageInfoFromResource
  • D3DXLoadSurfaceFromFile
  • D3DXLoadSurfaceFromFileInMemory
  • D3DXLoadSurfaceFromMemory
  • D3DXLoadSurfaceFromResource
  • D3DXLoadSurfaceFromSurface
  • D3DXLoadVolumeFromFile
  • D3DXLoadVolumeFromFileInMemory
  • D3DXLoadVolumeFromMemory
  • D3DXLoadVolumeFromResource
  • D3DXLoadVolumeFromVolume
  • D3DXSaveSurfaceToFile
  • D3DXSaveSurfaceToFileInMemory
  • D3DXSaveTextureToFile
  • D3DXSaveTextureToFileInMemory
  • D3DXSaveVolumeToFile
  • D3DXSaveVolumeToFileInMemory

Related Topics

  • D3DXCreateTextureGutterHelper


D3DXCheckCubeTextureRequirements Function

Checks cube-texture-creation parameters.

Syntax

HRESULT WINAPI D3DXCheckCubeTextureRequirements(

    LPDIRECT3DDEVICE9 pDevice,
    UINT *pSize,
    UINT *pNumMipLevels,
    DWORD Usage,
    D3DFORMAT *pFormat,
    D3DPOOL Pool
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the cube texture.
pSize
[in, out] Pointer to the requested width and height in pixels, or NULL. Returns the corrected size.
pNumMipLevels
[in, out] Pointer to the number of requested mipmap levels, or NULL. Returns the corrected number of mipmap levels.
Usage
[in] 0 or D3DUSAGE_RENDERTARGET. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat.
pFormat
[in, out] Pointer to a member of the D3DFORMAT enumerated type. Specifies the desired pixel format, or NULL. Returns the corrected format.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

If parameters to this function are invalid, this function returns corrected parameters.

Cube textures differ from other surfaces in that they are collections of surfaces. To call IDirect3DDevice9::SetRenderTarget with a cube texture, you must select an individual face using IDirect3DCubeTexture9::GetCubeMapSurface and pass the resulting surface to IDirect3DDevice9::SetRenderTarget.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXCheckTextureRequirements Function

Checks texture-creation parameters.

Syntax

HRESULT WINAPI D3DXCheckTextureRequirements(

    LPDIRECT3DDEVICE9 pDevice,
    UINT *pWidth,
    UINT *pHeight,
    UINT *pNumMipLevels,
    DWORD Usage,
    D3DFORMAT *pFormat,
    D3DPOOL Pool
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
pWidth
[in, out] Pointer to the requested width in pixels, or NULL. Returns the corrected size.
pHeight
[in, out] Pointer to the requested height in pixels, or NULL. Returns the corrected size.
pNumMipLevels
[in, out] Pointer to number of requested mipmap levels, or NULL. Returns the corrected number of mipmap levels.
Usage
[in] 0 or D3DUSAGE_RENDERTARGET. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTargetmethod. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat.
pFormat
[in, out] Pointer to a member of the D3DFORMAT enumerated type. Specifies the desired pixel format, or NULL. Returns the corrected format.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

If parameters to this function are invalid, this function returns corrected parameters.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXCheckVolumeTextureRequirements Function

Checks volume-texture-creation parameters.

Syntax

HRESULT WINAPI D3DXCheckVolumeTextureRequirements(

    LPDIRECT3DDEVICE9 pDevice,
    UINT *pWidth,
    UINT *pHeight,
    UINT *pDepth,
    UINT *pNumMipLevels,
    DWORD Usage,
    D3DFORMAT *pFormat,
    D3DPOOL Pool
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the volume texture.
pWidth
[in, out] Pointer to the requested width in pixels, or NULL. Returns the corrected size.
pHeight
[in, out] Pointer to the requested height in pixels, or NULL. Returns the corrected size.
pDepth
[in, out] Pointer to the requested depth in pixels, or NULL. Returns the corrected size.
pNumMipLevels
[in, out] Pointer to the number of requested mipmap levels, or NULL. Returns the corrected number of mipmap levels.
Usage
[in] Currently not used, set to 0.
pFormat
[in, out] Pointer to a member of the D3DFORMAT enumerated type. Specifies the desired pixel format, or NULL. Returns the corrected format.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the volume texture should be placed.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

If parameters to this function are invalid, this function returns corrected parameters.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXComputeNormalMap Function

Converts a height map into a normal map. The (x,y,z) components of each normal are mapped to the (r,g,b) channels of the output texture.

Syntax

HRESULT WINAPI D3DXComputeNormalMap(

    LPDIRECT3DTEXTURE9 pTexture,
    LPDIRECT3DTEXTURE9 pSrcTexture,
    const PALETTEENTRY *pSrcPalette,
    DWORD Flags,
    DWORD Channel,
    FLOAT Amplitude
);

Parameters

pTexture
[out, retval] Pointer to an IDirect3DTexture9 interface, representing the destination texture.
pSrcTexture
[in, retval] Pointer to an IDirect3DTexture9 interface, representing the source height-map texture.
pSrcPalette
[in] Pointer to a PALETTEENTRY type that contains the source palette of 256 colors or NULL.
Flags
[in] One or more D3DX_NORMALMAP flags that control generation of normal maps.
Channel
[in, out] One D3DX_CHANNEL flag specifying the source of height information.
Amplitude
[in] Constant value multiplier that increases (or decreases) the values in the normal map. Higher values usually make bumps more visible, lower values usually make bumps less visible.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be the following value:

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This method computes the normal by using the central difference with a kernel size of 3x3. RGB channels in the destination contain biased (x,y,z) components of the normal.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXCreateCubeTexture Function

Creates an empty cube texture, adjusting the calling parameters as needed.

Syntax

HRESULT WINAPI D3DXCreateCubeTexture(

    LPDIRECT3DDEVICE9 pDevice,
    UINT Size,
    UINT MipLevels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    LPDIRECT3DCUBETEXTURE9 *ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
Size
[in] Width and height of the cube texture, in pixels. For example, if the cube texture is an 8-pixel by 8-pixel cube, the value for this parameter should be 8.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the cube texture. The returned cube texture might have a different format from that specified by Format. Applications should check the format of the returned cube texture.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the cube texture should be placed.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture9 interface, representing the created cube texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Cube textures differ from other surfaces in that they are collections of surfaces.

Internally, D3DXCreateCubeTexture uses D3DXCheckCubeTextureRequirements to adjust the calling parameters. Therefore, calls to D3DXCreateCubeTexture will often succeed where calls to IDirect3DDevice9::CreateCubeTexture would fail.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Texture Support in D3DX


D3DXCreateCubeTextureFromFile Function

Creates a cube texture from a file.

Syntax

HRESULT WINAPI D3DXCreateCubeTextureFromFile(

    LPDIRECT3DDEVICE9 pDevice,
    LPCTSTR pSrcFile,
    LPDIRECT3DCUBETEXTURE9 *ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the cube texture.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture9 interface, representing the created cube texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateCubeTextureFromFileW. Otherwise, the function call resolves to D3DXCreateCubeTextureFromFileA because ANSI strings are being used.

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

D3DXCreateCubeTextureFromFile uses the Microsoft DirectDraw surface (DDS) file format. The DXTex enables you to generate a cube map from other file formats and save it in the DDS file format.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateCubeTextureFromFileEx, Texture Support in D3DX


D3DXCreateCubeTextureFromFileEx Function

Creates a cube texture from a file. This is a more advanced function than D3DXCreateCubeTextureFromFile.

Syntax

HRESULT WINAPI D3DXCreateCubeTextureFromFileEx(

    LPDIRECT3DDEVICE9 pDevice,
    LPCTSTR pSrcFile,
    UINT Size,
    UINT MipLevels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    DWORD Filter,
    DWORD MipFilter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO *pSrcInfo,
    PALETTEENTRY *pPalette,
    LPDIRECT3DCUBETEXTURE9 *ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the cube texture.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Size
[in] Width and height of the cube texture, in pixels. For example, if the cube texture is an 8-pixel by 8-pixel cube, the value for this parameter should be 8. If this value is 0 or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0 or D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. D3DUSAGE_DYNAMIC indicates that the surface should be handled dynamically. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the cube texture. The returned cube texture might have a different format from that specified by Format. Applications should check the format of the returned cube texture. If D3DFMT_UNKNOWN, the format is taken from the file. If D3DFMT_FROM_FILE, the format is taken exactly as it is in the file, and the call will fail if this violates device capabilities.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the cube texture should be placed.
Filter
[in] A combination of one or more D3DX_FILTER, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
MipFilter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant, and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture9 interface, representing the created cube texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateCubeTextureFromFileExW. Otherwise, the function call resolves to D3DXCreateCubeTextureFromFileExA because ANSI strings are being used.

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Cube textures differ from other surfaces in that they are collections of surfaces. To call IDirect3DDevice9::SetRenderTarget with a cube texture, you must select an individual face using IDirect3DCubeTexture9::GetCubeMapSurface and pass the resulting surface to IDirect3DDevice9::SetRenderTarget.

D3DXCreateCubeTextureFromFileEx uses the Microsoft DirectDraw surface (DDS) file format. The DXTex enables you to generate a cube map from other file formats and save it in the DDS file format.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateCubeTextureFromFile, Texture Support in D3DX


D3DXCreateCubeTextureFromFileInMemory Function

Creates a cube texture from a file in memory.

Syntax

HRESULT WINAPI D3DXCreateCubeTextureFromFileInMemory(

    LPDIRECT3DDEVICE9 pDevice,
    LPCVOID pSrcData,
    UINT SrcDataSize,
    LPDIRECT3DCUBETEXTURE9 *ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the cube texture.
pSrcData
[in] Pointer to the file in memory from which to create the cubemap. See Remarks.
SrcDataSize
[in] Size of the file in memory, in bytes.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture9 interface, representing the created cube texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

This method is designed to be used for loading image files stored as RT_RCDATA, which is an application-defined resource (raw data). Otherwise this method will fail.

D3DXCreateCubeTextureFromFileInMemory uses the Microsoft DirectDraw surface (DDS) file format. The DXTex enables you to generate a cube map from other file formats and save it in the DDS file format.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Texture Support in D3DX


D3DXCreateCubeTextureFromFileInMemoryEx Function

Creates a cube texture from a file in memory. This is a more advanced function than D3DXCreateCubeTextureFromFileInMemory.

Syntax

HRESULT WINAPI D3DXCreateCubeTextureFromFileInMemoryEx(

    LPDIRECT3DDEVICE9 pDevice,
    LPCVOID pSrcData,
    UINT SrcDataSize,
    UINT Size,
    UINT MipLevels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    DWORD Filter,
    DWORD MipFilter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO *pSrcInfo,
    PALETTEENTRY *pPalette,
    LPDIRECT3DCUBETEXTURE9 *ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the cube texture.
pSrcData
[in] Pointer to the file in memory from which to create the cube texture. See Remarks.
SrcDataSize
[in] Size of the file in memory, in bytes.
Size
[in] Width (or height) in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the cube texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If D3DFMT_UNKNOWN, the format is taken from the file. If D3DFMT_FROM_FILE, the format is taken exactly as it is in the file, and the call will fail if this violates device capabilities.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the cube texture should be placed.
Filter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
MipFilter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant, and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL. See Remarks.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture9 interface, representing the created cube texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Cube textures differ from other surfaces in that they are collections of surfaces. To call IDirect3DDevice9::SetRenderTarget with a cube texture, you must select an individual face using IDirect3DCubeTexture9::GetCubeMapSurface and pass the resulting surface to IDirect3DDevice9::SetRenderTarget .

This method is designed to be used for loading image files stored as RT_RCDATA, which is an application-defined resource (raw data). Otherwise this method will fail.

For details on PALETTEENTRY, see the Microsoft Platform Software Development Kit (SDK). Note that as of Microsoft DirectX 8.0, the peFlags member of the PALETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

D3DXCreateCubeTextureFromFileInMemoryEx uses the Microsoft DirectDraw surface (DDS) file format. The DXTex enables you to generate a cube map from other file formats and save it in the DDS file format

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Texture Support in D3DX


D3DXCreateCubeTextureFromResource Function

Creates a cube texture from a resource.

Syntax

HRESULT WINAPI D3DXCreateCubeTextureFromResource(

    LPDIRECT3DDEVICE9 pDevice,
    HMODULE hSrcModule,
    LPCTSTR pSrcResource,
    LPDIRECT3DCUBETEXTURE9 *ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the cube texture.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for the module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture9 interface, representing the created cube texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting determines the function version. If Unicode is defined, the function call resolves to D3DXCreateCubeTextureFromResourceW. Otherwise, the function call resolves to D3DXCreateCubeTextureFromResourceA because ANSI strings are being used.

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

D3DXCreateCubeTextureFromResource uses the Microsoft DirectDraw surface (DDS) file format. The DXTex enables you to generate a cube map from other file formats and save it in the DDS file format.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateCubeTextureFromResourceEx, Texture Support in D3DX


D3DXCreateCubeTextureFromResourceEx Function

Creates a cube texture from a resource specified by a string. This is a more advanced function than D3DXCreateCubeTextureFromResource.

Syntax

HRESULT WINAPI D3DXCreateCubeTextureFromResourceEx(

    LPDIRECT3DDEVICE9 pDevice,
    HMODULE hSrcModule,
    LPCTSTR pSrcResource,
    UINT Size,
    UINT MipLevels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    DWORD Filter,
    DWORD MipFilter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO *pSrcInfo,
    PALETTEENTRY *pPalette,
    LPDIRECT3DCUBETEXTURE9 *ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the cube texture.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for the module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Size
[in] Width and height of the cube texture, in pixels. For example, if the cube texture is an 8-pixel by 8-pixel cube, the value for this parameter should be 8. If this value is 0 or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0 or D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. D3DUSAGE_DYNAMIC indicates that the surface should be handled dynamically. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the cube texture. The returned cube texture might have a different format from that specified by Format. Applications should check the format of the returned cube texture. If D3DFMT_UNKNOWN, the format is taken from the file. If D3DFMT_FROM_FILE, the format is taken exactly as it is in the file, and the call will fail if this violates device capabilities.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the cube texture should be placed.
Filter
[in] A combination of one or more D3DX_FILTER, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
MipFilter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant, and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in or NULL.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture9 interface, representing the created cube texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting determines the function version. If Unicode is defined, the function call resolves to D3DXCreateCubeTextureFromResourceExW. Otherwise, the function call resolves to D3DXCreateCubeTextureFromResourceExA because ANSI strings are being used.

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Cube textures differ from other surfaces in that they are collections of surfaces. To call IDirect3DDevice9::SetRenderTarget with a cube texture, you must select an individual face using IDirect3DCubeTexture9::GetCubeMapSurface and pass the resulting surface to IDirect3DDevice9::SetRenderTarget.

D3DXCreateCubeTextureFromResourceEx uses the Microsoft DirectDraw surface (DDS) file format. The DXTex enables you to generate a cube map from other file formats and save it in the DDS file format.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateCubeTextureFromResource, Texture Support in D3DX


D3DXCreateTexture Function

Creates an empty texture, adjusting the calling parameters as needed.

Syntax

HRESULT WINAPI D3DXCreateTexture(

    LPDIRECT3DDEVICE9 pDevice,
    UINT Width,
    UINT Height,
    UINT MipLevels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    LPDIRECT3DTEXTURE9 *ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
Width
[in] Width in pixels. If this value is 0, a value of 1 is used. See Remarks.
Height
[in] Height in pixels. If this value is 0, a value of 1 is used. See Remarks.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget" parameter of the IDirect3DDevice9::SetRenderTarget method. If either D3DUSAGE_RENDERTARGET or D3DUSAGE_DYNAMIC is specified, the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture may be a different format from that specified, if the device does not support the requested format. Applications should check the format of the returned texture to see if it matches the format requested.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
ppTexture
[out] Address of a pointer to an IDirect3DTexture9 interface, representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Internally, D3DXCreateTexture uses D3DXCheckTextureRequirements to adjust the calling parameters. Therefore, calls to D3DXCreateTexture will often succeed where calls to IDirect3DDevice9::CreateTexture would fail.

If both Height and Width are set to D3DX_DEFAULT, a value of 256 is used for both parameters. If Height and Width are set to D3DX_DEFAULT and the other parameter is set to a numeric value, the texture is square, with the height and width of the texture equal to the numeric value.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Texture Support in D3DX


D3DXCreateTextureFromFile Function

Creates a texture from a file.

Syntax

HRESULT WINAPI D3DXCreateTextureFromFile(

    LPDIRECT3DDEVICE9 pDevice,
    LPCTSTR pSrcFile,
    LPDIRECT3DTEXTURE9 *ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
ppTexture
[out] Address of a pointer to an IDirect3DTexture9 interface, representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateTextureFromFileW. Otherwise, the function call resolves to D3DXCreateTextureFromFileA because ANSI strings are being used.

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

The function is equivalent to D3DXCreateTextureFromFileExW(pDevice, pSrcFile, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, ppTexture).

Mipmapped textures automatically have each level filled with the loaded texture.

When loading images into mipmapped textures, some devices are unable to go to a 1x1 image and this function will fail. If this happens, the images need to be loaded manually.

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

For the best performance when using D3DXCreateTextureFromFile:

  1. Doing image scaling and format conversion at load time can be slow. Store images in the format and resolution they will be used. If the target hardware requires power of two dimensions, create and store images using power of two dimensions.
  2. Consider using Microsoft DirectDraw surface (DDS) files. Because DDS files can be used to represent any Microsoft DirectX 9.0 texture format, they are very easy for D3DX to read. Also, they can store mipmaps, so any mipmap-generation algorithms can be used to author the images.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateTextureFromFileEx, Texture Support in D3DX


D3DXCreateTextureFromFileEx Function

Creates a texture from a file. This is a more advanced function than D3DXCreateTextureFromFile.

Syntax

HRESULT WINAPI D3DXCreateTextureFromFileEx(

    LPDIRECT3DDEVICE9 pDevice,
    LPCTSTR pSrcFile,
    UINT Width,
    UINT Height,
    UINT MipLevels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    DWORD Filter,
    DWORD MipFilter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO *pSrcInfo,
    PALETTEENTRY *pPalette,
    LPDIRECT3DTEXTURE9 *ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Width
[in] Width in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file and rounded up to a power of two. If the device supports non-power of 2 textures and D3DX_DEFAULT_NONPOW2 is specified, the size will not be rounded.
Height
[in] Height, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file and rounded up to a power of two. If the device supports non-power of 2 textures and D3DX_DEFAULT_NONPOW2 is sepcified, the size will not be rounded.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created. If D3DX_FROM_FILE, the size will be taken exactly as it is in the file, and the call will fail if this violates device capabilities.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If either D3DUSAGE_RENDERTARGET or D3DUSAGE_DYNAMIC is specified, Pool must be set to D3DPOOL_DEFAULT, and the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. D3DUSAGE_DYNAMIC indicates that the surface should be handled dynamically. See Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If D3DFMT_UNKNOWN, the format is taken from the file. If D3DFMT_FROM_FILE, the format is taken exactly as it is in the file, and the call will fail if this violates device capabilities.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
Filter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
MipFilter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the color key. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled in with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL.
ppTexture
[out] Address of a pointer to an IDirect3DTexture9 interface, representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Direct3D does not have enough display memory to perform the operation.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateTextureFromFileExW. Otherwise, the function call resolves to D3DXCreateTextureFromFileExA because ANSI strings are being used.

Use D3DXCheckTextureRequirements to determine if your device can support the texture given the current state.

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Mipmapped textures automatically have each level filled with the loaded texture. When loading images into mipmapped textures, some devices are unable to go to a 1x1 image and this function will fail. If this happens, then the images need to be loaded manually.

For the best performance when using D3DXCreateTextureFromFileEx:

  1. Doing image scaling and format conversion at load time can be slow. Store images in the format and resolution they will be used. If the target hardware requires power of 2 dimensions, then create and store images using power of 2 dimensions.
  2. For mipmap image creation at load time, filter using D3DX_FILTER_BOX. A box filter is much faster than other filter types such as D3DX_FILTER_TRIANGLE.
  3. Consider using DDS files. Since DDS files can be used to represent any Microsoft DirectX 9.0 texture format, they are very easy for D3DX to read. Also, they can store mipmaps, so any mipmap-generation algorithms can be used to author the images.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateTextureFromFile, Texture Support in D3DX


D3DXCreateTextureFromFileInMemory Function

Creates a texture from a file in memory.

Syntax

HRESULT WINAPI D3DXCreateTextureFromFileInMemory(

    LPDIRECT3DDEVICE9 pDevice,
    LPCVOID pSrcData,
    UINT SrcDataSize,
    LPDIRECT3DTEXTURE9 *ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface representing the device to be associated with the texture.
pSrcData
[in] Pointer to the file in memory from which to create the texture.
SrcDataSize
[in] Size in bytes of the file in memory.
ppTexture
[out] Address of a pointer to an IDirect3DTexture9 interface representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateTextureFromFileInMemoryEx, Texture Support in D3DX


D3DXCreateTextureFromFileInMemoryEx Function

Creates a texture from a file in memory. This is a more advanced function than D3DXCreateTextureFromFileInMemory.

Syntax

HRESULT WINAPI D3DXCreateTextureFromFileInMemoryEx(

    LPDIRECT3DDEVICE9 pDevice,
    LPCVOID pSrcData,
    UINT SrcDataSize,
    UINT Width,
    UINT Height,
    UINT MipLevels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    DWORD Filter,
    DWORD MipFilter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO *pSrcInfo,
    PALETTEENTRY *pPalette,
    LPDIRECT3DTEXTURE9 *ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
pSrcData
[in] Pointer to the file in memory from which to create the texture.
SrcDataSize
[in] Size of the file in memory, in bytes.
Width
[in] Width in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
Height
[in] Height, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If either D3DUSAGE_RENDERTARGET or D3DUSAGE_DYNAMIC is specified, Pool must be set to D3DPOOL_DEFAULT, and the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If D3DFMT_UNKNOWN, the format is taken from the file. If D3DFMT_FROM_FILE, the format is taken exactly as it is in the file, and the call will fail if this violates device capabilities.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
Filter
[in] Combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER. Each valid filter must contain one of the flags in D3DX_FILTER.
MipFilter
[in] Combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX. Each valid filter must contain one of the flags in D3DX_FILTER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL. See Remarks.
ppTexture
[out] Address of a pointer to an IDirect3DTexture9 interface, representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

For details about PALETTEENTRY, see the Microsoft Platform Software Development Kit (SDK). Note that as of Microsoft DirectX 8.0, the peFlags member of the PALETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateTextureFromFileInMemory, Texture Support in D3DX


D3DXCreateTextureFromResource Function

Creates a texture from a resource.

Syntax

HRESULT WINAPI D3DXCreateTextureFromResource(

    LPDIRECT3DDEVICE9 pDevice,
    HMODULE hSrcModule,
    LPCTSTR pSrcResource,
    LPDIRECT3DTEXTURE9 *ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
ppTexture
[out] Address of a pointer to an IDirect3DTexture9 interface, representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateTextureFromResourceW. Otherwise, the function call resolves to D3DXCreateTextureFromResourceA because ANSI strings are being used.

The resource being loaded must be of type RT_BITMAP or RT_RCDATA. Resource type RT_RCDATA is used to load formats other than bitmaps (such as .tga, .jpg, and .dds).

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateTextureFromResourceEx, Texture Support in D3DX


D3DXCreateTextureFromResourceEx Function

Creates a texture from a resource. This is a more advanced function than D3DXCreateTextureFromResource.

Syntax

HRESULT WINAPI D3DXCreateTextureFromResourceEx(

    LPDIRECT3DDEVICE9 pDevice,
    HMODULE hSrcModule,
    LPCTSTR pSrcResource,
    UINT Width,
    UINT Height,
    UINT MipLevels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    DWORD Filter,
    DWORD MipFilter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO *pSrcInfo,
    PALETTEENTRY *pPalette,
    LPDIRECT3DTEXTURE9 *ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Width
[in] Width in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
Height
[in] Height, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If either D3DUSAGE_RENDERTARGET or D3DUSAGE is specified, Pool must be set to D3DPOOL_DEFAULT, and the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. D3DUSAGE_DYNAMIC indicates that the surface should be handled dynamically. For more information about using dynamic textures, see Performance OptimizationsUsing Dynamic Textures.
Format
[in] A member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If D3DFMT_UNKNOWN, the format is taken from the file. If D3DFMT_FROM_FILE, the format is taken exactly as it is in the file, and the call will fail if this violates device capabilities.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
Filter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
MipFilter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in or NULL.
ppTexture
[out] Address of a pointer to an IDirect3DTexture9 interface, representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateTextureFromResourceExW. Otherwise, the function call resolves to D3DXCreateTextureFromResourceExA because ANSI strings are being used.

The resource being loaded must be of type RT_BITMAP or RT_RCDATA. Resource type RT_RCDATA is used to load formats other than bitmaps (such as .tga, .jpg, and .dds).

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateTextureFromResource, Texture Support in D3DX


D3DXCreateVolumeTexture Function

Creates an empty volume texture, adjusting the calling parameters as needed.

Syntax

HRESULT WINAPI D3DXCreateVolumeTexture(

    LPDIRECT3DDEVICE9 pDevice,
    UINT Width,
    UINT Height,
    UINT Depth,
    UINT MipLevels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    LPDIRECT3DVOLUMETEXTURE9 *ppVolumeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the volume texture.
Width
[in] Width in pixels. This value must be nonzero. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
Height
[in] Height in pixels. This value must be nonzero. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
Depth
[in] Depth in pixels. This value must be nonzero. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0 or D3DUSAGE_DYNAMIC. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the volume texture. The returned volume texture might have a different format from that specified by Format. Applications should check the format of the returned volume texture.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the volume texture should be placed.
ppVolumeTexture
[out] Address of a pointer to an IDirect3DVolumeTexture9 interface, representing the created volume texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Internally, D3DXCreateVolumeTexture uses D3DXCheckVolumeTextureRequirements to adjust the calling parameters. Therefore, calls to D3DXCreateVolumeTexture will often succeed where calls to IDirect3DDevice9::CreateVolumeTexture would fail.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Texture Support in D3DX


D3DXCreateVolumeTextureFromFile Function

Creates a volume texture from a file.

Syntax

HRESULT WINAPI D3DXCreateVolumeTextureFromFile(

    LPDIRECT3DDEVICE9 pDevice,
    LPCTSTR pSrcFile,
    LPDIRECT3DVOLUMETEXTURE9 *ppVolumeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the volume texture.
pSrcFile
[in] Pointer to a string that specifies the file name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
ppVolumeTexture
[out] Address of a pointer to an IDirect3DVolumeTexture9 interface representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateVolumeTextureFromFileW. Otherwise, the function call resolves to D3DXCreateVolumeTextureFromFileA because ANSI strings are being used.

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Mipmapped textures automatically have each level filled with the loaded texture.

When loading images into mipmapped textures, some devices are unable to go to a 1x1 image and this function will fail. If this happens, then the images need to be loaded manually.

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateVolumeTextureFromFileEx, D3DXCreateVolumeTextureFromFileInMemory, D3DXCreateVolumeTextureFromFileInMemoryEx, D3DXCreateVolumeTextureFromResource, D3DXCreateVolumeTextureFromResourceEx, Texture Support in D3DX


D3DXCreateVolumeTextureFromFileEx Function

Creates a volume texture from a file.

Syntax

HRESULT WINAPI D3DXCreateVolumeTextureFromFileEx(

    LPDIRECT3DDEVICE9 pDevice,
    LPCTSTR pSrcFile,
    UINT Width,
    UINT Height,
    UINT Depth,
    UINT MipLevels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    DWORD Filter,
    DWORD MipFilter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO *pSrcInfo,
    PALETTEENTRY *pPalette,
    LPDIRECT3DVOLUMETEXTURE9 *ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Width
[in] Width in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
Height
[in] Height, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
Depth
[in] Depth, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If either D3DUSAGE_RENDERTARGET or D3DUSAGE_DYNAMIC is specified, Pool must be set to D3DPOOL_DEFAULT, and the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. D3DUSAGE_DYNAMIC indicates that the surface should be handled dynamically. For more information about using dynamic textures, see Using Dynamic Textures.
Format
Member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If D3DFMT_UNKNOWN, the format is taken from the file. If D3DFMT_FROM_FILE, the format is taken exactly as it is in the file, and the call will fail if this violates device capabilities.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
Filter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
MipFilter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled in with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL.
ppTexture
[out] Address of a pointer to an IDirect3DVolumeTexture9 interface, representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateVolumeTextureFromFileExW. Otherwise, the function call resolves to D3DXCreateVolumeTextureFromFileExA because ANSI strings are being used.

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Mipmapped textures automatically have each level filled with the loaded volume texture. When loading images into mipmapped textures, some devices are unable to go to a 1x1 image and this function will fail. If this happens, then the images need to be loaded manually.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateVolumeTextureFromFile, D3DXCreateVolumeTextureFromFileInMemory, D3DXCreateVolumeTextureFromFileInMemoryEx, D3DXCreateVolumeTextureFromResource, D3DXCreateVolumeTextureFromResourceEx, Texture Support in D3DX


D3DXCreateVolumeTextureFromFileInMemory Function

Creates a volume texture from a file in memory.

Syntax

HRESULT WINAPI D3DXCreateVolumeTextureFromFileInMemory(

    LPDIRECT3DDEVICE9 pDevice,
    LPCVOID pSrcFile,
    UINT SrcData,
    LPDIRECT3DVOLUMETEXTURE9 ppVolumeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the volume texture.
pSrcFile
[in] Pointer to the file in memory from which to create the volume texture.
SrcData
[in] Size of the file in memory, in bytes.
ppVolumeTexture
[out] Address of a pointer to an IDirect3DVolumeTexture9 interface, representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateVolumeTextureFromFile, D3DXCreateVolumeTextureFromFileEx, D3DXCreateVolumeTextureFromFileInMemoryEx, D3DXCreateVolumeTextureFromResource, D3DXCreateVolumeTextureFromResourceEx, Texture Support in D3DX


D3DXCreateVolumeTextureFromFileInMemoryEx Function

Creates a volume texture from a file. This is a more advanced function than D3DXCreateVolumeTextureFromFileInMemory.

Syntax

HRESULT WINAPI D3DXCreateVolumeTextureFromFileInMemoryEx(

    LPDIRECT3DDEVICE9 pDevice,
    LPCVOID pSrcData,
    UINT SrcDataSize,
    UINT Width,
    UINT Height,
    UINT Depth,
    UINT MipLevels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    DWORD Filter,
    DWORD MipFilter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO *pSrcInfo,
    PALETTEENTRY *pPalette,
    LPDIRECT3DVOLUMETEXTURE9 *ppVolumeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
pSrcData
[in] Pointer to the file in memory from which to create the volume texture.
SrcDataSize
[in] Size of the file in memory, in bytes.
Width
[in] Width in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
Height
[in] Height, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
Depth
[in] Depth, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If either D3DUSAGE_RENDERTARGET or D3DUSAGE_DYNAMIC is specified, Pool must be set to D3DPOOL_DEFAULT, and the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. D3DUSAGE_DYNAMIC indicates that the surface should be handled dynamically. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If D3DFMT_UNKNOWN, the format is taken from the file. If D3DFMT_FROM_FILE, the format is taken exactly as it is in the file, and the call will fail if this violates device capabilities.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
Filter
[in] Combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
MipFilter
[in] Combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled in with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL.
ppVolumeTexture
[out] Address of a pointer to an IDirect3DVolumeTexture9 interface, representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateVolumeTextureFromFile, D3DXCreateVolumeTextureFromFileEx, D3DXCreateVolumeTextureFromFileInMemory, D3DXCreateVolumeTextureFromResource, D3DXCreateVolumeTextureFromResourceEx, Texture Support in D3DX


D3DXCreateVolumeTextureFromResource Function

Creates a volume texture from a resource.

Syntax

HRESULT WINAPI D3DXCreateVolumeTextureFromResource(

    LPDIRECT3DDEVICE9 pDevice,
    HMODULE hSrcModule,
    LPCTSTR pSrcResource,
    LPDIRECT3DVOLUMETEXTURE9 *ppVolumeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the volume texture.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for the module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
ppVolumeTexture
[out] Address of a pointer to an IDirect3DVolumeTexture9 interface representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateVolumeTextureFromResourceW. Otherwise, the function call resolves to D3DXCreateVolumeTextureFromResourceA because ANSI strings are being used.

The resource being loaded must be an application-defined resource (RT_RCDATA).

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateVolumeTextureFromFile, D3DXCreateVolumeTextureFromFileEx, D3DXCreateVolumeTextureFromFileInMemory, D3DXCreateVolumeTextureFromFileInMemoryEx, D3DXCreateVolumeTextureFromResourceEx, Texture Support in D3DX


D3DXCreateVolumeTextureFromResourceEx Function

Creates a volume texture from a resource specified by a string. This is a more advanced function than D3DXCreateVolumeTextureFromResource.

Syntax

HRESULT WINAPI D3DXCreateVolumeTextureFromResourceEx(

    LPDIRECT3DDEVICE9 pDevice,
    HMODULE hSrcModule,
    LPCTSTR pSrcResource,
    UINT Width,
    UINT Height,
    UINT Depth,
    UINT MipLevels,
    DWORD Usage,
    D3DFORMAT Format,
    D3DPOOL Pool,
    DWORD Filter,
    DWORD MipFilter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO *pSrcInfo,
    PALETTEENTRY *pPalette,
    LPDIRECT3DVOLUMETEXTURE9 *ppVolumeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Width
[in] Width in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
Height
[in] Height, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
Depth
[in] Depth, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file. The maximum dimension that a driver supports (for width, height, and depth) can be found in MaxVolumeExtent in D3DCAPS9.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If either D3DUSAGE_RENDERTARGET or D3DUSAGE_DYNAMIC is specified, Pool must be set to D3DPOOL_DEFAULT, and the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. D3DUSAGE_DYNAMIC indicates that the surface should be handled dynamically. For more information about using dynamic textures, see Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If D3DFMT_UNKNOWN, the format is taken from the file. If D3DFMT_FROM_FILE, the format is taken exactly as it is in the file, and the call will fail if this violates device capabilities.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
Filter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
MipFilter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled in with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL.
ppVolumeTexture
[out] Address of a pointer to an IDirect3DVolumeTexture9 interface, representing the created texture object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_OUTOFVIDEOMEMORY | Microsoft Direct3D does not have enough display memory to perform the operation.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateVolumeTextureFromResourceExW. Otherwise, the function call resolves to D3DXCreateVolumeTextureFromResourceExA because ANSI strings are being used.

The resource being loaded must be an application-defined resource (RT_RCDATA).

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateVolumeTextureFromFile, D3DXCreateVolumeTextureFromFileEx, D3DXCreateVolumeTextureFromFileInMemory, D3DXCreateVolumeTextureFromFileInMemoryEx, D3DXCreateVolumeTextureFromResource, Texture Support in D3DX


D3DXFillCubeTexture Function

Uses a user-provided function to fill each texel of each mip level of a given cube texture.

Syntax

HRESULT WINAPI D3DXFillCubeTexture(

    LPDIRECT3DCUBETEXTURE9 pTexture,
    LPD3DXFILL3D pFunction,
    LPVOID pData
);

Parameters

pTexture
[out, retval] Pointer to an IDirect3DCubeTexture9 interface, representing the filled texture.
pFunction
[in] Pointer to a user-provided evaluator function, which will be used to compute the value of each texel. The function follows the prototype of LPD3DXFILL3D.
pData
[in] Pointer to an arbitrary block of user-defined data. This pointer will be passed to the function provided in pFunction.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

Here is an example that creates a function called ColorCubeFill, which relies on D3DXFillCubeTexture.

// Define a function that matches the prototype of LPD3DXFILL3D
VOID WINAPI ColorCubeFill (D3DXVECTOR4* pOut, const D3DXVECTOR3* pTexCoord,
const D3DXVECTOR3* pTexelSize, LPVOID pData)
{
   *pOut = D3DXVECTOR4(pTexCoord->x, pTexCoord->y, pTexCoord->z, 0.0f);
}

// Fill the texture using D3DXFillCubeTexture
if (FAILED (hr = D3DXFillCubeTexture (m_pTexture, ColorCubeFill, NULL)))
{
       return hr;
}

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXFillCubeTextureTX Function

Uses a compiled high-level shader language (HLSL) function to fill each texel of each mipmap level of a texture.

Syntax

HRESULT WINAPI D3DXFillCubeTextureTX(

    LPDIRECT3DCUBETEXTURE9 pTexture,
    LPD3DXTEXTURESHADER pTextureShader
);

Parameters

pTexture
[in] Pointer to an IDirect3DCubeTexture9 object, representing the texture to be filled.
pTextureShader
[in] Pointer to a ID3DXTextureShader texture shader object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The texture target must be an HLSL function that takes contains the following semantics:

  • One input parameter must use a POSITION semantic.
  • One input parameter must use a PSIZE semantic.
  • The function must return a parameter that uses the COLOR semantic.

The input parameters can be in any order. For an example, see D3DXFillTextureTX

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXFillVolumeTextureTX


D3DXFillTexture Function

Uses a user-provided function to fill each texel of each mip level of a given texture.

Syntax

HRESULT WINAPI D3DXFillTexture(

    LPDIRECT3DTEXTURE9 pTexture,
    LPD3DXFILL2D pFunction,
    LPVOID pData
);

Parameters

pTexture
[out, retval] Pointer to an IDirect3DTexture9 interface, representing the filled texture.
pFunction
[in] Pointer to a user-provided evaluator function, which will be used to compute the value of each texel. The function follows the prototype of LPD3DXFILL2D.
pData
[in] Pointer to an arbitrary block of user-defined data. This pointer will be passed to the function provided in pFunction.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

Here is an example that creates a function called ColorFill, which relies on D3DXFillTexture.

// Define a function that matches the prototype of LPD3DXFILL3D
VOID WINAPI ColorFill (D3DXVECTOR4* pOut, const D3DXVECTOR2* pTexCoord,
const D3DXVECTOR2* pTexelSize, LPVOID pData)
{
   *pOut = D3DXVECTOR4(pTexCoord->x, pTexCoord->y, 0.0f, 0.0f);
}

// Fill the texture using D3DXFillTexture
if (FAILED (hr = D3DXFillTexture (m_pTexture, ColorFill, NULL)))
{
       return hr;
}

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXFillTextureTX Function

Uses a compiled high-level shader language (HLSL) function to fill each texel of each mipmap level of a texture.

Syntax

HRESULT WINAPI D3DXFillTextureTX(

    LPDIRECT3DTEXTURE9 pTexture,
    LPD3DXTEXTURESHADER pTextureShader
);

Parameters

pTexture
[in, out] Pointer to an IDirect3DTexture9 object, representing the texture to be filled.
pTextureShader
[in] Pointer to a ID3DXTextureShader texture shader object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The texture target must be an HLSL function that takes contains the following semantics:

  • One input parameter must use a POSITION semantic.
  • One input parameter must use a PSIZE semantic.
  • The function must return a parameter that uses the COLOR semantic.

The following is an example of such an HLSL function:

float4 TextureGradientFill(
  float2 vTexCoord : POSITION,
  float2 vTexelSize : PSIZE) : COLOR
  {
    float r,g, b, xSq,ySq, a;
    xSq = 2.f*vTexCoord.x-1.f; xSq *= xSq;
    ySq = 2.f*vTexCoord.y-1.f; ySq *= ySq;
    a = sqrt(xSq+ySq);
    if (a > 1.0f) {
        a = 1.0f-(a-1.0f);
    }
    else if (a < 0.2f) {
        a = 0.2f;
    }
    r = 1-vTexCoord.x;
    g = 1-vTexCoord.y;
    b = vTexCoord.x;
    return float4(r, g, b, a);

  };

Note that the input parameters can be in any order, but both input semantics must be represented.

EffectEdit Sample demonstrates the use of this function.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXFillCubeTextureTX, D3DXFillVolumeTextureTX


D3DXFillVolumeTexture Function

Uses a user-provided function to fill each texel of each mip level of a given volume texture.

Syntax

HRESULT WINAPI D3DXFillVolumeTexture(

    LPDIRECT3DVOLUMETEXTURE9 pTexture,
    LPD3DXFILL3D pFunction,
    LPVOID pData
);

Parameters

pTexture
[out, retval] Pointer to an IDirect3DVolumeTexture9 interface, representing the filled texture.
pFunction
[in] Pointer to a user-provided evaluator function, which will be used to compute the value of each texel. The function follows the prototype of LPD3DXFILL3D.
pData
[in] Pointer to an arbitrary block of user-defined data. This pointer will be passed to the function provided in pFunction.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

If the volume is non-dynamic (because usage is set to 0 when it is created), and located in video memory (the memory pool set to D3DPOOL_DEFAULT), D3DXFillVolumeTexture will fail because the volume cannot be locked.

This example creates a function called ColorVolumeFill, which relies on D3DXFillVolumeTexture.

// Define a function that matches the prototype of LPD3DXFILL3D
VOID WINAPI ColorVolumeFill (D3DXVECTOR4* pOut, const D3DXVECTOR3* pTexCoord,
const D3DXVECTOR3* pTexelSize, LPVOID pData)
{
   *pOut = D3DXVECTOR4(pTexCoord->x, pTexCoord->y, pTexCoord->z, 0.0f);
}

// Fill volume texture
if (FAILED (hr = D3DXFillVolumeTexture (m_pTexture, ColorVolumeFill, NULL)))
{
       return hr;
}

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXFillVolumeTextureTX Function

Uses a compiled high-level shader language (HLSL) function to fill each texel of each mipmap level of a texture.

Syntax

HRESULT WINAPI D3DXFillVolumeTextureTX(

    LPDIRECT3DVOLUMETEXTURE9 pTexture,
    LPD3DXTEXTURESHADER pTextureShader
);

Parameters

pTexture
[in] Pointer to an IDirect3DVolumeTexture9 object, representing the texture to be filled.
pTextureShader
[in] Pointer to a ID3DXTextureShader texture shader object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_NOTAVAILABLE | This device does not support the queried technique.
D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The texture target must be an HLSL function that takes contains the following semantics:

  • One input parameter must use a POSITION semantic.
  • One input parameter must use a PSIZE semantic.
  • The function must return a parameter that uses the COLOR semantic.

The input parameters can be in any order. For an example, see D3DXFillTextureTX

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXFillTextureTX, D3DXFillCubeTextureTX


D3DXFilterTexture Function

Filters mipmap levels of a texture.

Syntax

HRESULT WINAPI D3DXFilterTexture(

    LPDIRECT3DBASETEXTURE9 pBaseTexture,
    CONST PALETTEENTRY *pPalette,
    UINT SrcLevel,
    DWORD MipFilter
);

Parameters

pBaseTexture
[in] Pointer to an IDirect3DBaseTexture9 interface that represents the texture object to filter.
pPalette
[out] Pointer to a PALETTEENTRY structure that represents a 256-color palette to fill in, or NULL for nonpalletized formats. If a palette is not specified, the default Microsoft Direct3D palette (an all opaque white palette) is provided. See Remarks.
SrcLevel
[in] Level whose image is used to generate the subsequent levels. Specifying D3DX_DEFAULT for this parameter is equivalent to specifying 0.
MipFilter
[in] Combination of one or more D3DX_FILTER controlling how the mipmap is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX if the texture size is a power of two, and D3DX_FILTER_BOX | D3DX_FILTER_DITHER otherwise.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

A filter is recursively applied to each texture level to generate the next texture level.

Writing to a non-level-zero surface of the texture will not cause the dirty rectangle to be updated. If D3DXFilterTexture is called and the surface was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DTexture9::AddDirtyRect on the texture.

Textures created in the default pool (D3DPOOL_DEFAULT) cannot be used with D3DXFilterTexture (unless created with D3DUSAGE_DYNAMIC) because a lock operation is needed on the object. Note that locks are prohibited on textures in the default pool (unless they are dynamic).

For details on PALETTEENTRY, see the Microsoft Platform Software Development Kit (SDK). Note that as of Microsoft DirectX 8.0, the peFlags member of the PALETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

There is only one texture filtering function, but two macros that call this method.

#define D3DXFilterCubeTexture D3DXFilterTexture
#define D3DXFilterVolumeTexture D3DXFilterTexture

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXGetImageInfoFromFile Function

Retrieves information about a given image file.

Syntax

HRESULT WINAPI D3DXGetImageInfoFromFile(

    LPCSTR pSrcFile,
    D3DXIMAGE_INFO *pSrcInfo
);

Parameters

pSrcFile
[in] File name of image to retrieve information about. If UNICODE or _UNICODE are defined, this parameter type is LPCWSTR, otherwise, the type is LPCSTR.
pSrcInfo
[in] Pointer to a D3DXIMAGE_INFO structure to be filled with the description of the data in the source file.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be the following.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This function supports both Unicode and ANSI strings.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXGetImageInfoFromFileInMemory, D3DXGetImageInfoFromResource


D3DXGetImageInfoFromFileInMemory Function

Retrieves information about a given image file in memory.

Syntax

HRESULT WINAPI D3DXGetImageInfoFromFileInMemory(

    LPCVOID pSrcData,
    UINT SrcDataSize,
    D3DXIMAGE_INFO *pSrcInfo
);

Parameters

pSrcData
[in] VOID pointer to the source file in memory.
SrcDataSize
[in] Size of file in memory, in bytes. .
pSrcInfo
[in] Pointer to a D3DXIMAGE_INFO structure to be filled with the description of the data in the source file.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be the following.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXGetImageInfoFromFile, D3DXGetImageInfoFromResource


D3DXGetImageInfoFromResource Function

Retrieves information about a given image in a resource.

Syntax

HRESULT WINAPI D3DXGetImageInfoFromResource(

    HMODULE hSrcModule,
    LPCTSTR pSrcFile,
    D3DXIMAGE_INFO *pSrcInfo
);

Parameters

hSrcModule
[in] Module where the resource is loaded. Set this parameter to NULL to specify the module associated with the image that the operating system used to create the current process.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pSrcInfo
[in] Pointer to a D3DXIMAGE_INFO structure to be filled with the description of the data in the source file.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be the following.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXGetImageInfoFromResourceW. Otherwise, the function call resolves to D3DXGetImageInfoFromResourceA because ANSI strings are being used.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXGetImageInfoFromFile, D3DXGetImageInfoFromFileInMemory


D3DXLoadSurfaceFromFile Function

Loads a surface from a file.

Syntax

HRESULT WINAPI D3DXLoadSurfaceFromFile(

    LPDIRECT3DSURFACE9 pDestSurface,
    CONST PALETTEENTRY* pDestPalette,
    CONST RECT* pDestRect,
    LPCTSTR pSrcFile,
    CONST RECT* pSrcRect,
    DWORD Filter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO* pSrcInfo
);

Parameters

pDestSurface
[in] Pointer to an IDirect3DSurface9 interface. Specifies the destination surface, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestRect
[in] Pointer to a RECT World Wide Web link structure. Specifies the destination rectangle. Set this parameter to NULL to specify the entire surface.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pSrcRect
[in] Pointer to a RECT structure. Specifies the source rectangle. Set this parameter to NULL to specify the entire image.
Filter
[in] Combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXLoadSurfaceFromFileW. Otherwise, the function call resolves to D3DXLoadSurfaceFromFileA because ANSI strings are being used.

This function handles conversion to and from compressed texture formats and supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Writing to a non-level-zero surface will not cause the dirty rectangle to be updated. If D3DXLoadSurfaceFromFile is called and the surface was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DTexture9::AddDirtyRect on the surface.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Texture Support in D3DX


D3DXLoadSurfaceFromFileInMemory Function

Loads a surface from a file in memory.

Syntax

HRESULT WINAPI D3DXLoadSurfaceFromFileInMemory(

    LPDIRECT3DSURFACE9 pDestSurface,
    CONST PALETTEENTRY *pDestPalette,
    CONST RECT *pDestRect,
    LPCVOID pSrcData,
    UINT SrcData,
    CONST RECT *pSrcRect,
    DWORD Filter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO *pSrcInfo
);

Parameters

pDestSurface
[in] Pointer to an IDirect3DSurface9 interface. Specifies the destination surface, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestRect
[in] Pointer to a RECT World Wide Web link structure. Specifies the destination rectangle. Set this parameter to NULL to specify the entire surface.
pSrcData
[in] Pointer to the file in memory from which to load the surface.
SrcData
[in] Size of the file in memory, in bytes.
pSrcRect
[in] Pointer to a RECT structure. Specifies the source rectangle. Set this parameter to NULL to specify the entire image.
Filter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file or NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

This function handles conversion to and from compressed texture formats and supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Writing to a non-level-zero surface will not cause the dirty rectangle to be updated. If D3DXLoadSurfaceFromFileInMemory is called and the surface was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DTexture9::AddDirtyRect on the surface.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Texture Support in D3DX


D3DXLoadSurfaceFromMemory Function

Loads a surface from memory.

Syntax

HRESULT WINAPI D3DXLoadSurfaceFromMemory(

    LPDIRECT3DSURFACE9 pDestSurface,
    CONST PALETTEENTRY *pDestPalette,
    CONST RECT *pDestRect,
    LPCVOID pSrcMemory,
    D3DFORMAT SrcFormat,
    UINT SrcPitch,
    CONST PALETTEENTRY *pSrcPalette,
    CONST RECT *pSrcRect,
    DWORD Filter,
    D3DCOLOR ColorKey
);

Parameters

pDestSurface
[in] Pointer to an IDirect3DSurface9 interface. Specifies the destination surface, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestRect
[in] Pointer to a RECT World Wide Web link structure. Specifies the destination rectangle. Set this parameter to NULL to specify the entire surface.
pSrcMemory
[in] Pointer to the upper left corner of the source image in memory.
SrcFormat
[in] Member of the D3DFORMAT enumerated type, the pixel format of the source image.
SrcPitch
[in] Pitch of source image, in bytes. For DXT formats, this number should represent the width of one row of cells, in bytes.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure, the source palette of 256 colors or NULL.
pSrcRect
[in] Pointer to a RECT structure. Specifies the dimensions of the source image in memory. This value cannot be NULL.
Filter
[in] Combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

This function handles conversion to and from compressed texture formats.

Writing to a non-level-zero surface will not cause the dirty rectangle to be updated. If D3DXLoadSurfaceFromMemory is called and the surface was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DTexture9::AddDirtyRect on the surface.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Texture Support in D3DX


D3DXLoadSurfaceFromResource Function

Loads a surface from a resource.

Syntax

HRESULT WINAPI D3DXLoadSurfaceFromResource(

    LPDIRECT3DSURFACE9 pDestSurface,
    const PALETTEENTRY *pDestPalette,
    const RECT *pDestRect,
    HMODULE hSrcModule,
    LPCTSTR pSrcResource,
    const RECT *pSrcRect,
    DWORD Filter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO *pSrcInfo
);

Parameters

pDestSurface
[in] Pointer to an IDirect3DSurface9 interface. Specifies the destination surface, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestRect
[in] Pointer to a RECT World Wide Web link structure. Specifies the destination rectangle. Set this parameter to NULL to specify the entire surface.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a string that specifies the resource name. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pSrcRect
[in] Pointer to a RECT structure. Specifies the source rectangle. Set this parameter to NULL to specify the entire image.
Filter
[in] Combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXLoadSurfaceFromResourceW. Otherwise, the function call resolves to D3DXLoadSurfaceFromResourceA because ANSI strings are being used.

The resource being loaded must be of type RT_BITMAP or RT_RCDATA. Resource type RT_RCDATA is used to load formats other than bitmaps (such as .tga, .jpg, and .dds).

This function handles conversion to and from compressed texture formats.

Writing to a non-level-zero surface will not cause the dirty rectangle to be updated. If D3DXLoadSurfaceFromFile is called and the surface was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DTexture9::AddDirtyRect on the surface.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Texture Support in D3DX


D3DXLoadSurfaceFromSurface Function

Loads a surface from another surface with color conversion.

Syntax

HRESULT WINAPI D3DXLoadSurfaceFromSurface(

    LPDIRECT3DSURFACE9 pDestSurface,
    CONST PALETTEENTRY *pDestPalette,
    CONST RECT *pDestRect,
    LPDIRECT3DSURFACE9 pSrcSurface,
    CONST PALETTEENTRY *pSrcPalette,
    CONST RECT *pSrcRect,
    DWORD Filter,
    D3DCOLOR ColorKey
);

Parameters

pDestSurface
[in] Pointer to an IDirect3DSurface9 interface. Specifies the destination surface, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestRect
[in] Pointer to a RECT World Wide Web link structure. Specifies the destination rectangle. Set this parameter to NULL to specify the entire surface.
pSrcSurface
[in] Pointer to an IDirect3DSurface9 interface, representing the source surface.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure, the source palette of 256 colors or NULL.
pSrcRect
[in] Pointer to a RECT structure. Specifies the source rectangle. Set this parameter to NULL to specify the entire surface.
Filter
[in] A combination of one or more D3DX_FILTER, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

This function handles conversion to and from compressed texture formats.

Writing to a non-level-zero surface will not cause the dirty rectangle to be updated. If D3DXLoadSurfaceFromSurface is called and the surface was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DTexture9::AddDirtyRect on the surface.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

Texture Support in D3DX


D3DXLoadVolumeFromFile Function

Loads a volume from a file.

Syntax

HRESULT WINAPI D3DXLoadVolumeFromFile(

    LPDIRECT3DVOLUME9 pDestVolume,
    const PALETTEENTRY *pDestPalette,
    const D3DBOX *pDestBox,
    LPCTSTR pSrcFile,
    const D3DBOX *pSrcBox,
    DWORD Filter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO pSrcInfo
);

Parameters

pDestVolume
[in] Pointer to an IDirect3DVolume9 interface. Specifies the destination volume.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestBox
[in] Pointer to a D3DBOX structure. Specifies the destination box. Set this parameter to NULL to specify the entire volume.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
pSrcBox
[in] Pointer to a D3DBOX structure. Specifies the source box. Set this parameter to NULL to specify the entire volume.
Filter
[in] Combination of one or more D3DX_FILTER, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXLoadVolumeFromFileW. Otherwise, the function call resolves to D3DXLoadVolumeFromFileA because ANSI strings are being used.

This function handles conversion to and from compressed texture formats and supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Writing to a non-level-zero surface of the volume texture will not cause the dirty rectangle to be updated. If D3DXLoadVolumeFromFile is called and the texture was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DVolumeTexture9::AddDirtyBox on the volume texture.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXLoadVolumeFromFileInMemory, D3DXLoadVolumeFromMemory, D3DXLoadVolumeFromResource, D3DXLoadVolumeFromVolume, Texture Support in D3DX


D3DXLoadVolumeFromFileInMemory Function

Loads a volume from a file in memory.

Syntax

HRESULT WINAPI D3DXLoadVolumeFromFileInMemory(

    LPDIRECT3DVOLUME9 pDestVolume,
    const PALETTEENTRY *pDestPalette,
    const D3DBOX *pDestBox,
    LPCVOID pSrcData,
    UINT SrcDataSize,
    const D3DBOX *pSrcBox,
    DWORD Filter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO *pSrcInfo
);

Parameters

pDestVolume
[in] Pointer to an IDirect3DVolume9 interface. Specifies the destination volume.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestBox
[in] Pointer to a D3DBOX structure. Specifies the destination box. Set this parameter to NULL to specify the entire volume.
pSrcData
[in] Pointer to the file in memory from which to load the volume.
SrcDataSize
[in] Size in bytes of the file in memory.
pSrcBox
[in] Pointer to a D3DBOX structure. Specifies the source box. Set this parameter to NULL to specify the entire volume.
Filter
[in] Combination of one or more D3DX_FILTER, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

This function handles conversion to and from compressed texture formats and supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Writing to a non-level-zero surface of the volume texture will not cause the dirty rectangle to be updated. If D3DXLoadVolumeFromFileInMemory is called and the texture was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DVolumeTexture9::AddDirtyBox on the volume texture.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXLoadVolumeFromFile, D3DXLoadVolumeFromMemory, D3DXLoadVolumeFromResource, D3DXLoadVolumeFromVolume, Texture Support in D3DX


D3DXLoadVolumeFromMemory Function

Loads a volume from memory.

Syntax

HRESULT WINAPI D3DXLoadVolumeFromMemory(

    LPDIRECT3DVOLUME9 pDestVolume,
    CONST PALETTEENTRY *pDestPalette,
    CONST D3DBOX *pDestBox,
    LPCVOID pSrcMemory,
    D3DFORMAT SrcFormat,
    UINT SrcRowPitch,
    UINT SrcSlicePitch,
    CONST PALETTEENTRY *pSrcPalette,
    CONST D3DBOX *pSrcBox,
    DWORD Filter,
    D3DCOLOR ColorKey
);

Parameters

pDestVolume
[in] Pointer to an IDirect3DVolume9 interface. Specifies the destination volume, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestBox
[in] Pointer to a D3DBOX structure. Specifies the destination box. Set this parameter to NULL to specify the entire volume.
pSrcMemory
[in] Pointer to the top-left corner of the source volume in memory.
SrcFormat
[in] Member of the D3DFORMAT enumerated type, the pixel format of the source volume.
SrcRowPitch
[in] Pitch of source image, in bytes. For DXT formats (compressed texture formats), this number should represent the size of one row of cells, in bytes.
SrcSlicePitch
[in] Pitch of source image, in bytes. For DXT formats (compressed texture formats), this number should represent the size of one slice of cells, in bytes.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure, the source palette of 256 colors or NULL.
pSrcBox
[in] Pointer to a D3DBOX structure. Specifies the source box. NULL is not a valid value for this parameter.
Filter
[in] A combination of one or more D3DX_FILTER controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

Writing to a non-level-zero surface of the volume texture will not cause the dirty rectangle to be updated. If D3DXLoadVolumeFromMemory is called and the texture was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DVolumeTexture9::AddDirtyBox on the volume texture.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXLoadVolumeFromFile, D3DXLoadVolumeFromResource, D3DXLoadVolumeFromVolume, Texture Support in D3DX


D3DXLoadVolumeFromResource Function

Loads a volume from a resource.

Syntax

HRESULT WINAPI D3DXLoadVolumeFromResource(

    LPDIRECT3DVOLUME9 pDestVolume,
    const PALETTEENTRY *pDestPalette,
    const D3DBOX *pDestBox,
    HMODULE hSrcModule,
    LPCSTR pSrcResource,
    const D3DBOX *pSrcBox,
    DWORD Filter,
    D3DCOLOR ColorKey,
    D3DXIMAGE_INFO pSrcInfo
);

Parameters

pDestVolume
[in] Pointer to an IDirect3DVolume9 interface. Specifies the destination volume.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestBox
[in] Pointer to a D3DBOX structure. Specifies the destination box. Set this parameter to NULL to specify the entire volume.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a string that specifies the file name of the source image. If UNICODE or _UNICODE are defined, this parameter type is LPCWSTR, otherwise, the type is LPCSTR.
pSrcBox
[in] Pointer to a D3DBOX structure. Specifies the source box. Set this parameter to NULL to specify the entire volume.
Filter
[in] Combination of one or more D3DX_FILTER, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

The resource being loaded must be a bitmap resource(RT_BITMAP).

This function handles conversion to and from compressed texture formats.

Writing to a non-level-zero surface of the volume texture will not cause the dirty rectangle to be updated. If D3DXLoadVolumeFromFile is called and the texture was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DVolumeTexture9::AddDirtyBox on the volume texture.

This function supports both Unicode and ANSI strings.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXLoadVolumeFromFile, D3DXLoadVolumeFromFileInMemory, D3DXLoadVolumeFromMemory, D3DXLoadVolumeFromVolume, Texture Support in D3DX


D3DXLoadVolumeFromVolume Function

Loads a volume from another volume.

Syntax

HRESULT WINAPI D3DXLoadVolumeFromVolume(

    LPDIRECT3DVOLUME9 pDestVolume,
    CONST PALETTEENTRY *pDestPalette,
    CONST D3DBOX *pDestBox,
    LPDIRECT3DVOLUME9 pSrcVolume,
    CONST PALETTEENTRY *pSrcPalette,
    CONST D3DBOX *pSrcBox,
    DWORD Filter,
    D3DCOLOR ColorKey
);

Parameters

pDestVolume
[in] Pointer to an IDirect3DVolume9 interface. Specifies the destination volume, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL.
pDestBox
[in] Pointer to a D3DBOX structure. Specifies the destination box. Set this parameter to NULL to specify the entire volume.
pSrcVolume
[in] A Pointer to an IDirect3DVolume9 interface. Specifies the source volume.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure, the source palette of 256 colors or NULL.
pSrcBox
[in] Pointer to a D3DBOX structure. Specifies the source box. Set this parameter to NULL to specify the entire volume.
Filter
[in] A combination of one or more D3DX_FILTER, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

Writing to a non-level-zero surface of the volume texture will not cause the dirty rectangle to be updated. If D3DXLoadVolumeFromVolume is called and the surface was not already dirty (this is unlikely under normal usage scenarios), the application needs to explicitly call IDirect3DVolumeTexture9::AddDirtyBox on the surface.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXLoadVolumeFromFile, D3DXLoadVolumeFromFileInMemory, D3DXLoadVolumeFromMemory, D3DXLoadVolumeFromResource, Texture Support in D3DX


D3DXSaveSurfaceToFile Function

Saves a surface to a file.

Syntax

HRESULT WINAPI D3DXSaveSurfaceToFile(

    LPCTSTR pDestFile,
    D3DXIMAGE_FILEFORMAT DestFormat,
    LPDIRECT3DSURFACE9 pSrcSurface,
    const PALETTEENTRY *pSrcPalette,
    const RECT *pSrcRect
);

Parameters

pDestFile
[in] Pointer to a string that specifies the file name of the source image. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
DestFormat
[in] D3DXIMAGE_FILEFORMAT specifying the file format to use when saving. This function supports saving to all D3DXIMAGE_FILEFORMAT formats except Portable Pixmap (.ppm) and Targa/Truevision Graphics Adapter (.tga).
pSrcSurface
[in] Pointer to IDirect3DSurface9 interface, containing the image to be saved.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure containing a palette of 256 colors. This parameter can be NULL.
pSrcRect
[in] Pointer to a RECT World Wide Web link structure. Specifies the source rectangle. Set this parameter to NULL to specify the entire image.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be the following.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXSaveSurfaceToFileW. Otherwise, the function call resolves to D3DXSaveSurfaceToFileA because ANSI strings are being used.

This function handles conversion to and from compressed texture formats.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXSaveTextureToFile, D3DXSaveVolumeToFile


D3DXSaveSurfaceToFileInMemory Function

Saves a surface to an image file.

Syntax

HRESULT WINAPI D3DXSaveSurfaceToFileInMemory(

    LPD3DXBUFFER *ppDestBuf,
    D3DXIMAGE_FILEFORMAT DestFormat,
    LPDIRECT3DSURFACE9 pSrcSurface,
    const PALETTEENTRY *pSrcPalette,
    const RECT *pSrcRect
);

Parameters

ppDestBuf
[in] Address of a pointer to an ID3DXBuffer that will store the source image.
DestFormat
[in] D3DXIMAGE_FILEFORMAT specifying the file format to use when saving. This function supports saving to all D3DXIMAGE_FILEFORMAT formats except Portable Pixmap (.ppm) and Targa/Truevision Graphics Adapter (.tga).
pSrcSurface
[in] Pointer to IDirect3DSurface9 interface containing the image to be saved.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure containing a palette of 256 colors. This parameter can be NULL.
pSrcRect
[in] Pointer to a RECT World Wide Web link structure. Specifies the source rectangle. Set this parameter to NULL to specify the entire image.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be the following:

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This function handles conversion to and from compressed texture formats.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXSaveVolumeToFileInMemory


D3DXSaveTextureToFile Function

Saves a texture to a file.

Syntax

HRESULT WINAPI D3DXSaveTextureToFile(

    LPCTSTR pDestFile,
    D3DXIMAGE_FILEFORMAT DestFormat,
    LPDIRECT3DBASETEXTURE9 pSrcTexture,
    const PALETTEENTRY *pSrcPalette
);

Parameters

pDestFile
[in] Pointer to a string that specifies the file name of the source image. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
DestFormat
[in] D3DXIMAGE_FILEFORMAT specifying the file format to use when saving. This function supports saving to all D3DXIMAGE_FILEFORMAT formats except Portable Pixmap (.ppm) and Targa/Truevision Graphics Adapter (.tga).
pSrcTexture
[in] Pointer to IDirect3DBaseTexture9 interface, containing the texture to be saved.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure containing a palette of 256 colors. This parameter can be NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be the following.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXSaveTextureToFileW. Otherwise, the function call resolves to D3DXSaveTextureToFileA because ANSI strings are being used.

This function handles conversion to and from compressed texture formats.

If the volume is nondynamic (because of a usage parameter set to 0 at the creation) and located in video memory (the memory pool set to D3DPOOL_DEFAULT), D3DXSaveTextureToFile will fail because D3DX cannot lock nondynamic volumes located in video memory.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXSaveSurfaceToFile, D3DXSaveVolumeToFile


D3DXSaveTextureToFileInMemory Function

Saves a texture to an image file.

Syntax

HRESULT WINAPI D3DXSaveTextureToFileInMemory(

    LPD3DXBUFFER *ppDestBuf,
    D3DXIMAGE_FILEFORMAT DestFormat,
    LPDIRECT3DBASETEXTURE9 pSrcTexture,
    const PALETTEENTRY *pSrcPalette
);

Parameters

ppDestBuf
[in] Address of a pointer to an ID3DXBuffer that will store the source image.
DestFormat
[in] D3DXIMAGE_FILEFORMAT specifying the file format to use when saving. This function supports saving to all D3DXIMAGE_FILEFORMAT formats except Portable Pixmap (.ppm) and Targa/Truevision Graphics Adapter (.tga).
pSrcTexture
[in] Pointer to IDirect3DBaseTexture9 interface containing the image to be saved.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure containing a palette of 256 colors. This parameter can be NULL.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be the following:

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

This function handles conversion to and from compressed texture formats.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXSaveSurfaceToFileInMemory, D3DXSaveVolumeToFileInMemory


D3DXSaveVolumeToFile Function

Saves a volume to a file on disk.

Syntax

HRESULT WINAPI D3DXSaveVolumeToFile(

    LPCTSTR pDestFile,
    D3DXIMAGE_FILEFORMAT DestFormat,
    LPDIRECT3DVOLUME9 pSrcVolume,
    const PALETTEENTRY *pSrcPalette,
    const D3DBOX *pSrcBox
);

Parameters

pDestFile
[in] Pointer to a string that specifies the file name of the source image. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
DestFormat
[in] D3DXIMAGE_FILEFORMAT specifying the file format to use when saving. This function supports saving to all D3DXIMAGE_FILEFORMAT formats except Portable Pixmap (.ppm) and Targa/Truevision Graphics Adapter (.tga).
pSrcVolume
[in] Pointer to IDirect3DVolume9 interface containing the image to be saved.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure containing a palette of 256 colors. This parameter can be NULL.
pSrcBox
[in] Pointer to a D3DBOX structure. Specifies the source box. Set this parameter to NULL to specify the entire volume.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be the following.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXSaveVolumeToFileW. Otherwise, the function call resolves to D3DXSaveVolumeToFileA because ANSI strings are being used.

This function handles conversion to and from compressed texture formats.

If the volume is nondynamic (because of a usage parameter set to 0 at the creation) and located in video memory (the memory pool set to D3DPOOL_DEFAULT), D3DXSaveTextureToFile will fail because D3DX cannot lock nondynamic volumes located in video memory.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXSaveSurfaceToFile, D3DXSaveTextureToFile, D3DXSaveVolumeToFileInMemory


D3DXSaveVolumeToFileInMemory Function

Saves a volume to a buffer. The method creates an ID3DXBuffer buffer to store the data, and returns that object.

Syntax

HRESULT WINAPI D3DXSaveVolumeToFileInMemory(

    LPD3DXBUFFER *ppDestBuf,
    D3DXIMAGE_FILEFORMAT DestFormat,
    LPDIRECT3DVOLUME9 pSrcVolume,
    const PALETTEENTRY *pSrcPalette,
    const D3DBOX *pSrcBox
);

Parameters

ppDestBuf
[out] Address of a pointer to an ID3DXBuffer buffer that will store the source image.
DestFormat
[in] D3DXIMAGE_FILEFORMAT specifying the file format to use when saving. This function supports saving to all D3DXIMAGE_FILEFORMAT formats except Portable Pixmap (.ppm) and Targa/Truevision Graphics Adapter (.tga).
pSrcVolume
[in] Pointer to IDirect3DVolume9 interface containing the image to be saved.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure containing a palette of 256 colors. This parameter can be NULL.
pSrcBox
[in] Pointer to a D3DBOX structure. Specifies the source box. Set this parameter to NULL to specify the entire volume.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be the following.

D3DERR_INVALIDCALL The method call is invalid. For example, a method's parameter may have an invalid value.

Function Information

Header | d3dx9tex.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXSaveVolumeToFile


Callback Functions
Microsoft DirectX 9.0 SDK Update (October 2004)

Callback Functions

This section contains information about the following callback functions.

  • LPD3DXFILL2D
  • LPD3DXFILL3D
  • LPD3DXSHPRTSIMCB


LPD3DXFILL2D
Microsoft DirectX 9.0 SDK Update (October 2004)

LPD3DXFILL2D

Note: This documentation is preliminary and is subject to change.

Function type used by the texture fill functions.

Syntax

typedef VOID (WINAPI *LPD3DXFILL2D)(
    D3DXVECTOR4* pOut,
    CONST D3DXVECTOR2* pTexCoord,
    CONST D3DXVECTOR2* pTexelSize,
    LPVOID pData,
);

Parameters

pOut - Pointer to a vector, which the function uses to return its result. X, Y, Z, and W will be mapped to R, G, B, and A, respectively.

pTexCoord - Pointer to a vector containing the coordinates of the texel currently being evaluated. Texture coordinate components for texture and volume textures range from 0 to 1. Texture coordinate components for cube textures range from -1 to 1.

pTexelSize - Pointer to a vector containing the dimensions of the current texel.

pData - Pointer to user data.

Return Value

No return value.

Remarks

Be sure to specify the WINAPI World Wide Web link calling convention when declaring the callback function. Otherwise, stack overflows can occur.

Header | d3dx9tex.h
Import Library | d3dx9.lib
Minimum Operating System | Windows 98

Related Topics

  • LPD3DXFILL3D


LPD3DXFILL3D
Microsoft DirectX 9.0 SDK Update (October 2004)

LPD3DXFILL3D

Note: This documentation is preliminary and is subject to change.

Function type used by the texture fill functions.

Syntax

typedef VOID (WINAPI *LPD3DXFILL2D)(
    D3DXVECTOR4* pOut,
    CONST D3DXVECTOR3* pTexCoord,
    CONST D3DXVECTOR3* pTexelSize,
    LPVOID pData,
);

Parameters

pOut - Pointer to a vector, which the function uses to return its result. X, Y, Z, and W will be mapped to R, G, B, and A, respectively.

pTexCoord - Pointer to a vector containing the coordinates of the texel currently being evaluated. Texture coordinate components for texture and volume textures range from 0 to 1. Texture coordinate components for cube textures range from -1 to 1.

pTexelSize - Pointer to a vector containing the dimensions of the current texel.

pData - Pointer to user data.

Return Value

No return value.

Remarks

Be sure to specify the WINAPI World Wide Web link calling convention when declaring the callback function. Otherwise, stack overflows can occur.

Header | d3dx9tex.h
Import Library | d3dx9.lib
Minimum Operating System | Windows 98

Related Topics

  • LPD3DXFILL2D


LPD3DXSHPRTSIMCB
Microsoft DirectX 9.0 SDK Update (October 2004)

LPD3DXSHPRTSIMCB

Note: This documentation is preliminary and is subject to change.

Callback function for precomputed radiance transfer (PRT) simulation and compression.

Syntax

typedef HRESULT (WINAPI *LPD3DXSHPRTSIMCB)(
    FLOAT fPercentDone,
    LPVOID lpUserContext
);

Parameters

fPercentDone - Floating point number between 0 and 1.0 that represents the percentage of spherical harmonics (SH) calculations completed (between 0 and 100 percent).

lpUserContext - Pointer to a user-defined value which is passed to the callback function; typically used by an application to pass a pointer to a data structure that provides context information for the callback function.

Return Value

This function must be implemented to return S_OK to keep running the simulator. Any other value will abort the simulator.

Remarks

Be sure to specify the WINAPI World Wide Web link calling convention when declaring the callback function. Otherwise, stack overflows can occur.

Header | d3dx9mesh.h
Import Library | d3dx9.lib
Minimum Operating System | Windows 98


Macros
Microsoft DirectX 9.0 SDK Update (October 2004)

Macros

This section contains reference information for the macros provided by the D3DX utility library.

Macros

  • D3DSINCOSCONST1
  • D3DSINCOSCONST2
  • D3DXToDegree
  • D3DXToRadian
  • D3DXTX_VERSION


D3DSINCOSCONST1 Macro

Creates the first constant (in register src2) for the sincos pixel shader instruction.

Syntax

#define D3DSINCOSCONST1 -1.5500992e-006f, -2.1701389e-005f,  0.0026041667f, 0.00026041668f

Return Value

Returns the first constant needed by sincos.

Macro Information

Header | d3dx9types.h
Minimum operating systems | Windows 98

See Also

sincos, D3DSINCOSCONST2


D3DSINCOSCONST2 Macro

Creates the second constant (in register src3) for the sincos pixel shader instruction.

Syntax

#define D3DSINCOSCONST2 -0.020833334f, -0.12500000f, 1.0f, 0.50000000f

Return Value

Returns the second constant needed by sincos.

Macro Information

Header | d3dx9types.h
Minimum operating systems | Windows 98

See Also

sincos, D3DSINCOSCONST1


D3DXToDegree Macro

Converts radians into degrees.

Syntax

#define D3DXToDegree( radian ) ((radian) * (180.0f / D3DX_PI))

Parameters

radian
The value, in radians, to convert to degrees.

Return Value

The macro returns the radian value in degrees.

Macro Information

Header | d3dx9math.h
Minimum operating systems | Windows 98

See Also

D3DXToRadian, D3DX_PI


D3DXToRadian Macro

Converts degrees into radians.

Syntax

#define D3DXToRadian( degree ) ((degree) * (D3DX_PI / 180.0f))

Parameters

degree
The value, in degrees, to convert to radians.

Return Value

The macro returns the degree value in radians.

Macro Information

Header | d3dx9math.h
Minimum operating systems | Windows 98

See Also

D3DXToDegree, D3DX_PI


D3DXTX_VERSION Macro

Version token that creates a procedural texture filler in effects. This macro is used by the D3DXFillxxxTX functions.

Syntax

#define D3DXTX_VERSION(_Major,_Minor) (('T' << 24) | ('X' << 16) | ((_Major) << 8) | (_Minor))

Return Value

The macro returns the procedural texture version token.

Macro Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

See Also

D3DXFillTextureTX, D3DXFillCubeTextureTX, D3DXFillVolumeTextureTX


Structures
Microsoft DirectX 9.0 SDK Update (October 2004)

Structures

This section contains information about the structures included in the D3DX utility library.

Structures

  • D3DXATTRIBUTERANGE
  • D3DXATTRIBUTEWEIGHTS
  • D3DXBONECOMBINATION
  • D3DXCOLOR
  • D3DXCOLOR Extensions
  • D3DXCONSTANT_DESC
  • D3DXCONSTANTTABLE_DESC
  • D3DXFLOAT16
  • D3DXFLOAT16 Extensions
  • D3DXFONT_DESC
  • D3DXFRAME
  • D3DXIMAGE_INFO
  • D3DXINTERSECTINFO
  • D3DXKEY_CALLBACK
  • D3DXKEY_QUATERNION
  • D3DXKEY_VECTOR3
  • D3DXMACRO
  • D3DXMATERIAL
  • D3DXMATRIX
  • D3DXMATRIX Extensions
  • D3DXMATRIXA16
  • D3DXMESHCONTAINER
  • D3DXMESHDATA
  • D3DXPATCHINFO
  • D3DXPLANE
  • D3DXPLANE Extensions
  • D3DXQUATERNION
  • D3DXQUATERNION Extensions
  • D3DXRTE_DESC
  • D3DXRTS_DESC
  • D3DXSHADER_CONSTANTINFO
  • D3DXSHADER_CONSTANTTABLE
  • D3DXSHADER_STRUCTMEMBERINFO
  • D3DXSHADER_TYPEINFO
  • D3DXSHMATERIAL
  • D3DXSHPRTSPLITMESHCLUSTERDATA
  • D3DXSHPRTSPLITMESHVERTDATA
  • D3DXTRACK_DESC
  • D3DXVECTOR2
  • D3DXVECTOR2 Extensions
  • D3DXVECTOR3
  • D3DXVECTOR3 Extensions
  • D3DXVECTOR4
  • D3DXVECTOR4 Extensions
  • D3DXWELDEPSILONS


D3DXATTRIBUTERANGE Structure

Stores an attribute table entry.

Syntax

typedef struct _D3DXATTRIBUTERANGE {
    DWORD AttribId;
    DWORD FaceStart;
    DWORD FaceCount;
    DWORD VertexStart;
    DWORD VertexCount;
} D3DXATTRIBUTERANGE;

Members

AttribId
Attribute table identifier.
FaceStart
Starting face.
FaceCount
Face count.
VertexStart
Starting vertex.
VertexCount
Vertex count.

Remarks

An attribute table is used to identify areas of the mesh that need to be drawn with different textures, render states, materials, and so on. In addition, the application can use the attribute table to hide portions of a mesh by not drawing a given attribute identifier (AttribId) when drawing the frame.

The LPD3DXATTRIBUTERANGE type is defined as a pointer to the D3DXATTRIBUTERANGE structure.

typedef D3DXATTRIBUTERANGE* LPD3DXATTRIBUTERANGE;

Structure Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

See Also

ID3DXBaseMesh::DrawSubset


D3DXATTRIBUTEWEIGHTS Structure

Specifies mesh weight attributes.

Syntax

typedef struct _D3DXATTRIBUTEWEIGHTS {
    FLOAT Position;
    FLOAT Boundary;
    FLOAT Normal;
    FLOAT Diffuse;
    FLOAT Specular;
    FLOAT Texcoord[8];
    FLOAT Tangent;
    FLOAT Binormal;
} D3DXATTRIBUTEWEIGHTS, *LPD3DXATTRIBUTEWEIGHTS;

Members

Position
Position.
Boundary
Blend weight.
Normal
Normal.
Diffuse
Diffuse lighting value.
Specular
Specular lighting value.
Texcoord
Eight texture coordinates.
Tangent
Tangent.
Binormal
Binormal.

Remarks

This structure describes how a simplification operation will consider vertex data when calculating relative costs between collapsing edges. For example, if the Normal field is 0.0, the simplification operation will ignore the vertex normal component when calculating the error for the collapse. However, if the Normal field is 1.0, the simplification operation will use the vertex normal component. If the Normal field is 2.0, double the amount of errors; if the Normal field is 4.0, then quadruple the number of errors, and so on.

The LPD3DXATTRIBUTEWEIGHTS type is defined as a pointer to the D3DXATTRIBUTEWEIGHTS structure.

typedef D3DXATTRIBUTEWEIGHTS* LPD3DXATTRIBUTEWEIGHTS;

Structure Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

See Also

D3DXCreateSPMesh, D3DXGeneratePMesh, D3DXSimplifyMesh


D3DXBONECOMBINATION Structure

Describes a subset of the mesh that has the same attribute and bone combination.

Syntax

typedef struct _D3DXBONECOMBINATION {
    DWORD AttribId;
    DWORD FaceStart;
    DWORD FaceCount;
    DWORD VertexStart;
    DWORD VertexCount;
    DWORD *BoneId;
} D3DXBONECOMBINATION, *LPD3DXBONECOMBINATION;

Members

AttribId
Attribute table identifier.
FaceStart
Starting face.
FaceCount
Face count.
VertexStart
Starting vertex.
VertexCount
Vertex count.
BoneId
Pointer to an array of values that identify each of the bones that can be drawn in a single drawing call. Note that the array can be of variable length to accommodate variable length bone combinations of ID3DXSkinInfo::ConvertToIndexedBlendedMesh.

The size of the array varies based on the type of mesh generated. A non-indexed mesh array size is equal to the number of weights per vertex (pMaxVertexInfl in ID3DXSkinInfo::ConvertToBlendedMesh). An indexed mesh array size is equal to the number of bone matrix palette entries (paletteSize in ID3DXSkinInfo::ConvertToIndexedBlendedMesh).

Remarks

The subset of the mesh described by D3DXBONECOMBINATION can be rendered in a single drawing call.

Structure Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98


D3DXCOLOR Structure

Describes color values.

Syntax

typedef struct D3DXCOLOR {
    FLOAT r;
    FLOAT g;
    FLOAT b;
    FLOAT a;
} D3DXCOLOR;

Members

r
Red component of the color.
g
Green component of the color.
b
Blue component of the color.
a
Alpha component of the color.

Remarks

C++ programmers can take advantage of operator overloading and type casting with the D3DXCOLOR Extensions, which implement overloaded constructors, as well as assignment, unary, and binary (including equality) operators.

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98


D3DXCOLOR Extensions Structure

Supplies the following operator overloads and type casts for D3DXCOLOR structures.

Syntax

typedef struct D3DXCOLOR
{
#ifdef __cplusplus
public:
    D3DXCOLOR() {}
    D3DXCOLOR( DWORD argb );
    D3DXCOLOR( CONST FLOAT * );
    D3DXCOLOR( CONST D3DXFLOAT16 * );
    D3DXCOLOR( CONST D3DCOLORVALUE& );
    D3DXCOLOR( FLOAT r, FLOAT g, FLOAT b, FLOAT a );

    // casting
    operator DWORD () const;

    operator FLOAT* ();
    operator CONST FLOAT* () const;

    operator D3DCOLORVALUE* ();
    operator CONST D3DCOLORVALUE* () const;

    operator D3DCOLORVALUE& ();
    operator CONST D3DCOLORVALUE& () const;

    // assignment operators
    D3DXCOLOR& operator += ( CONST D3DXCOLOR& );
    D3DXCOLOR& operator -= ( CONST D3DXCOLOR& );
    D3DXCOLOR& operator *= ( FLOAT );
    D3DXCOLOR& operator /= ( FLOAT );

    // unary operators
    D3DXCOLOR operator + () const;
    D3DXCOLOR operator - () const;

    // binary operators
    D3DXCOLOR operator + ( CONST D3DXCOLOR& ) const;
    D3DXCOLOR operator - ( CONST D3DXCOLOR& ) const;
    D3DXCOLOR operator * ( FLOAT ) const;
    D3DXCOLOR operator / ( FLOAT ) const;

    friend D3DXCOLOR operator * ( FLOAT, CONST D3DXCOLOR& );

    BOOL operator == ( CONST D3DXCOLOR& ) const;
    BOOL operator != ( CONST D3DXCOLOR& ) const;

#endif //__cplusplus
    FLOAT r, g, b, a;
} D3DXCOLOR, *LPD3DXCOLOR;

Members

For more information about structure members, refer to D3DXCOLOR.

Remarks

Operator overloads and type casts for this structure are implemented in d3dx9math.inl.

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98


D3DXCONSTANT_DESC Structure

A description of a constant in a constant table.

Syntax

typedef struct _D3DXCONSTANT_DESC {
    LPCSTR Name;
    D3DXREGISTER_SET RegisterSet;
    UINT RegisterIndex;
    UINT RegisterCount;
    D3DXPARAMETER_CLASS Class;
    D3DXPARAMETER_TYPE Type;
    UINT Rows;
    UINT Columns;
    UINT Elements;
    UINT StructMembers;
    UINT Bytes;
    LPCVOID DefaultValue;
} D3DXCONSTANT_DESC;

Members

Name
Name of the constant.
RegisterSet
Constant data type. See D3DXREGISTER_SET.
RegisterIndex
Zero-based index of the constant in the table.
RegisterCount
Number of registers that contain data.
Class
Parameter class. See D3DXPARAMETER_CLASS.
Type
Parameter type. See D3DXPARAMETER_TYPE.
Rows
Number of rows.
Columns
Number of columns.
Elements
Number of elements in the array.
StructMembers
Number of structure member sub-parameters.
Bytes
Data size in number of bytes.
DefaultValue
Pointer to the default value.

Structure Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

See Also

D3DXCONSTANTTABLE_DESC


D3DXCONSTANTTABLE_DESC Structure

A description of the constant table.

Syntax

typedef struct _D3DXCONSTANTTABLE_DESC {
    LPCSTR Creator;
    DWORD Version;
    UINT Constants;
} D3DXCONSTANTTABLE_DESC;

Members

Creator
Name of the constant table creator.
Version
Shader version.
Constants
Number of constants in the constant table.

Structure Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

See Also

D3DXCONSTANT_DESC


D3DXEVENT_DESC Structure
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DXEVENT_DESC Structure

Describes an animation event.

Syntax

typedef struct D3DXEVENT_DESC {

    D3DXEVENT_TYPE      Type;
    UINT                Track;
    DOUBLE              StartTime;
    DOUBLE              Duration;
    D3DXTRANSITION_TYPE Transition;

    union
    {
    FLOAT  Weight;
    FLOAT  Speed;
    DOUBLE Position;
    BOOL   Enable;
    }

} D3DXEVENT_DESC, *LPD3DXEVENT_DESC;

Members

Type - Event type, as defined in D3DXEVENT_TYPE.

Track - Event track identifier.

StartTime - Start time of the event in global time.

Duration - Duration of the event in global time.

Transition - Transition style of the event, as defined in D3DXTRANSITION_TYPE.

Weight - Track weight for the event.

Speed - Track speed for the event.

Position - Track position for the event.

Enable - Enable flag.

Structure Information

Header | d3dx9anim.h
Minimum Operating System | Windows 98


D3DXFLOAT16 Structure

Describes a 16-bit floating point vector.

Syntax

typedef struct D3DXFLOAT16 {
    WORD Value;
} D3DXFLOAT16;

Members

Value
The 16-bit data.

Remarks

C++ programmers can take advantage of operator overloading and type casting with the D3DXFLOAT16 Extensions, which implement overloaded constructors and assignment, unary, and binary (including equality) operators.

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98


D3DXFLOAT16 Extensions Structure

Supplies operator overloads and type casts for D3DXFLOAT16 structures.

Syntax

typedef struct D3DXFLOAT16
{
#ifdef __cplusplus
public:
    D3DXFLOAT16() {};
    D3DXFLOAT16( FLOAT );
    D3DXFLOAT16( CONST D3DXFLOAT16& );

    // casting
    operator FLOAT ();

    // binary operators
    BOOL operator == ( CONST D3DXFLOAT16& ) const;
    BOOL operator != ( CONST D3DXFLOAT16& ) const;

protected:
#endif //__cplusplus
    WORD value;
} D3DXFLOAT16, *LPD3DXFLOAT16;

Members

For more information about structure members, refer to D3DXFLOAT16.

Remarks

Operator overloads and type casts for this structure are implemented in d3dx9math.inl.

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98


D3DXFONT_DESC Structure

Defines the attributes of a font.

Syntax

typedef struct D3DXFONT_DESC {
    INT Height;
    UINT Width;
    UINT Weight;
    UINT MipLevels;
    BOOL Italic;
    BYTE CharSet;
    BYTE OutputPrecision;
    BYTE Quality;
    BYTE PitchAndFamily;
    TCHAR FaceName[LF_FACESIZE];
} D3DXFONT_DESC;

Members

Height
Height, in logical units, of the font's character cell or character.
Width
Width, in logical units, of characters in the font.
Weight
Weight of the font in the range from 0 through 1000.
MipLevels
Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created. If the value is 1, the texture space is mapped identically to the screen space.
Italic
Set to TRUE for an Italic font.
CharSet
Character set.
OutputPrecision
Output precision. The output precision defines how closely the output must match the requested font height, width, character orientation, escapement, pitch, and font type.
Quality
Output quality.
PitchAndFamily
Pitch and family of the font.
FaceName
A null-terminated string or characters that specifies the typeface name of the font. The length of the string must not exceed 32 characters, including the terminating null character. If FaceName is an empty string, the first font that matches the other specified attributes will be used.

If the compiler settings require Unicode, the data type TCHAR resolves to WCHAR; otherwise, the data type resolves to CHAR. See Remarks.

Remarks

The compiler setting also determines the structure type. If Unicode is defined, the D3DXFONT_DESC structure type resolves to a D3DXFONT_DESCW; otherwise the structure type resolves to a D3DXFONT_DESCA.

Possible values of the above members are given in the Microsoft Windows Graphics Device Interface (GDI) LOGFONT World Wide Web link structure.

Structure Information

Header | d3dx9core.h
Minimum operating systems | Windows 98

See Also

ID3DXFont::GetDesc


D3DXFRAME Structure

Encapsulates a transform frame in a transformation frame hierarchy.

Syntax

typedef struct _D3DXFRAME {
    LPSTR Name;
    D3DXMATRIX TransformationMatrix;
    LPD3DXMESHCONTAINER pMeshContainer;
    struct _D3DXFRAME *pFrameSibling;
    struct _D3DXFRAME *pFrameFirstChild;
} D3DXFRAME, *LPD3DXFRAME;

Members

Name
Name of the frame.
TransformationMatrix
Transformation matrix.
pMeshContainer
Pointer to the mesh container.
pFrameSibling
Pointer to a sibling frame.
pFrameFirstChild
Pointer to a child frame.

Remarks

An application can derive from this structure to add other data.

Structure Information

Header | d3dx9anim.h
Minimum operating systems | Windows 98


D3DXIMAGE_INFO Structure

Returns a description of the original contents of an image file.

Syntax

typedef struct _D3DXIMAGE_INFO {
    UINT Width;
    UINT Height;
    UINT Depth;
    UINT MipLevels;
    D3DFORMAT Format;
    D3DRESOURCETYPE ResourceType;
    D3DXIMAGE_FILEFORMAT ImageFileFormat;
} D3DXIMAGE_INFO;

Members

Width
Width of original image in pixels.
Height
Height of original image in pixels.
Depth
Depth of original image in pixels.
MipLevels
Number of mip levels in original image.
Format
A value from the D3DFORMAT enumerated type that most closely describes the data in the original image.
ResourceType
Represents the type of the texture stored in the file. It is either D3DRTYPE_TEXTURE, D3DRTYPE_VOLUMETEXTURE, or D3DRTYPE_CUBETEXTURE.
ImageFileFormat
Represents the format of the image file.

Structure Information

Header | d3dx9tex.h
Minimum operating systems | Windows 98


D3DXINTERSECTINFO Structure

Describes a ray-triangle intersection.

Syntax

typedef struct _D3DXINTERSECTINFO {
    DWORD FaceIndex;
    FLOAT U;
    FLOAT V;
    FLOAT Dist;
} D3DXINTERSECTINFO, *LPD3DXINTERSECTINFO;

Members

FaceIndex
Index of the triangle that hit the ray.
U
Barycentric coordinate within the triangle where the ray intersects.
V
Barycentric coordinate within the triangle where the ray intersects.
Dist
Distance along the ray where the intersection occurred.

Structure Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98


D3DXKEY_CALLBACK Structure

Describes a callback key for use in key frame animation.

Syntax

typedef struct _D3DXKEY_CALLBACK {
    FLOAT Time;
    LPVOID pCallbackData;
} D3DXKEY_CALLBACK, *LPD3DXKEY_CALLBACK;

Members

Time
Key frame time stamp.
pCallbackData
Pointer to user callback data.

Structure Information

Header | d3dx9anim.h
Minimum operating systems | Windows 98


D3DXKEY_QUATERNION Structure

Describes a quaternion key for use in key frame animation. A quaternion key is a quaternion value at a given time.

Syntax

typedef struct _D3DXKEY_QUATERNION {
    FLOAT Time;
    D3DXQUATERNION Value;
} D3DXKEY_QUATERNION, *LPD3DXKEY_QUATERNION;

Members

Time
Time value.
Value
D3DXQUATERNION quaternion that supplies rotation values.

Structure Information

Header | d3dx9anim.h
Minimum operating systems | Windows 98


D3DXKEY_VECTOR3 Structure

Describes a vector key for use in key frame animation. It specifies a vector at a given time. This is used for scale and translation keys.

Syntax

typedef struct _D3DXKEY_VECTOR3 {
    FLOAT Time;
    D3DXVECTOR3 Value;
} D3DXKEY_VECTOR3, *LPD3DXKEY_VECTOR3;

Members

Time
Key frame time stamp.
Value
D3DXVECTOR3 3-D vector that supplies scale and/or translation values.

Structure Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98


D3DXMACRO Structure

Describes preprocessor definitions used by an effect object.

Syntax

typedef struct D3DXMACRO {
    LPCSTR Name;
    LPCSTR Definition;
} D3DXMACRO;

Members

Name
Preprocessor name.
Definition
Definition name.

Structure Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

See Also

D3DXCreateEffectFromFile


D3DXMATERIAL Structure

Returns material information saved in Microsoft Direct3D (.x) files.

Syntax

typedef struct D3DXMATERIAL {
    D3DMATERIAL9 MatD3D;
    LPSTR pTextureFilename;
} D3DXMATERIAL;

Members

MatD3D
D3DMATERIAL9 structure that describes the material properties.
pTextureFilename
Pointer to a string that specifies the file name of the texture.

Remarks

The D3DXLoadMeshFromX and D3DXLoadMeshFromXof functions return an array of D3DXMATERIAL structures that specify the material color and name of the texture for each material in the mesh. The application is then required to load the texture.

The LPD3DXMATERIAL type is defined as a pointer to the D3DXMATERIAL structure.

typedef struct D3DXMATERIAL* LPD3DXMATERIAL;

Structure Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

See Also

D3DXLoadMeshFromX, D3DXLoadMeshFromXof


D3DXMATRIX Structure

Describes a matrix.

Syntax

typedef struct D3DXMATRIX {
    FLOAT _11, FLOAT _12, FLOAT _13, FLOAT _14,
    FLOAT _21, FLOAT _22, FLOAT _23, FLOAT _24,
    FLOAT _31, FLOAT _32, FLOAT _33, FLOAT _34,
    FLOAT _41, FLOAT _42, FLOAT _43, FLOAT _44 );
} D3DXMATRIX;

Members

_ij
The (i, j) component of the matrix, where i is the row number and j is the column number. For example, _34 means the same as [a34], the component in the third row and fourth column.

Remarks

This structure inherits members from the D3DMATRIX structure. C programmers cannot use the D3DXMATRIX structure. They must use the D3DMATRIX structure.

In D3DX, the _34 element of a projection matrix cannot be a negative number. If your application needs to use a negative value in this location, it should scale the entire projection matrix by -1 instead.

C++ programmers can take advantage of operator overloading and type casting with the D3DXMATRIX Extensions, which implement overloaded constructors and assignment, unary, and binary (including equality) operators.

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98

See Also

D3DMATRIX, Matrix Transforms


D3DXMATRIX Extensions Structure

Supplies the following operator overloads and type casts for D3DXMATRIX structures. The _D3DXMATRIXA16 structure provides 16-bit versions of overloads and type casts.

Syntax

#ifdef __cplusplus
typedef struct D3DXMATRIX : public D3DMATRIX
{
public:
    D3DXMATRIX() {};
    D3DXMATRIX( CONST FLOAT * );
    D3DXMATRIX( CONST D3DMATRIX& );
    D3DXMATRIX( CONST D3DXFLOAT16 * );
    D3DXMATRIX( FLOAT _11, FLOAT _12, FLOAT _13, FLOAT _14,
                FLOAT _21, FLOAT _22, FLOAT _23, FLOAT _24,
                FLOAT _31, FLOAT _32, FLOAT _33, FLOAT _34,
                FLOAT _41, FLOAT _42, FLOAT _43, FLOAT _44 );

    // access grants
    FLOAT& operator () ( UINT Row, UINT Col );
    FLOAT  operator () ( UINT Row, UINT Col ) const;

    // casting operators
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXMATRIX& operator *= ( CONST D3DXMATRIX& );
    D3DXMATRIX& operator += ( CONST D3DXMATRIX& );
    D3DXMATRIX& operator -= ( CONST D3DXMATRIX& );
    D3DXMATRIX& operator *= ( FLOAT );
    D3DXMATRIX& operator /= ( FLOAT );

    // unary operators
    D3DXMATRIX operator + () const;
    D3DXMATRIX operator - () const;

    // binary operators
    D3DXMATRIX operator * ( CONST D3DXMATRIX& ) const;
    D3DXMATRIX operator + ( CONST D3DXMATRIX& ) const;
    D3DXMATRIX operator - ( CONST D3DXMATRIX& ) const;
    D3DXMATRIX operator * ( FLOAT ) const;
    D3DXMATRIX operator / ( FLOAT ) const;

    friend D3DXMATRIX operator * ( FLOAT, CONST D3DXMATRIX& );

    BOOL operator == ( CONST D3DXMATRIX& ) const;
    BOOL operator != ( CONST D3DXMATRIX& ) const;

} D3DXMATRIX, *LPD3DXMATRIX;

#else //!__cplusplus
typedef struct _D3DMATRIX D3DXMATRIX, *LPD3DXMATRIX;
#endif //!__cplusplus

#ifdef __cplusplus
typedef struct _D3DXMATRIXA16 : public D3DXMATRIX
{
    _D3DXMATRIXA16() {}
    _D3DXMATRIXA16( CONST FLOAT * );
    _D3DXMATRIXA16( CONST D3DMATRIX& );
    _D3DXMATRIXA16( CONST D3DXFLOAT16 * );
    _D3DXMATRIXA16( FLOAT _11, FLOAT _12, FLOAT _13, FLOAT _14,
                    FLOAT _21, FLOAT _22, FLOAT _23, FLOAT _24,
                    FLOAT _31, FLOAT _32, FLOAT _33, FLOAT _34,
                    FLOAT _41, FLOAT _42, FLOAT _43, FLOAT _44 );

    // new operators
    void* operator new   ( size_t );
    void* operator new[] ( size_t );

    // delete operators
    void operator delete   ( void* );   // These are NOT virtual; Do not
    void operator delete[] ( void* );   // cast to D3DXMATRIX and delete.

    // assignment operators
    _D3DXMATRIXA16& operator = ( CONST D3DXMATRIX& );

} _D3DXMATRIXA16;

#else //!__cplusplus
typedef D3DXMATRIX  _D3DXMATRIXA16;
#endif //!__cplusplus

Members

For more information about structure members, refer to D3DXMATRIX or D3DXMATRIXA16.

Remarks

Operator overloads and type casts for this structure are implemented in d3dx9math.inl.

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98


D3DXMATRIXA16 Structure

Defines a 16-byte aligned matrix.

Syntax

typedef struct _D3DXMATRIXA16 : public D3DXMATRIX
{
    _D3DXMATRIXA16();
    _D3DXMATRIXA16( CONST FLOAT * f);
    _D3DXMATRIXA16( CONST D3DMATRIX& m);
    _D3DXMATRIXA16( FLOAT _11, FLOAT _12, FLOAT _13, FLOAT _14,
                    FLOAT _21, FLOAT _22, FLOAT _23, FLOAT _24,
                    FLOAT _31, FLOAT _32, FLOAT _33, FLOAT _34,
                    FLOAT _41, FLOAT _42, FLOAT _43, FLOAT _44 );
    void* operator new(size_t s);
    void* operator new[](size_t s);

    // The two operators below are not virtual operators. If you cast
    //   to D3DXMATRIX, do not delete using them
    void operator delete(void* p);
    void operator delete[](void* p);

    struct _D3DXMATRIXA16& operator=(CONST D3DXMATRIX& rhs);
} _D3DXMATRIXA16;

typedef D3DX_ALIGN16 _D3DXMATRIXA16 D3DXMATRIXA16, *LPD3DXMATRIXA16;

Members

_ij
The (i, j) component of the matrix, where i is the row number and j is the column number. For example, _34 means the same as [a34], the component in the third row and fourth column.

Remarks

A 16-byte aligned matrix, when used by D3DX math functions, has been optimized for improved performance on Intel Pentium 4 processors. Matrices are aligned independent of where they are created: on the program stack, in the heap, or in global scope. Alignment is accomplished using __declspec(align(16)), which works with Microsoft Visual C++ .NET and with Visual C++ 6.0 only when the processor pack is installed. Unfortunately, there is no way to detect the processor pack, so byte alignment is turned on by default only with Visual C++ .NET.

Vectors and quaternions are not byte aligned in D3DX. When using vectors and quaternions with D3DX math functions, use _declspec(align(16)) to generate byte aligned vectors and quaternions, because they will perform significantly better. The definition of _declspec is shown here.

#define D3DX_ALIGN16 __declspec(align(16))

Other compilers interpret D3DXMATRIXA16 as D3DXMATRIX. Using this structure on a compiler that does not actually align the matrix can be problematic because it will not expose bugs that ignore alignment. For example, if a D3DXMATRIXA16 object is inside a structure or class, a memcpy World Wide Web link might be done with tight packing (ignoring 16-byte boundaries). This would cause build breaks if the compiler were to sometime add matrix aligning.

C++ programmers can take advantage of operator overloading and type casting with the D3DXMATRIX Extensions, which implement overloaded constructors and assignment, unary, and binary (including equality) operators.

Structure Information

Header | d3dx9math.h
Minimum availability | DirectX 9.0
Minimum operating systems | Windows 2000, Windows 98

See Also

D3DXMATRIX, Matrix Transforms


D3DXMESHCONTAINER Structure

Encapsulates a mesh object in a transformation frame hierarchy.

Syntax

typedef struct _D3DXMESHCONTAINER {
    LPSTR Name;
    D3DXMESHDATA MeshData;
    LPD3DXMATERIAL pMaterials;
    LPD3DXEFFECTINSTANCE pEffects;
    DWORD NumMaterials;
    DWORD *pAdjacency;
    LPD3DXSKININFO pSkinInfo;
    struct _D3DXMESHCONTAINER *pNextMeshContainer;
} D3DXMESHCONTAINER, *LPD3DXMESHCONTAINER;

Members

Name
Mesh name.
MeshData
Type of data in the mesh. See D3DXMESHDATA.
pMaterials
Array of mesh materials. See D3DXMATERIAL.
pEffects
Pointer to the effect interface. See D3DXEFFECTINSTANCE.
NumMaterials
Number of materials in the mesh.
pAdjacency
Pointer to an array of three DWORDs per triangle of the mesh that contains adjacency information.
pSkinInfo
Pointer to the skin information interface. See ID3DXSkinInfo.
pNextMeshContainer
Pointer to the next mesh container.

Remarks

An application can derive from this structure to add other data.

Structure Information

Header | d3dx9anim.h
Minimum operating systems | Windows 98


D3DXMESHDATA Structure
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DXMESHDATA Structure

Mesh data structure.

Syntax

typedef struct D3DXMESHDATA {

    D3DXMESHDATATYPE Type;

    union
    {
    LPD3DXMESH      pMesh;
    LPD3DXPMESH     pPMesh;
    LPD3DXPATCHMESH pPatchMesh;
    }

} D3DXMESHDATA, *LPD3DXMESHDATA;

Members

Type - Defines the mesh data type. See D3DXMESHDATATYPE.

pMesh - Pointer to a mesh. See ID3DXMesh.

pPMesh - Pointer to a progressive mesh. See ID3DXPMesh.

pPatchMesh - Pointer to a patch mesh. See ID3DXPatchMesh.

Structure Information

Header | d3dx9mesh.h
Minimum Operating System | Windows 98

Related Topics

  • D3DXMESHCONTAINER


D3DXPATCHINFO Structure

Structure that contains the attributes of a patch mesh.

Syntax

typedef struct _D3DXPATCHINFO {
    D3DXPATCHMESHTYPE PatchType;
    D3DDEGREETYPE Degree;
    D3DBASISTYPE Basis;
} D3DXPATCHINFO, *LPD3DXPATCHINFO;

Members

PatchType
The patch type. For information about patch types, see D3DXPATCHMESHTYPE.
Degree
Degree of the curves used to construct the patch. For information about the degrees supported, see D3DDEGREETYPE.
Basis
Type of curve used to construct the patch. For information about the basis types supported, see D3DBASISTYPE.

Remarks

A mesh is a set of faces, each of which is described by a simple polygon. Objects can be created by connecting several meshes together. A patch mesh is constructed from patches. A patch is a four-sided piece of geometry constructed from curves. The type of curve used and the order of the curve can be varied so that the patch surface will fit almost any surface shape.

The following types of patch combinations are supported:

Patch Type | Basis | Degree
Rectangle | Bezier | 2,3,5
Rectangle | B-Spline | 2,3,5
Rectangle | Catmull-Rom | 3
Triangle | Bezier | 2,3,5
N-patch | N/A | 3

Structure Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

See Also

D3DRECTPATCH_INFO, D3DTRIPATCH_INFO, D3DXCreatePatchMesh


D3DXPLANE Structure

Describes a plane.

Syntax

typedef struct D3DXPLANE {
    FLOAT a;
    FLOAT b;
    FLOAT c;
    FLOAT d;
} D3DXPLANE;

Members

a
The a coefficient of the clipping plane in the general plane equation. See Remarks.
b
The b coefficient of the clipping plane in the general plane equation. See Remarks.
c
The c coefficient of the clipping plane in the general plane equation. See Remarks.
d
The d coefficient of the clipping plane in the general plane equation. See Remarks.

Remarks

The members of the D3DXPLANE structure take the form of the general plane equation. They fit into the general plane equation so that ax + by + cz + dw = 0.

C++ programmers can take advantage of operator overloading and type casting with the D3DXPLANE Extensions which implement overloaded constructors and assignment, unary, and binary (including equality) operators.

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98


D3DXPLANE Extensions Structure

Supplies the following operator overloads and type casts for D3DXPLANE structures.

Syntax

typedef struct D3DXPLANE
{
#ifdef __cplusplus
public:
    D3DXPLANE() {}
    D3DXPLANE( CONST FLOAT* );
    D3DXPLANE( CONST D3DXFLOAT16* );
    D3DXPLANE( FLOAT a, FLOAT b, FLOAT c, FLOAT d );

    // casting
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXPLANE& operator *= ( FLOAT );
    D3DXPLANE& operator /= ( FLOAT );

    // unary operators
    D3DXPLANE operator + () const;
    D3DXPLANE operator - () const;

    // binary operators
    D3DXPLANE operator * ( FLOAT ) const;
    D3DXPLANE operator / ( FLOAT ) const;

    friend D3DXPLANE operator * ( FLOAT, CONST D3DXPLANE& );

    BOOL operator == ( CONST D3DXPLANE& ) const;
    BOOL operator != ( CONST D3DXPLANE& ) const;

#endif //__cplusplus
    FLOAT a, b, c, d;
} D3DXPLANE, *LPD3DXPLANE;

Members

For more information about structure members, refer to D3DXPLANE.

Remarks

Operator overloads and type casts for this structure are implemented in d3dx9math.inl.

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98


D3DXQUATERNION Structure

Describes a quaternion.

Syntax

typedef struct D3DXQUATERNION {
    FLOAT x;
    FLOAT y;
    FLOAT z;
    FLOAT w;
} D3DXQUATERNION;

Members

x
The x-component.
y
The y-component.
z
The z-component.
w
The w-component.

Remarks

Quaternions add a fourth element to the [ x, y, z] values that define a vector, resulting in arbitrary 4-D vectors. However, the following illustrates how each element of a unit quaternion relates to an axis-angle rotation (where q represents a unit quaternion (x, y, z, w), axis is normalized, and theta is the desired CCW rotation about the axis):

q.x = sin(theta/2) * axis.x

q.y = sin(theta/2) * axis.y

q.z = sin(theta/2) * axis.z

q.w = cos(theta/2)

C++ programmers can take advantage of operator overloading and type casting with the D3DXQUATERNION Extensions, which implement overloaded constructors and assignment, unary, and binary (including equality) operators.

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98

See Also

Vectors, Vertices, and Quaternions


D3DXQUATERNION Extensions Structure

Supplies the following operator overloads and type casts for D3DXQUATERNION structures.

Syntax

typedef struct D3DXQUATERNION
{
#ifdef __cplusplus
public:
    D3DXQUATERNION() {}
    D3DXQUATERNION( CONST FLOAT * );
    D3DXQUATERNION( CONST D3DXFLOAT16 * );
    D3DXQUATERNION( FLOAT x, FLOAT y, FLOAT z, FLOAT w );

    // casting
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXQUATERNION& operator += ( CONST D3DXQUATERNION& );
    D3DXQUATERNION& operator -= ( CONST D3DXQUATERNION& );
    D3DXQUATERNION& operator *= ( CONST D3DXQUATERNION& );
    D3DXQUATERNION& operator *= ( FLOAT );
    D3DXQUATERNION& operator /= ( FLOAT );

    // unary operators
    D3DXQUATERNION  operator + () const;
    D3DXQUATERNION  operator - () const;

    // binary operators
    D3DXQUATERNION operator + ( CONST D3DXQUATERNION& ) const;
    D3DXQUATERNION operator - ( CONST D3DXQUATERNION& ) const;
    D3DXQUATERNION operator * ( CONST D3DXQUATERNION& ) const;
    D3DXQUATERNION operator * ( FLOAT ) const;
    D3DXQUATERNION operator / ( FLOAT ) const;

    friend D3DXQUATERNION operator * (FLOAT, CONST D3DXQUATERNION& );

    BOOL operator == ( CONST D3DXQUATERNION& ) const;
    BOOL operator != ( CONST D3DXQUATERNION& ) const;

#endif //__cplusplus
    FLOAT x, y, z, w;
} D3DXQUATERNION, *LPD3DXQUATERNION;

Members

For more information about structure members, refer to D3DXQUATERNION.

Remarks

Operator overloads and type casts for this structure are implemented in d3dx9math.inl.

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98


D3DXRTE_DESC Structure

Describes an off-screen render target used by an instance of ID3DXRenderToEnvMap.

Syntax

typedef struct _D3DXRTE_DESC {
    UINT Size;
    UINT MipLevels;
    D3DFORMAT Format;
    BOOL DepthStencil;
    D3DFORMAT DepthStencilFormat;
} D3DXRTE_DESC;

Members

Size
Width and height in pixels.
MipLevels
Maximum level of detail (LOD) number.
Format
Color buffer format.
DepthStencil
Indicates if the z-buffer is needed.
DepthStencilFormat
Format of the depth buffer.

Remarks

This method is used to return the creation parameters used when creating an ID3DXRenderToEnvMap object.

Structure Information

Header | d3dx9core.h
Minimum operating systems | Windows 98


D3DXRTS_DESC Structure

Describes a render surface.

Syntax

typedef struct _D3DXRTS_DESC {
    UINT Width;
    UINT Height;
    D3DFORMAT Format;
    BOOL DepthStencil;
    D3DFORMAT DepthStencilFormat;
} D3DXRTS_DESC;

Members

Width
Width of the render surface, in pixels.
Height
Height of the render surface, in pixels.
Format
Member of the D3DFORMAT enumerated type, describing the pixel format of the render surface.
DepthStencil
If TRUE, the render surface supports a depth-stencil surface; otherwise this member is set to FALSE.
DepthStencilFormat
If DepthStencil is set to TRUE, this parameter is a member of the D3DFORMAT enumerated type, describing the depth-stencil format of the render surface.

Structure Information

Header | d3dx9core.h
Minimum operating systems | Windows 98

See Also

ID3DXRenderToSurface::GetDesc


D3DXSHADER_CONSTANTINFO Structure

Syntax

typedef struct _D3DXSHADER_CONSTANTINFO {
    DWORD Name;
    WORD RegisterSet;
    WORD RegisterIndex;
    WORD RegisterCount;
    WORD Reserved;
    DWORD TypeInfo;
    DWORD DefaultValue;
} D3DXSHADER_CONSTANTINFO;

Members

Name
Offset from the beginning of this structure, in bytes, to the string that contains the constant information.
RegisterSet
Register set. See D3DXREGISTER_SET.
RegisterIndex
The register index.
RegisterCount
Number of registers.
Reserved
Reserved.
TypeInfo
Offset from the beginning of this structure, in bytes, to the string that contains the D3DXSHADER_TYPEINFO information.
DefaultValue
Offset from the beginning of this structure, in bytes, to the string that contains the default value.

Structure Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98


D3DXSHADER_CONSTANTTABLE Structure

Helper structure for managing a shader constant table. This can also be done using ID3DXConstantTable.

Syntax

typedef struct _D3DXSHADER_CONSTANTTABLE {
    DWORD Size;
    DWORD Creator;
    DWORD Version;
    DWORD Constants;
    DWORD ConstantInfo;
    DWORD Flags;
    DWORD Target;
} D3DXSHADER_CONSTANTTABLE;

Members

Size
Size of the structure. See Remarks.
Creator
Offset from the beginning of this structure, in bytes, to the string that contains the name of the creator.
Version
Shader version.
Constants
Number of constants.
ConstantInfo
Array of constant information, D3DXSHADER_CONSTANTINFO[Constants]. See D3DXSHADER_CONSTANTINFO.
Flags
The D3DXSHADER Compile Options flags used to compile the shader.
Target
Offset into the string that contains the target.

Remarks

Shader constant information is included in a tab-delimited table of comments. All offsets are measured in bytes from the beginning of the structure. Entries in the constant table are sorted by Creator in ascending order.

A shader constant table can be managed with the ID3DXConstantTable interfaces. Alternatively, you can manage the constant table with D3DXSHADER_CONSTANTTABLE.

This size member is often initialized using the following:

D3DXSHADER_CONSTANTTABLE constantTable;
constantTable.Size = sizeof(D3DXSHADER_CONSTANTTABLE)

Structure Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

See Also

D3DXGetShaderConstantTable


D3DXSHADER_STRUCTMEMBERINFO Structure

A helper structure containing member structure information.

Syntax

typedef struct _D3DXSHADER_STRUCTMEMBERINFO {
    DWORD Name;
    DWORD TypeInfo;
} D3DXSHADER_STRUCTMEMBERINFO;

Members

Name
Offset from the beginning of this structure, in bytes, to the string that contains the structure member name.
TypeInfo
Offset from the beginning of this structure, in bytes, to the string that contains the type information. See D3DXSHADER_TYPEINFO.

Structure Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

See Also

D3DXSHADER_TYPEINFO


D3DXSHADER_TYPEINFO Structure

A helper structure containing member type information.

Syntax

typedef struct _D3DXSHADER_TYPEINFO {
    WORD Class;
    WORD Type;
    WORD Rows;
    WORD Columns;
    WORD Elements;
    WORD StructMembers;
    DWORD StructMemberInfo;
} D3DXSHADER_TYPEINFO;

Members

Class
Shader object type. See D3DXPARAMETER_CLASS.
Type
Data type. See D3DXPARAMETER_TYPE.
Rows
Number of matrix rows (matrices).
Columns
Number of columns (vectors and matrices).
Elements
Array dimension.
StructMembers
Number of structure members.
StructMemberInfo
Array of structure member information, D3DXSHADER_STRUCTMEMBERINFO[StructMembers]. See D3DXSHADER_STRUCTMEMBERINFO.

Remarks

The type information is part of D3DXSHADER_STRUCTMEMBERINFO.

Structure Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

See Also

D3DXSHADER_CONSTANTINFO


D3DXSHMATERIAL Structure

Spherical harmonic (SH) precomputed radiance transfer (PRT) material characteristics.

Syntax

typedef struct _D3DXSHMATERIAL {
    D3DCOLORVALUE Diffuse;
    BOOL bMirror;
    BOOL bSubSurf;
    FLOAT RelativeIndexOfRefraction;
    D3DCOLORVALUE Absorption;
    D3DCOLORVALUE ReducedScattering;
} D3DXSHMATERIAL;

Members

Diffuse
Diffuse albedo of the surface. This value is ignored if the object is a mirror.
bMirror
Must be set to FALSE.
bSubSurf
Set to TRUE to enable subsurface scattering; any object that does subsurface scattering cannot be a mirror.
RelativeIndexOfRefraction
Relative index of refraction is the ratio between two absolute indexes of refraction. An index of refraction is the ratio of the sine of the angle of incidence to the sine of the angle of refraction.
Absorption
The absorption coefficient is a parameter to the volume rendering equation used to model light propagation in a participating medium.
ReducedScattering
The reduced scattering coefficient is a parameter to the volume rendering equation used to model light propagation in a participating medium.

Remarks

Non-spectral scenes use the red channel from the materials instead of the luminance value.

For more information about PRT see:

  • Jensen, Henrik Wann, et al. Siggraph Proceedings: A Practical Model for Subsurface Light Transport, 2001.

Structure Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98


D3DXSHPRTSPLITMESHCLUSTERDATA Structure

Syntax

typedef struct D3DXSHPRTSPLITMESHCLUSTERDATA {
    UINT uVertStart;
    UINT uVertLength;
    UINT uFaceStart;
    UINT uFaceLength;
    UINT uClusterStart;
    UINT uClusterLength;
} D3DXSHPRTSPLITMESHCLUSTERDATA;

Members

uVertStart
Initial vertex into remapped vertex array.
uVertLength
Number of vertices in this supercluster.
uFaceStart
Initial index into face array.
uFaceLength
Number of faces in this supercluster.
uClusterStart
Initial index into cluster array.
uClusterLength
Number of clusters in this supercluster array.

Structure Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

See Also

D3DXSHPRTCompSplitMeshSC


D3DXSHPRTSPLITMESHVERTDATA Structure

Syntax

typedef struct D3DXSHPRTSPLITMESHVERTDATA {
    UINT uVertRemap;
    UINT uSubCluster;
    UINT ucVertStatus;
} D3DXSHPRTSPLITMESHVERTDATA;

Members

uVertRemap
Vertex in original mesh this corresponds to.
uSubCluster
Cluster index, relative to the supercluster.
ucVertStatus
1 if vertex has valid data, 0 if it is "full".

Remarks

Allocated in D3DXSHPRTCompSplitMeshSC.

Structure Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98


D3DXTRACK_DESC Structure

Describes an animation track and specifies blending weight, speed, and position for the track at a given time.

Syntax

typedef struct _D3DXTRACK_DESC {
    D3DXPRIORITY_TYPE Priority;
    FLOAT Weight;
    FLOAT Speed;
    DOUBLE Position;
    BOOL Enable;
} D3DXTRACK_DESC, *LPD3DXTRACK_DESC;

Members

Priority
Priority type, as defined in D3DXPRIORITY_TYPE.
Weight
Weight value. The weight determines the proportion of this track to blend with other tracks.
Speed
Speed value. This is used similarly to a multiplier to scale the period of the track.
Position
Time position of the track, in the local timeframe of its current animation set.
Enable
Track enable/disable. To enable, set to TRUE. To disable, set to FALSE.

Remarks

Tracks with the same priority are blended together, and the two resulting values are then blended using the priority blend factor. A track must have an animation set (stored separately) associated with it.

Structure Information

Header | d3dx9anim.h
Minimum operating systems | Windows 98


D3DXVECTOR2 Structure

Describes a vector in 2-D space.

Syntax

typedef struct D3DXVECTOR2 {
    FLOAT x;
    FLOAT y;
} D3DXVECTOR2;

Members

x
The x-component.
y
The y-component.

Remarks

C++ programmers can take advantage of operator overloading and type casting with the D3DXVECTOR2 Extensions, which implement overloaded constructors, assignment, unary, and binary (including equality) operators.

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98


D3DXVECTOR2 Extensions Structure

Supplies the following operator overloads and type casts for D3DXVECTOR2 structures. The D3DXVECTOR2_16F structure provides 16-bit versions of overloads and type casts.

Syntax

typedef struct D3DXVECTOR2
{
#ifdef __cplusplus
public:
    D3DXVECTOR2() {};
    D3DXVECTOR2( CONST FLOAT * );
    D3DXVECTOR2( CONST D3DXFLOAT16 * );
    D3DXVECTOR2( FLOAT x, FLOAT y );

    // casting
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXVECTOR2& operator += ( CONST D3DXVECTOR2& );
    D3DXVECTOR2& operator -= ( CONST D3DXVECTOR2& );
    D3DXVECTOR2& operator *= ( FLOAT );
    D3DXVECTOR2& operator /= ( FLOAT );

    // unary operators
    D3DXVECTOR2 operator + () const;
    D3DXVECTOR2 operator - () const;

    // binary operators
    D3DXVECTOR2 operator + ( CONST D3DXVECTOR2& ) const;
    D3DXVECTOR2 operator - ( CONST D3DXVECTOR2& ) const;
    D3DXVECTOR2 operator * ( FLOAT ) const;
    D3DXVECTOR2 operator / ( FLOAT ) const;

    friend D3DXVECTOR2 operator * ( FLOAT, CONST D3DXVECTOR2& );

    BOOL operator == ( CONST D3DXVECTOR2& ) const;
    BOOL operator != ( CONST D3DXVECTOR2& ) const;

public:
#endif //__cplusplus
    FLOAT x, y;
} D3DXVECTOR2, *LPD3DXVECTOR2;

typedef struct D3DXVECTOR2_16F
{
#ifdef __cplusplus
public:
    D3DXVECTOR2_16F() {};
    D3DXVECTOR2_16F( CONST FLOAT * );
    D3DXVECTOR2_16F( CONST D3DXFLOAT16 * );
    D3DXVECTOR2_16F( CONST D3DXFLOAT16 &x, CONST D3DXFLOAT16 &y );

    // casting
    operator D3DXFLOAT16* ();
    operator CONST D3DXFLOAT16* () const;

    // binary operators
    BOOL operator == ( CONST D3DXVECTOR2_16F& ) const;
    BOOL operator != ( CONST D3DXVECTOR2_16F& ) const;

public:
#endif //__cplusplus
    D3DXFLOAT16 x, y;

} D3DXVECTOR2_16F, *LPD3DXVECTOR2_16F;

Members

For more information about structure members, refer to D3DXVECTOR2.

Remarks

Operator overloads and type casts for this structure are implemented in d3dx9math.inl.

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98


D3DXVECTOR3 Structure

Describes a vector in three-dimensional (3-D) space.

Syntax

typedef struct {
    FLOAT x;
    FLOAT y;
    FLOAT z;
} D3DXVECTOR3;

Members

x
The x-component.
y
The y-component.
z
The z-component.

Remarks

This structure inherits the x, y and z members from the D3DVECTOR structure. C programmers cannot use the D3DXVECTOR3 structure. They must use the D3DVECTOR structure.

C++ programmers can take advantage of operator overloading and type casting with the D3DXVECTOR3 Extensions, which implement overloaded constructors, assignment, unary, and binary (including equality) operators.

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98


D3DXVECTOR3 Extensions Structure

Supplies the following operator overloads and type casts for D3DXVECTOR3 structures. The D3DXVECTOR3_16F structure provides 16-bit versions of overloads and type casts.

Syntax

#ifdef __cplusplus
typedef struct D3DXVECTOR3 : public D3DVECTOR
{
public:
    D3DXVECTOR3() {};
    D3DXVECTOR3( CONST FLOAT * );
    D3DXVECTOR3( CONST D3DVECTOR& );
    D3DXVECTOR3( CONST D3DXFLOAT16 * );
    D3DXVECTOR3( FLOAT x, FLOAT y, FLOAT z );

    // casting
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXVECTOR3& operator += ( CONST D3DXVECTOR3& );
    D3DXVECTOR3& operator -= ( CONST D3DXVECTOR3& );
    D3DXVECTOR3& operator *= ( FLOAT );
    D3DXVECTOR3& operator /= ( FLOAT );

    // unary operators
    D3DXVECTOR3 operator + () const;
    D3DXVECTOR3 operator - () const;

    // binary operators
    D3DXVECTOR3 operator + ( CONST D3DXVECTOR3& ) const;
    D3DXVECTOR3 operator - ( CONST D3DXVECTOR3& ) const;
    D3DXVECTOR3 operator * ( FLOAT ) const;
    D3DXVECTOR3 operator / ( FLOAT ) const;

    friend D3DXVECTOR3 operator * ( FLOAT, CONST struct D3DXVECTOR3& );

    BOOL operator == ( CONST D3DXVECTOR3& ) const;
    BOOL operator != ( CONST D3DXVECTOR3& ) const;

} D3DXVECTOR3, *LPD3DXVECTOR3;

#else //!__cplusplus
typedef struct _D3DVECTOR D3DXVECTOR3, *LPD3DXVECTOR3;
#endif //!__cplusplus

typedef struct D3DXVECTOR3_16F
{
#ifdef __cplusplus
public:
    D3DXVECTOR3_16F() {};
    D3DXVECTOR3_16F( CONST FLOAT * );
    D3DXVECTOR3_16F( CONST D3DVECTOR& );
    D3DXVECTOR3_16F( CONST D3DXFLOAT16 * );
    D3DXVECTOR3_16F( CONST D3DXFLOAT16 &x, CONST D3DXFLOAT16 &y, CONST D3DXFLOAT16 &z );

    // casting
    operator D3DXFLOAT16* ();
    operator CONST D3DXFLOAT16* () const;

    // binary operators
    BOOL operator == ( CONST D3DXVECTOR3_16F& ) const;
    BOOL operator != ( CONST D3DXVECTOR3_16F& ) const;

public:
#endif //__cplusplus
    D3DXFLOAT16 x, y, z;

} D3DXVECTOR3_16F, *LPD3DXVECTOR3_16F;

Members

For more information about structure members, refer to D3DXVECTOR3.

Remarks

Operator overloads and type casts for this structure are implemented in d3dx9math.inl.

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98


D3DXVECTOR4 Structure

Describes a vector in 4-D space.

Syntax

typedef struct D3DXVECTOR4 {
    FLOAT x;
    FLOAT y;
    FLOAT z;
    FLOAT w;
} D3DXVECTOR4;

Members

x
The x-component.
y
The y-component.
z
The z-component.
w
The w-component.

Remarks

C++ programmers can take advantage of operator overloading and type casting with the D3DXVECTOR4 Extensions, which implement overloaded constructors, assignment, unary, and binary (including equality) operators.

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98


D3DXVECTOR4 Extensions Structure

Supplies the following operator overloads and type casts for D3DXVECTOR4 structures. The D3DXVECTOR4_16F structure provides 16-bit versions of overloads and type casts.

Syntax

typedef struct D3DXVECTOR4
{
#ifdef __cplusplus
public:
    D3DXVECTOR4() {};
    D3DXVECTOR4( CONST FLOAT* );
    D3DXVECTOR4( CONST D3DXFLOAT16 * );
    D3DXVECTOR4( CONST D3DVECTOR& xyz, FLOAT w );
    D3DXVECTOR4( FLOAT x, FLOAT y, FLOAT z, FLOAT w );

    // casting
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXVECTOR4& operator += ( CONST D3DXVECTOR4& );
    D3DXVECTOR4& operator -= ( CONST D3DXVECTOR4& );
    D3DXVECTOR4& operator *= ( FLOAT );
    D3DXVECTOR4& operator /= ( FLOAT );

    // unary operators
    D3DXVECTOR4 operator + () const;
    D3DXVECTOR4 operator - () const;

    // binary operators
    D3DXVECTOR4 operator + ( CONST D3DXVECTOR4& ) const;
    D3DXVECTOR4 operator - ( CONST D3DXVECTOR4& ) const;
    D3DXVECTOR4 operator * ( FLOAT ) const;
    D3DXVECTOR4 operator / ( FLOAT ) const;

    friend D3DXVECTOR4 operator * ( FLOAT, CONST D3DXVECTOR4& );

    BOOL operator == ( CONST D3DXVECTOR4& ) const;
    BOOL operator != ( CONST D3DXVECTOR4& ) const;

public:
#endif //__cplusplus
    FLOAT x, y, z, w;
} D3DXVECTOR4, *LPD3DXVECTOR4;

typedef struct D3DXVECTOR4_16F
{
#ifdef __cplusplus
public:
    D3DXVECTOR4_16F() {};
    D3DXVECTOR4_16F( CONST FLOAT * );
    D3DXVECTOR4_16F( CONST D3DXFLOAT16 * );
    D3DXVECTOR4_16F( CONST D3DXVECTOR3_16F& xyz, CONST D3DXFLOAT16& w );
    D3DXVECTOR4_16F( CONST D3DXFLOAT16& x, CONST D3DXFLOAT16& y, CONST D3DXFLOAT16& z, CONST D3DXFLOAT16& w );

    // casting
    operator D3DXFLOAT16* ();
    operator CONST D3DXFLOAT16* () const;

    // binary operators
    BOOL operator == ( CONST D3DXVECTOR4_16F& ) const;
    BOOL operator != ( CONST D3DXVECTOR4_16F& ) const;

public:
#endif //__cplusplus
    D3DXFLOAT16 x, y, z, w;

} D3DXVECTOR4_16F, *LPD3DXVECTOR4_16F;

Members

For more information about structure members, refer to D3DXVECTOR4.

Remarks

Operator overloads and type casts for this structure are implemented in d3dx9math.inl.

Structure Information

Header | d3dx9math.h
Minimum operating systems | Windows 98


D3DXWELDEPSILONS Structure

Specifies tolerance values for each vertex component when comparing vertices to determine if they are similar enough to be welded together.

Syntax

typedef struct _D3DXWELDEPSILONS {
    FLOAT Position;
    FLOAT BlendWeights;
    FLOAT Normal;
    FLOAT PSize;
    FLOAT Specular;
    FLOAT Diffuse;
    FLOAT Texcoord[8];
    FLOAT Tangent;
    FLOAT Binormal;
    FLOAT Tess Factor;
} D3DXWELDEPSILONS;

Members

Position
Position
BlendWeights
Blend weight
Normal
Normal
PSize
Point size value
Specular
Specular lighting value
Diffuse
Diffuse lighting value
Texcoord
Eight texture coordinates
Tangent
Tangent
Binormal
Binormal
Tess Factor
Tessellation factor

Remarks

The LPD3DXWELDEPSILONS type is defined as a pointer to the D3DXWELDEPSILONS structure.

typedef D3DXWELDEPSILONS *LPD3DXWELDEPSILONS;

Structure Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98


Enumerated Types
Microsoft DirectX 9.0 SDK Update (October 2004)

Enumerated Types

This section contains information about the following enumerated types and flags used with D3DX.

Enumerations

  • D3DXCALLBACK_SEARCH_FLAGS
  • D3DXCLEANTYPE
  • D3DXCOMPRESSION_FLAGS
  • D3DXEFFECTDEFAULTTYPE
  • D3DXERR
  • D3DXEVENT_TYPE
  • D3DXIMAGE_FILEFORMAT
  • D3DXINCLUDE_TYPE
  • D3DXMESH
  • D3DXMESHDATATYPE
  • D3DXMESHOPT
  • D3DXMESHSIMP
  • D3DXPARAMETER_CLASS
  • D3DXPARAMETER_TYPE
  • D3DXPATCHMESH
  • D3DXPATCHMESHTYPE
  • D3DXPLAYBACK_TYPE
  • D3DXPRIORITY_TYPE
  • D3DXREGISTER_SET
  • D3DXSHCOMPRESSQUALITYTYPE
  • D3DXSHGPUSIMOPT
  • D3DXTRANSITION_TYPE
  • D3DXWELDEPSILONSFLAGS
  • MAX_FVF_DECL_SIZE


D3DXCALLBACK_SEARCH_FLAGS Enumerated Type

Flags used to obtain callback information.

Syntax

typedef enum _D3DXCALLBACK_SEARCH_FLAGS {
    D3DXCALLBACK_SEARCH_EXCLUDING_INITIAL_POSITION = 1,
    D3DXCALLBACK_SEARCH_BEHIND_INITIAL_POSITION = 2,
    D3DXEDT_FORCE_DWORD = 0x7fffffff
} D3DXCALLBACK_SEARCH_FLAGS;

Constants

D3DXCALLBACK_SEARCH_EXCLUDING_INITIAL_POSITION

Exclude callbacks located at the initial position from the search.

D3DXCALLBACK_SEARCH_BEHIND_INITIAL_POSITION

Reverse the callback search direction.

D3DXEDT_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Enumerated Type Information

Header | d3dx9anim.h
Minimum operating systems | Windows 98


D3DXCLEANTYPE Enumerated Type

Defines operations to perform on vertices in preparation for mesh cleaning.

Syntax

typedef enum _D3DXCLEANTYPE {
    D3DXCLEAN_BACKFACING = 1,
    D3DXCLEAN_BOWTIES = 2,
    D3DXCLEAN_SKINNING = D3DXCLEAN_BACKFACING,
    D3DXCLEAN_OPTIMIZATION = D3DXCLEAN_BACKFACING,
    D3DXCLEAN_SIMPLIFICATION = D3DXCLEAN_BACKFACING | D3DXCLEAN_BOWTIES
} D3DXCLEANTYPE;

Constants

D3DXCLEAN_BACKFACING

Merge triangles that share the same vertex indices but have face normals pointing in opposite directions (back-facing triangles). Unless the triangles are not split by adding a replicated vertex, mesh adjacency data from the two triangles may conflict.

D3DXCLEAN_BOWTIES

If a vertex is the apex of two triangle fans (a bowtie) and mesh operations will affect one of the fans, then split the shared vertex into two new vertices. Bowties can cause problems for operations such as mesh simplification that remove vertices, because removing one vertex affects two distinct sets of triangles.

D3DXCLEAN_SKINNING

Use this flag to prevent infinite loops during skinning setup mesh operations.

D3DXCLEAN_OPTIMIZATION

Use this flag to prevent infinite loops during mesh optimization operations.

D3DXCLEAN_SIMPLIFICATION

Use this flag to prevent infinite loops during mesh simplification operations.

Enumerated Type Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98


D3DXCOMPRESSION_FLAGS Enumerated Type

Defines the compression mode used for storing compressed animation set data.

Syntax

typedef enum _D3DXCOMPRESSION_FLAGS {
    D3DXCOMPRESS_DEFAULT = 0,
    D3DXCOMPRESS_FORCE_DWORD = 0x7fffffff
} D3DXCOMPRESSION_FLAGS;

Constants

D3DXCOMPRESS_DEFAULT

Implements fast compression.

D3DXCOMPRESS_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Enumerated Type Information

Header | d3dx9anim.h
Minimum operating systems | Windows 98


D3DXEFFECTDEFAULTTYPE Enumerated Type

Effect data types. The data is contained in the pValue member of D3DXEFFECTDEFAULT.

Syntax

typedef enum _D3DXEFFECTDEFAULTTYPE {
    D3DXEDT_STRING = 1,
    D3DXEDT_FLOATS = 2,
    D3DXEDT_DWORD = 3,
    D3DXEDT_FORCE_DWORD = 0x7fffffff
} D3DXEFFECTDEFAULTTYPE;

Constants

D3DXEDT_STRING

The data type is a NULL terminated ASCII text string.

D3DXEDT_FLOATS

The data type is an array of floats. The number of floats in the array is specified by NumBytes in D3DXEFFECTDEFAULT.

D3DXEDT_DWORD

The data type in pValue is a DWORD.

D3DXEDT_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Enumerated Type Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98


D3DXERR Enumerated Type

Errors are represented by negative values and cannot be combined. The following is a list of values that can be returned by methods included with the D3DX utility library. See the individual method descriptions for lists of the values that each can return. These lists are not necessarily comprehensive.

Syntax

typedef enum {
    D3DXERR_CANNOTMODIFYINDEXBUFFER,
    D3DXERR_INVALIDMESH,
    D3DXERR_CANNOTATTRSORT,
    D3DXERR_SKINNINGNOTSUPPORTED,
    D3DXERR_TOOMANYINFLUENCES,
    D3DXERR_INVALIDDATA,
    D3DXERR_LOADEDMESHASNODATA,
    D3DXERR_DUPLICATENAMEDFRAGMENT,
    D3DXERR_CANNOTREMOVELASTITEM
} D3DXERR;

Constants

D3DXERR_CANNOTMODIFYINDEXBUFFER

The index buffer cannot be modified.

D3DXERR_INVALIDMESH

The mesh is invalid.

D3DXERR_CANNOTATTRSORT

Attribute sort (D3DXMESHOPT_ATTRSORT) is not supported as an optimization technique.

D3DXERR_SKINNINGNOTSUPPORTED

Skinning is not supported.

D3DXERR_TOOMANYINFLUENCES

Too many influences specified.

D3DXERR_INVALIDDATA

The data is invalid.

D3DXERR_LOADEDMESHASNODATA

The mesh has no data.

D3DXERR_DUPLICATENAMEDFRAGMENT

A fragment with that name already exists.

D3DXERR_CANNOTREMOVELASTITEM

The last item cannot be deleted.

Remarks

The facility code _FACDD is used to generate error codes, as in the following macros.

#define _FACDD                  0x876
#define MAKE_DDHRESULT( code )  MAKE_HRESULT( 1, _FACDD, code )
enum _D3DXERR {
    D3DXERR_CANNOTMODIFYINDEXBUFFER = MAKE_DDHRESULT(2900),
    D3DXERR_INVALIDMESH             = MAKE_DDHRESULT(2901),
    ...
    };

Enumerated Type Information

Header | d3dx9.h
Minimum operating systems | Windows 98


D3DXEVENT_TYPE Enumerated Type

Describes the type of events that can be keyed by the animation controller.

Syntax

typedef enum _D3DXEVENT_TYPE {
    D3DXEVENT_TRACKSPEED = 0,
    D3DXEVENT_TRACKWEIGHT = 1,
    D3DXEVENT_TRACKPOSITION = 2,
    D3DXEVENT_TRACKENABLE = 3,
    D3DXEVENT_PRIORITYBLEND = 4,
    D3DXEDT_FORCE_DWORD = 0x7fffffff
} D3DXEVENT_TYPE;

Constants

D3DXEVENT_TRACKSPEED

Track speed.

D3DXEVENT_TRACKWEIGHT

Track weight.

D3DXEVENT_TRACKPOSITION

Track position.

D3DXEVENT_TRACKENABLE

Enable flag.

D3DXEVENT_PRIORITYBLEND

Priority blend value.

D3DXEDT_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Enumerated Type Information

Header | d3dx9anim.h
Minimum operating systems | Windows 98


D3DXIMAGE_FILEFORMAT Enumerated Type

Describes the supported image file formats. See Remarks for descriptions of these formats.

Syntax

typedef enum _D3DXIMAGE_FILEFORMAT {
    D3DXIFF_BMP = 0,
    D3DXIFF_JPG = 1,
    D3DXIFF_TGA = 2,
    D3DXIFF_PNG = 3,
    D3DXIFF_DDS = 4,
    D3DXIFF_PPM = 5,
    D3DXIFF_DIB = 6,
    D3DXIFF_HDR = 7,
    D3DXIFF_PFM = 8,
    D3DXIFF_FORCE_DWORD = 0x7fffffff
} D3DXIMAGE_FILEFORMAT;

Constants

D3DXIFF_BMP

Microsoft Windows bitmap (BMP) file format.

D3DXIFF_JPG

Joint Photographics Experts Group (JPEG) compressed file format.

D3DXIFF_TGA

Truevision (Targa, or TGA) image file format.

D3DXIFF_PNG

Portable Network Graphics (PNG) file format.

D3DXIFF_DDS

Microsoft DirectDraw surface (DDS) file format.

D3DXIFF_PPM

Portable pixmap (PPM) file format.

D3DXIFF_DIB

Windows device-independent bitmap (DIB) file format.

D3DXIFF_HDR

High dynamic range file format.

D3DXIFF_PFM

Portable float map file format.

D3DXIFF_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Functions that begin with D3DXLoad xxx support all of the formats listed. Functions that begin with D3DXSave xxx support all but the Truevision (.tga) and portable pixmap (.ppm) formats.

The following table lists the available input and output formats.

File Extension | Description
.bmp | Windows bitmap format. Contains a header that describes the resolution of the device on which the rectangle of pixels was created, the dimensions of the rectangle, the size of the array of bits, a logical palette, and an array of bits that defines the relationship between pixels in the bitmapped image and entries in the logical palette.
.dds | DirectDraw Surface file format. Stores textures, volume textures, and cubic environment maps, with or without mipmap levels, and with or without pixel compression. See DDS File Reference.
.dib | Windows DIB. Contains an array of bits combined with structures that specify width and height of the bitmapped image, color format of the device where the image was created, and resolution of the device used to create that image.
.hdr | High dynamic range format. Encodes each pixel as an RGBE 32-bit color, with 8 bits of mantissa for red, green, and blue, and a shared 8-bit exponent. Each channel is separately compressed with run-length encoding (RLE).
.jpg | JPEG standard. Specifies variable compression of 24-bit RGB color and 8-bit gray-scale Tagged Image File Format (TIFF) image document files.
.pfm | Portable float map format. A raw floating point image format, without any compression. The file header specifies image width, height, monochrome or color, and machine word order. Pixel data is stored as 32-bit floating point values, with 3 values per pixel for color, and one value per pixel for monochrome.
.png | Portable Network Graphics format. A nonproprietary bitmap format using lossless compression.
.ppm | Portable Pixmap format. A binary or ASCII file format for color images that includes image height and width and the maximum color component value.
.tga | Targa or Truevision Graphics Adapter format. Supports depths of 8, 15, 16, 24, and 32 bits, including 8-bit gray scale, and contains optional color palette data, image (x, y) origin and size data, and pixel data.

See Types of Bitmaps (GDI+) World Wide Web link for more information on some of these formats.

Enumerated Type Information

Header | d3dx9tex.h
Minimum operating systems | Windows 98


D3DXINCLUDE_TYPE Enumerated Type

Describes the location for the include file.

Syntax

typedef enum _D3DXINCLUDE_TYPE {
    D3DXINC_LOCAL = 0,
    D3DXINC_SYSTEM = 1,
    D3DXINC_FORCE_DWORD = 0x7fffffff
} D3DXINCLUDE_TYPE;

Constants

D3DXINC_LOCAL

Look in the local project for the include file.

D3DXINC_SYSTEM

Look in the system path for the include file.

D3DXINC_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Enumerated Type Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98


D3DXMESH Enumerated Type

Flags used to specify creation options for a mesh.

Syntax

typedef enum _D3DXMESH {
    D3DXMESH_32BIT = 0x001,
    D3DXMESH_DONOTCLIP = 0x002,
    D3DXMESH_POINTS = 0x004,
    D3DXMESH_RTPATCHES = 0x008,
    D3DXMESH_NPATCHES = 0x4000,
    D3DXMESH_VB_SYSTEMMEM = 0x010,
    D3DXMESH_VB_MANAGED = 0x020,
    D3DXMESH_VB_WRITEONLY = 0x040,
    D3DXMESH_VB_DYNAMIC = 0x080,
    D3DXMESH_VB_SOFTWAREPROCESSING = 0x8000,
    D3DXMESH_IB_SYSTEMMEM = 0x100,
    D3DXMESH_IB_MANAGED = 0x200,
    D3DXMESH_IB_WRITEONLY = 0x400,
    D3DXMESH_IB_DYNAMIC = 0x800,
    D3DXMESH_IB_SOFTWAREPROCESSING = 0x10000,
    D3DXMESH_VB_SHARE = 0x1000,
    D3DXMESH_USEHWONLY = 0x2000,
    D3DXMESH_SYSTEMMEM = 0x110,
    D3DXMESH_MANAGED = 0x220,
    D3DXMESH_WRITEONLY = 0x440,
    D3DXMESH_DYNAMIC = 0x880,
    D3DXMESH_SOFTWAREPROCESSING = 0x18000
} D3DXMESH;

Constants

D3DXMESH_32BIT

The mesh has 32-bit indices instead of 16-bit indices. See Remarks.

D3DXMESH_DONOTCLIP

Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.

D3DXMESH_POINTS

Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.

D3DXMESH_RTPATCHES

Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.

D3DXMESH_NPATCHES

Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-patch enhancement using Microsoft Direct3D.

D3DXMESH_VB_SYSTEMMEM

Use the D3DPOOL_SYSTEMMEM usage flag for vertex buffers.

D3DXMESH_VB_MANAGED

Use the D3DPOOL_MANAGED usage flag for vertex buffers.

D3DXMESH_VB_WRITEONLY

Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.

D3DXMESH_VB_DYNAMIC

Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.

D3DXMESH_VB_SOFTWAREPROCESSING

Use the D3DUSAGE_SOFTWAREPROCESSING usage flag for vertex buffers.

D3DXMESH_IB_SYSTEMMEM

Use the D3DPOOL_SYSTEMMEM usage flag for index buffers.

D3DXMESH_IB_MANAGED

Use the D3DPOOL_MANAGED usage flag for index buffers.

D3DXMESH_IB_WRITEONLY

Use the D3DUSAGE_WRITEONLY usage flag for index buffers.

D3DXMESH_IB_DYNAMIC

Use the D3DUSAGE_DYNAMIC usage flag for index buffers.

D3DXMESH_IB_SOFTWAREPROCESSING

Use the D3DUSAGE_SOFTWAREPROCESSING usage flag for index buffers.

D3DXMESH_VB_SHARE

Forces the cloned meshes to share vertex buffers.

D3DXMESH_USEHWONLY

Use hardware processing only. For mixed-mode device, this flag will cause the system to use hardware (if supported in hardware) or will default to software processing.

D3DXMESH_SYSTEMMEM

Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.

D3DXMESH_MANAGED

Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.

D3DXMESH_WRITEONLY

Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.

D3DXMESH_DYNAMIC

Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.

D3DXMESH_SOFTWAREPROCESSING

Equivalent to specifying both D3DXMESH_VB_SOFTWAREPROCESSING and D3DXMESH_IB_SOFTWAREPROCESSING.

Remarks

A 32-bit mesh (D3DXMESH_32BIT) can theoretically support (2^32)-1 faces and vertices. However, allocating memory for a mesh that large on a 32-bit operating system is not practical.

Enumerated Type Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98


D3DXMESHDATATYPE Enumerated Type

Defines the type of mesh data present in D3DXMESHDATA.

Syntax

typedef enum D3DXMESHDATATYPE {
    D3DXMESHTYPE_MESH = 0x001,
    D3DXMESHTYPE_PMESH = 0x002,
    D3DXMESHTYPE_PATCHMESH = 0x003,
    D3DXEDT_FORCE_DWORD = 0x7fffffff
} D3DXMESHDATATYPE;

Constants

D3DXMESHTYPE_MESH

The data type is a mesh. See ID3DXMesh.

D3DXMESHTYPE_PMESH

The data type is a progressive mesh. See ID3DXPMesh.

D3DXMESHTYPE_PATCHMESH

The data type is a patch mesh. See ID3DXPatchMesh.

D3DXEDT_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Enumerated Type Information

Header | d3dx9anim.h
Minimum operating systems | Windows 98

See Also

D3DXMESHDATA


D3DXMESHOPT Enumerated Type

Specifies the type of mesh optimization to be performed.

Syntax

typedef enum {
    D3DXMESHOPT_COMPACT = 0x01000000,
    D3DXMESHOPT_ATTRSORT = 0x02000000,
    D3DXMESHOPT_VERTEXCACHE = 0x04000000,
    D3DXMESHOPT_STRIPREORDER = 0x08000000,
    D3DXMESHOPT_IGNOREVERTS = 0x10000000,
    D3DXMESHOPT_DONOTSPLIT = 0x20000000,
    D3DXMESHOPT_DEVICEINDEPENDENT = 0x40000000
} D3DXMESHOPT;

Constants

D3DXMESHOPT_COMPACT

Reorders faces to remove unused vertices and faces.

D3DXMESHOPT_ATTRSORT

Reorders faces to optimize for fewer attribute bundle state changes and enhanced ID3DXBaseMesh::DrawSubset performance.

D3DXMESHOPT_VERTEXCACHE

Reorders faces to increase the cache hit rate of vertex caches.

D3DXMESHOPT_STRIPREORDER

Reorders faces to maximize length of adjacent triangles.

D3DXMESHOPT_IGNOREVERTS

Optimize the faces only; do not optimize the vertices.

D3DXMESHOPT_DONOTSPLIT

While attribute sorting, do not split vertices that are shared between attribute groups.

D3DXMESHOPT_DEVICEINDEPENDENT

Affects the vertex cache size. Using this flag specifies a default vertex cache size that works well on legacy hardware.

Remarks

The D3DXMESHOPT_STRIPREORDER and D3DXMESHOPT_VERTEXCACHE optimization flags are mutually exclusive.

The D3DXMESHOPT_SHAREVB flag has been removed from this enumeration. Use D3DXMESH_VB_SHARE instead, in D3DXMESH.

Enumerated Type Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98


D3DXMESHSIMP Enumerated Type

Specifies simplification options for a mesh.

Syntax

typedef enum _D3DXMESHSIMP {
    D3DXMESHSIMP_VERTEX = 1,
    D3DXMESHSIMP_FACE = 2
} D3DXMESHSIMP;

Constants

D3DXMESHSIMP_VERTEX

The mesh will be simplified by the number of vertices specified in the MinValue parameter.

D3DXMESHSIMP_FACE

The mesh will be simplified by the number of faces specified in the MinValue parameter.

Enumerated Type Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

See Also

D3DXGeneratePMesh, D3DXSimplifyMesh


D3DXPARAMETER_CLASS Enumerated Type

The type of object.

Syntax

typedef enum _D3DXPARAMETER_CLASS {
    D3DXPC_SCALAR,
    D3DXPC_VECTOR,
    D3DXPC_MATRIX_ROWS,
    D3DXPC_MATRIX_COLUMNS,
    D3DXPC_OBJECT,
    D3DXPC_STRUCT,
    D3DXPC_FORCE_DWORD = 0x7fffffff
} D3DXPARAMETER_CLASS;

Constants

D3DXPC_SCALAR

Constant is a scalar.

D3DXPC_VECTOR

Constant is a vector.

D3DXPC_MATRIX_ROWS

Constant is a row major matrix.

D3DXPC_MATRIX_COLUMNS

Constant is a column major matrix.

D3DXPC_OBJECT

Constant is either a texture, shader or a string.

D3DXPC_STRUCT

Constant is a structure.

D3DXPC_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Enumerated Type Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

See Also

D3DXSHADER_TYPEINFO, D3DXCONSTANT_DESC


D3DXPARAMETER_TYPE Enumerated Type

Describes the data contained by the enumeration.

Syntax

typedef enum _D3DXPARAMETER_TYPE {
    D3DXPT_VOID,
    D3DXPT_BOOL,
    D3DXPT_INT,
    D3DXPT_FLOAT,
    D3DXPT_STRING,
    D3DXPT_TEXTURE,
    D3DXPT_TEXTURE1D,
    D3DXPT_TEXTURE2D,
    D3DXPT_TEXTURE3D,
    D3DXPT_TEXTURECUBE,
    D3DXPT_SAMPLER,
    D3DXPT_SAMPLER1D,
    D3DXPT_SAMPLER2D,
    D3DXPT_SAMPLER3D,
    D3DXPT_SAMPLERCUBE,
    D3DXPT_PIXELSHADER,
    D3DXPT_VERTEXSHADER,
    D3DXPT_PIXELFRAGMENT,
    D3DXPT_VERTEXFRAGMENT,
    D3DXPT_FORCE_DWORD = 0x7fffffff
} D3DXPARAMETER_TYPE;

Constants

D3DXPT_VOID

Parameter is a void pointer.

D3DXPT_BOOL

Parameter is a Boolean. Any non-zero value passed into ID3DXConstantTable::SetBool, ID3DXConstantTable::SetBoolArray, ID3DXConstantTable::SetValue, ID3DXConstantTable::SetVector, or ID3DXConstantTable::SetVectorArray will be mapped to 1 (TRUE) before being written into the constant table; otherwise, the value will be set to 0 in the constant table.

D3DXPT_INT

Parameter is an integer. Any floating-point values passed into ID3DXConstantTable::SetValue, ID3DXConstantTable::SetVector, or ID3DXConstantTable::SetVectorArray will be rounded off (to zero decimal places) before being written into the constant table.

D3DXPT_FLOAT

Parameter is a floating-point number.

D3DXPT_STRING

Parameter is a string.

D3DXPT_TEXTURE

Parameter is a texture.

D3DXPT_TEXTURE1D

Parameter is a 1-D texture.

D3DXPT_TEXTURE2D

Parameter is a 2-D texture.

D3DXPT_TEXTURE3D

Parameter is a 3-D texture.

D3DXPT_TEXTURECUBE

Parameter is a cube texture.

D3DXPT_SAMPLER

Parameter is a sampler.

D3DXPT_SAMPLER1D

Parameter is a 1-D sampler.

D3DXPT_SAMPLER2D

Parameter is a 2-D sampler.

D3DXPT_SAMPLER3D

Parameter is a 3-D sampler.

D3DXPT_SAMPLERCUBE

Parameter is a cube sampler.

D3DXPT_PIXELSHADER

Parameter is a pixel shader.

D3DXPT_VERTEXSHADER

Parameter is a vertex shader.

D3DXPT_PIXELFRAGMENT

Parameter is a pixel shader fragment.

D3DXPT_VERTEXFRAGMENT

Parameter is a vertex shader fragment.

D3DXPT_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Enumerated Type Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

See Also

D3DXSHADER_TYPEINFO, D3DXCONSTANT_DESC


D3DXPATCHMESH Enumerated Type

Not used. Use D3DXPATCHMESHTYPE instead to specify mesh patch types.

Syntax

typedef enum _D3DXPATCHMESH {
    D3DXPATCHMESH_DEFAULT = 0
} D3DXPATCHMESH;

Constants

D3DXPATCHMESH_DEFAULT

Not used.

Enumerated Type Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98


D3DXPATCHMESHTYPE Enumerated Type

Mesh patch types.

Syntax

typedef enum _D3DXPATCHMESHTYPE {
    D3DXPATCHMESH_RECT = 0x001,
    D3DXPATCHMESH_TRI = 0x002,
    D3DXPATCHMESH_NPATCH = 0x003,
    D3DXPATCHMESH_FORCE_DWORD = 0x7fffffff
} D3DXPATCHMESHTYPE;

Constants

D3DXPATCHMESH_RECT

Rectangle patch mesh type.

D3DXPATCHMESH_TRI

Triangle patch mesh type.

D3DXPATCHMESH_NPATCH

N-patch mesh type.

D3DXPATCHMESH_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Triangle patches have three sides and are described in D3DTRIPATCH_INFO. Rectangle patches are four-sided and are described in D3DRECTPATCH_INFO.

Enumerated Type Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

See Also

Using Higher-Order Primitives


D3DXPLAYBACK_TYPE Enumerated Type

Defines the type of animation set looping modes used for playback.

Syntax

typedef enum _D3DXPLAYBACK_TYPE {
    D3DXPLAY_LOOP = 0,
    D3DXPLAY_ONCE = 1,
    D3DXPLAY_PINGPONG = 2,
    D3DXEDT_FORCE_DWORD = 0x7fffffff
} D3DXPLAYBACK_TYPE;

Constants

D3DXPLAY_LOOP

The animation repeats endlessly.

D3DXPLAY_ONCE

The animation plays once, and then it stops on the last frame.

D3DXPLAY_PINGPONG

The animation alternates endlessly between playing forward and playing backward.

D3DXEDT_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Enumerated Type Information

Header | d3dx9anim.h
Minimum operating systems | Windows 98


D3DXPRIORITY_TYPE Enumerated Type

Defines the priority type an animation track is assigned to.

Syntax

typedef enum _D3DXPRIORITY_TYPE {
    D3DXPRIORITY_LOW = 0,
    D3DXPRIORITY_HIGH = 1,
    D3DXEDT_FORCE_DWORD = 0x7fffffff
} D3DXPRIORITY_TYPE;

Constants

D3DXPRIORITY_LOW

Track should be blended with all the low-priority tracks before the low-priority blend is mixed with the high-priority blend.

D3DXPRIORITY_HIGH

Track should be blended with all the high-priority tracks before the high-priority blend is mixed with the low-priority blend.

D3DXEDT_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Tracks with the same priority are blended together, and the two resulting values are then blended using the priority blend factor.

Enumerated Type Information

Header | d3dx9anim.h
Minimum operating systems | Windows 98


D3DXREGISTER_SET Enumerated Type

Data type of the register.

Syntax

typedef enum _D3DXREGISTER_SET {
    D3DXRS_BOOL,
    D3DXRS_INT4,
    D3DXRS_FLOAT4,
    D3DXRS_SAMPLER,
    D3DXPC_FORCE_DWORD = 0x7fffffff
} D3DXREGISTER_SET;

Constants

D3DXRS_BOOL

Boolean value.

D3DXRS_INT4

4-D integer number.

D3DXRS_FLOAT4

4-D floating-point number.

D3DXRS_SAMPLER

The register contains 4-D sampler data.

D3DXPC_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Enumerated Type Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98

See Also

D3DXSHADER_CONSTANTINFO, D3DXCONSTANT_DESC


D3DXSHCOMPRESSQUALITYTYPE Enumerated Type

Spherical harmonic compression setting.

Syntax

typedef enum D3DXSHCOMPRESSQUALITYTYPE {
    D3DXSHCQUAL_FASTLOWQUALITY = 1,
    D3DXSHCQUAL_SLOWHIGHQUALITY = 2,
    D3DXSHCQUAL_FORCE_DWORD = 0x7fffffff
} D3DXSHCOMPRESSQUALITYTYPE;

Constants

D3DXSHCQUAL_FASTLOWQUALITY

The data compression is low quality, but is fast to compress.

D3DXSHCQUAL_SLOWHIGHQUALITY

The data compression is high quality, but is slow to compress.

D3DXSHCQUAL_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Enumerated Type Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98


D3DXSHGPUSIMOPT Enumerated Type

Describes the resolution of the shadow z-buffer that will be used in precomputed radiance transfer (PRT) direct lighting simulation on the GPU. A higher quality z-buffer can also be specified to reduce noise in the results of the direct lighting simulation, although the simulation will be slower.

Syntax

typedef enum D3DXSHGPUSIMOPT {
    D3DXSHGPUSIMOPT_SHADOWRES256 = 1,
    D3DXSHGPUSIMOPT_SHADOWRES512 = 0,
    D3DXSHGPUSIMOPT_SHADOWRES1024 = 2,
    D3DXSHGPUSIMOPT_SHADOWRES2048 = 3,
    D3DXSHGPUSIMOPT_HIGHQUALITY = 4,
    D3DXSHGPUSIMOPT_FORCE_DWORD = 0x7fffffff
} D3DXSHGPUSIMOPT;

Constants

D3DXSHGPUSIMOPT_SHADOWRES256

Low resolution simulation. A 256 x 256 pixel texture is used in the simulation to encode the shadow z-buffer.

D3DXSHGPUSIMOPT_SHADOWRES512

Medium resolution simulation. A 512 x 512 pixel texture is used in the simulation to encode the shadow z-buffer.

This is the default value.

D3DXSHGPUSIMOPT_SHADOWRES1024

High resolution simulation. A 1024 x 1024 pixel texture is used in the simulation to encode the shadow z-buffer.

D3DXSHGPUSIMOPT_SHADOWRES2048

Highest resolution simulation. A 2048 x 2048 pixel texture is used in the simulation to encode the shadow z-buffer.

D3DXSHGPUSIMOPT_HIGHQUALITY

The simulation is of high precision, regardless of the selected resolution. Setting this value will reduce noise in the results of the direct lighting simulation, although the simulation will be slower. May be combined with one of the D3DXSHGPUSIMOPT_SHADOWRESxxx values.

D3DXSHGPUSIMOPT_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Only one of the D3DXSHGPUSIMOPT_SHADOWRESxxx values should be specified. D3DXSHGPUSIMOPT_HIGHQUALITY may be combined with one of the D3DXSHGPUSIMOPT_SHADOWRESxxx values.

Enumerated Type Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98


D3DXTRANSITION_TYPE Enumerated Type

Defines the transition style between values of a mesh animation.

Syntax

typedef enum _D3DXTRANSITION_TYPE {
    D3DXTRANSITION_LINEAR = 0x000,
    D3DXTRANSITION_EASEINEASEOUT = 0x001,
    D3DXEDT_FORCE_DWORD = 0x7fffffff
} D3DXTRANSITION_TYPE;

Constants

D3DXTRANSITION_LINEAR

Linear transition between values.

D3DXTRANSITION_EASEINEASEOUT

Ease-in, ease-out spline transition between values.

D3DXEDT_FORCE_DWORD

Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The calculation for the ramp from ease in to ease out is calculated as follows:

Q(t) = 2(x - y)t3 + 3(y - x)t2 + x.

where the ramp is a function Q(t) with the following properties:

  • Q(t) is a cubic spline.
  • Q(t) interpolates between x and y as t ranges from 0 to 1.
  • Q(t) is horizontal when t = 0 and t = 1.

Mathematically, this translates into:

Q(t) = At3 + Bt2 + Ct + D (and therefore, Q'(t) = 3At2 + 2Bt + C)
2a) Q(0) = x
2b) Q(1) = y

3a) Q'(0) = 0
3b) Q'(1) = 0

Solving for A, B, C, D:

D = x   (from 2a)
C = 0  (from 3a)
3A + 2B = 0 (from 3b)
A + B = y - x (from 2b and D = x)

Therefore:

A = 2(x - y), B = 3(y - x), C = 0, D = x.

Enumerated Type Information

Header | d3dx9anim.h
Minimum operating systems | Windows 98


D3DXWELDEPSILONSFLAGS Enumerated Type

Options for welding together vertices.

Syntax

typedef enum {
    D3DXWELDEPSILONS_WELDALL = 1,
    D3DXWELDEPSILONS_WELDPARTIALMATCHES = 2,
    D3DXWELDEPSILONS_DONOTREMOVEVERTICES = 4,
    D3DXWELDEPSILONS_DONOTSPLIT = 8
} D3DXWELDEPSILONSFLAGS;

Constants

D3DXWELDEPSILONS_WELDALL

Weld together all vertices that are at the same location. Using this flag avoids an epsilon comparison between vertex components.

D3DXWELDEPSILONS_WELDPARTIALMATCHES

If a given vertex component is within epsilon, modify partially matched vertices so that both components are identical. If all components are equal, remove one of the vertices.

D3DXWELDEPSILONS_DONOTREMOVEVERTICES

Instructs the weld to allow only modifications to vertices and not removal. This flag is valid only if D3DXWELDEPSILONS_WELDPARTIALMATCHES is set. It is useful to modify vertices to be equal, but not to allow vertices to be removed.

D3DXWELDEPSILONS_DONOTSPLIT

Instructs the weld not to split vertices that are in separate attribute groups. When the ID3DXMesh::Optimize, ID3DXPMesh::Optimize, or ID3DXPMesh::OptimizeBaseLOD methods are called with the D3DXMESHOPT_ATTRSORT flag, then the D3DXMESHOPT_DONOTSPLIT flag will also be set.

Setting this flag can slow down software vertex processing.

Enumerated Type Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

See Also

D3DXWELDEPSILONS


MAX_FVF_DECL_SIZE Enumerated Type

Defines the maximum number of vertex declarators for a mesh.

Syntax

typedef enum {
    MAX_FVF_DECL_SIZE = MAXD3DDECLLENGTH + 1
} MAX_FVF_DECL_SIZE;

Constants

MAX_FVF_DECL_SIZE

The maximum number of elements in the vertex declaration. The additional (+1) is for D3DDECL_END.

Remarks

MAXD3DDECLLENGTH is defined as a maximum of 64 (see d3d9types.h). This does not include the "end" marker vertex element.

Enumerated Type Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

See Also

ID3DXBaseMesh, IDirect3DVertexDeclaration9::GetDeclaration, ID3DXSPMesh::GetDeclaration, D3DXDeclaratorFromFVF, ID3DXSkinInfo


Constants
Microsoft DirectX 9.0 SDK Update (October 2004)

Constants

This section contains reference information for the constants defined in D3DX.

  • D3DX_CHANNEL - Texture channel constants
  • D3DXERR - Error constants
  • D3DX_FILTER - Texture filter constants
  • D3DX_NORMALMAP - Normal map generation constants
  • D3DXSHADER Compile Options - Shader compile options
  • D3DXSPRITE - Sprite render constants
  • Other D3DX Constants - Other constants


D3DX_CHANNEL
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DX_CHANNEL

The following flags are used to specify which channels in a texture to operate on.

#define | Description
D3DX_CHANNEL_RED | Indicates the red channel should be used.
D3DX_CHANNEL_BLUE | Indicates the blue channel should be used.
D3DX_CHANNEL_GREEN | Indicates the green channel should be used.
D3DX_CHANNEL_ALPHA | Indicates the alpha channel should be used.
D3DX_CHANNEL_LUMINANCE | Indicates the luminances of the red, green, and blue channels should be used.

Constant Information

Header | d3dx9tex.h
Minimum operating system | Windows 98


D3DX_FILTER
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DX_FILTER

The following flags are used to specify which channels in a texture to operate on.

#define | Description
D3DX_FILTER_NONE | No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT | Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_LINEAR | Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_TRIANGLE | Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.
D3DX_FILTER_BOX | Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_MIRROR_U | Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V | Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W | Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR | Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX_FILTER_DITHER | The resulting image must be dithered using a 4x4 ordered dither algorithm.
D3DX_FILTER_SRGB_IN | Input data is in sRGB (gamma 2.2) color space.
D3DX_FILTER_SRGB_OUT | The output data is in sRGB (gamma 2.2) color space.
D3DX_FILTER_SRGB | Same as specifying D3DX_FILTER_SRGB_IN | D3DX_FILTER_SRGB_OUT.

Each valid filter must contain exactly one of the following flags: D3DX_FILTER_NONE, D3DX_FILTER_POINT, D3DX_FILTER_LINEAR, D3DX_FILTER_TRIANGLE, or D3DX_FILTER_BOX. In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter: D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, D3DX_FILTER_MIRROR_W, D3DX_FILTER_MIRROR, D3DX_FILTER_DITHER, D3DX_FILTER_SRGB_IN, D3DX_FILTER_SRGB_OUT or D3DX_FILTER_SRGB.

Specifying D3DX_DEFAULT for this parameter is usually the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER. However, D3DX_DEFAULT can have different meanings, depending on which method uses the filter. For example:

  • When using D3DXCreateTextureFromFileEx, D3DX_DEFAULT maps to D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
  • When using D3DXFilterTexture, D3DX_DEFAULT maps to D3DX_FILTER_BOX if the texture size is a power of two, and D3DX_FILTER_BOX | D3DX_FILTER_DITHER otherwise.

Reference each method to check for information about how D3DX_DEFAULT filter is mapped.

Constant Information

Header | d3dx9tex.h
Minimum operating system | Windows 98


D3DX_NORMALMAP
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DX_NORMALMAP

Normal maps generation constants.

#define | Description
D3DX_NORMALMAP_MIRROR_U | Indicates that pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_NORMALMAP_MIRROR_V | Indicates that pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_NORMALMAP_MIRROR | Same as specifying D3DX_NORMALMAP_MIRROR_U | D3DX_NORMALMAP_MIRROR_V.
D3DX_NORMALMAP_INVERTSIGN | Inverts the direction of each normal.
D3DX_NORMALMAP_COMPUTE_OCCLUSION | Computes the per-pixel occlusion term and encodes it into the alpha. An alpha of 1 means that the pixel is not obscured in any way, and an alpha of 0 means that the pixel is completely obscured.

Constant Information

Header | d3dx9tex.h
Minimum operating system | Windows 98

Related Topics

  • D3DXComputeNormalMap


D3DXSHADER Compile Options
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DXSHADER Compile Options

Control the compile options during a shader compile.

#define | Description
D3DXSHADER_AVOID_FLOW_CONTROL | This is a hint to the compiler to avoid using flow-control instructions.
D3DXSHADER_DEBUG | Insert debug filename, line numbers, and type and symbol information during shader compile.
D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT | Force the compiler to compile against the next highest available software target for pixel shaders. This flag also turns optimizations off and debugging on.
D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT | Force the compiler to compile against the next highest available software target for vertex shaders. This flag also turns optimizations off and debugging on.
D3DXSHADER_NO_PRESHADER | Disables preshaders. The compiler will not pull out static expressions for evaluation on the host CPU. Additionally, the compiler will not loft any expressions when compiling stand-alone functions.
D3DXSHADER_PACKMATRIX_COLUMNMAJOR | Unless explicitly specified, matrices will be packed in column-major order (each vector will be in a single column) when passed to and from the shader. This is generally more efficient because it allows vector-matrix multiplication to be performed using a series of dot products.
D3DXSHADER_PACKMATRIX_ROWMAJOR | Unless explicitly specified, matrices will be packed in row-major order (each vector will be in a single row) when passed to or from the shader.
D3DXSHADER_PARTIALPRECISION | Force all computations in the resulting shader to occur at partial precision. This may result in faster evaluation of shaders on some hardware.
D3DXSHADER_PREFER_FLOW_CONTROL | This is a hint to the compiler to prefer using flow-control instructions.
D3DXSHADER_SKIPOPTIMIZATION | Instruct the compiler to skip optimization steps during code generation. Unless you are trying to isolate a problem in your code and you suspect the compiler, using this option is not recommended.
D3DXSHADER_SKIPVALIDATION | Do not validate the generated code against known capabilities and constraints. This option is recommended only when compiling shaders that are known to work (that is, shaders that have compiled before without this option). Shaders are always validated by the runtime before they are set to the device.

Constant Information

Header | d3dx9shader.h
Minimum operating system | Windows 98

Related Topics

  • ID3DXEffectCompiler::CompileEffect


D3DXSPRITE
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DXSPRITE

The following flags are used to specify sprite rendering options.

#define | Description
D3DXSPRITE_DONOTSAVESTATE | The device state is not to be saved or restored when ID3DXSprite::Begin or ID3DXSprite::End is called.
D3DXSPRITE_DONOTMODIFY_RENDERSTATE | The device render state is not to be changed when ID3DXSprite::Begin is called. The device is assumed to be in a valid state to draw vertices containing UsageIndex = 0 in the D3DDECLUSAGE_POSITION, D3DDECLUSAGE_TEXCOORD, and D3DDECLUSAGE_COLOR data.
D3DXSPRITE_OBJECTSPACE | The world, view, and projection transforms are not modified. The transforms currently set to the device are used to transform the sprites when the batched sprites are drawn (when ID3DXSprite::Flush or ID3DXSprite::End is called). If this flag is not specified, then world, view, and projection transforms are modified so that sprites are drawn in screen-space coordinates.
D3DXSPRITE_BILLBOARD | Each sprite will be rotated about its center so that it is facing the viewer. ID3DXSprite::SetWorldViewLH or ID3DXSprite::SetWorldViewRH must be called first.
D3DXSPRITE_ALPHABLEND | Enables alpha blending with D3DRS_ALPHATESTENABLE set to TRUE (for nonzero alpha). D3DBLEND_SRCALPHA will be the source blend state, and D3DBLEND_INVSRCALPHA will be the destination blend state in calls to IDirect3DDevice9::SetRenderState. See Alpha Blending State. ID3DXFont expects this flag to be set when drawing text.
D3DXSPRITE_SORT_TEXTURE | Sprites are sorted by texture prior to drawing. This procedure is recommended when drawing non-overlapping sprites of uniform depth. For example, use this procedure when drawing screen-aligned text with ID3DXFont.
D3DXSPRITE_SORT_DEPTH_FRONTTOBACK | Sprites are sorted by depth in front-to-back order prior to drawing. This procedure is recommended when drawing opaque sprites of varying depths.
D3DXSPRITE_SORT_DEPTH_BACKTOFRONT | Sprites are sorted by depth in back-to-front order prior to drawing. This procedure is recommended when drawing transparent sprites of varying depths.

Constant Information

Header | d3dx9core.h
Minimum operating system | Windows 98


Other D3DX Constants
Microsoft DirectX 9.0 SDK Update (October 2004)

Other D3DX Constants

Other D3DX constants include the following:

16-Bit Floating Point Numbers

#define | Value | Description
D3DX_16F_DIG | 3 | Number of decimal digits of precision
D3DX_16F_EPSILON | 4.8875809e-4f | Smallest such that 1.0 + epsilon != 1.0
D3DX_16F_MANT_DIG | 11 | Number of bits in mantissa
D3DX_16F_MAX | 6.5519996e+4f | Maximum value
D3DX_16F_MAX_10_EXP | 4 | Maximum decimal exponent
D3DX_16F_MAX_EXP | 15 | Maximum binary exponent
D3DX_16F_MIN | 6.1035156e-5f | Minimum positive value
D3DX_16F_MIN_10_EXP | (-4) | Minimum decimal exponent
D3DX_16F_MIN_EXP | (-12) | Minimum binary exponent
D3DX_16F_RADIX | 2 | Exponent radix
D3DX_16F_ROUNDS | 1 | Addition rounding: near
D3DX_1BYPI | ((FLOAT) 0.318309886f) | 1/pi
D3DX_PI | ((FLOAT) 3.141592654f) | pi

These #defines are declared in D3dx9math.h.

PRT Constants

#define | Value | Description
D3DXSH_MINORDER | 2 | Lowest allowable order of the simulation.
D3DXSH_MAXORDER | 6 | Highest allowable order of the simulation.

These #defines are declared in D3dx9math.h. For more about precomputed radiance transfer (PRT), see Precomputed Radiance Transfer.

Texture Constants

#define | Description
D3DFMT_FROM_FILE | Take the format exactly from a file.
D3DX_DEFAULT | A default value.
D3DX_DEFAULT_NONPOW2 | Do not round up numbers such as width or height to a power of two.
D3DX_FROM_FILE | Take the texture dimensions exactly from a file.

These #defines are declared in D3dx9.h.

Internal Use Constants

The following constants are used internally:

#define | Value
UNUSED16 | 0xffff
UNUSED32 | 0xffffffff

These #defines are declared in D3dx9mesh.h.

#define | Value
D3DX_VERSION | 0x0902
D3DX_SDK_VERSION | 22

These #defines are declared in D3dx9core.h.

#define | Value
D3DX_DEFAULT_FLOAT | FLT_MAX

This #defines is declared in D3dx9.h.

Constant Information

Minimum operating system Windows 98


HLSL Shader Reference
Microsoft DirectX 9.0 SDK Update (October 2004)

HLSL Shader Reference

  • Variable Declaration Syntax
    • Basic Types
    • Vector Type Syntax
    • Matrix Type Syntax
    • Shader Type Syntax
    • Sampler Type Syntax
    • User-Defined Type Syntax
  • Function Declaration Syntax
    • Function Parameter List Syntax
    • Statement Block Syntax
  • Flow Control Statement Syntax
  • Shader Semantic Syntax
  • Fragment Declaration Syntax
  • Appendix

Related Topics

  • HLSL Shaders


Variable Declaration Syntax
Microsoft DirectX 9.0 SDK Update (October 2004)

Variable Declaration Syntax

Syntax

Variables are declared with one or more of the following components:

[Storage Class Modifiers] [Type Modifiers]
  Type VariableName[Array_Index]
    [: Semantic] [Initializers] [Annotations] [: Register];

Storage Class Modifiers

Storage class modifiers are optional keywords that give the compiler hints about variable scope and lifetime.

Global variable declarations prefixed with the uniform keyword are uniform inputs to the shader. All non-static global variables are uniform by default.

Global variable declarations can be prefixed with the shared keyword. This a hint to the effect framework that the value of this parameter is intended to be shared between effect objects.

extern | A global variable marked extern is an external input to the shader. To set an extern variable, use any of the set methods ("SetVertexShaderConstantX") or any of the ID3DXConstantTable interface methods. A global variable that is not declared to be either static or extern is assumed to be extern. You cannot declare a global variable with both extern and static.
shared | Global shader variables that can be shared between effects use the shared keyword.
static | The static keyword is interpreted differently on a global variable and a local variable. For a local variable (declared inside of a function), the static keyword indicates that the value of the variable persists between funtion invocations. Initialization of local static variables happens only once. If they are not explicitly initialized, their initial value is assumed to be zero. For a global variable (declared outside of any function), the static keyword indicates that the shader variable will not be visible to an application. Since it is not visible, the get and set methods ("GetVertexShaderConstantX" or "SetVertexShaderConstantX") will not work, and the ID3DXConstantTable methods will not work.
uniform | Use the uniform keyword to mark a uniform shader variable. This is a variable that is initialized in the constant registers with the ID3DXConstantTable interface. All the vertices (if you are using a vertex shader) or pixels (if you are using a pixel shader) see the same initial value in a uniform variable. Global variables are treated as if they are declared uniform.
volatile | On global variables, this is a hint to the effect framework that the value of this parameter changes frequently.

Storage class modifiers are optional and may be specified in any order, as long as they occur before the variable type.

Type Modifiers

Type modifiers are optional keywords placed immediately before the variable type, which give the compiler additional information about the data type.

const | The const modifier indicates a variable whose value cannot be changed by a shader. Declaring a variable with const allows the compiler to put the value in a portion of memory that does not need write access. Because the variable cannot be changed, it must be initialized in the declaration.
row_major | Matrix elements are organized in row-major order; that is, each row of the matrix will be stored in a single constant register.
col_major | Matrix elements are organized in column-major order; that is, each column of the matrix will be stored in a single constant register.

Type

Any valid type including:

  • basic types
  • vector types
  • matrix types
  • shader types
  • sampler type
  • struct type
  • user defined types.

VariableName[Array_Index]

An ASCII string that uniquely identifies the name of a variable within a shader. Each variable can be defined as a single variable or optionally as an array of variables. Array_Index is the optional array size and is specified as a positive integer greater than or equal to 1.

Semantic

Shader parameters marked with semantics contain varying data. Semantics can mark any parameter, but only the semantics attached to top-level parameters are used at compile time by high-level shader language (HLSL). Semantics have no meaning in the language, they are simply associated with the variable and passed down to the back-end. Semantics are not case-sensitive. For a listing of the vertex and pixel shader semantics, see the shader semantic syntax.

Initializers

An initializer is an optional, default value. For good practice, the number of initializers should match the number of components in the data type.

For global variables marked extern, each expression must be a literal value. For other global variables and local variables marked static, each expression must be a constant.

Annotations

Annotations are metadata attached to global variables. They are ignored by HLSL, but used by effects. They cannot be referenced from a shader. See Add Information to Effect Parameters with Annotations.

Register

An optional constant register. Use this to assign a variable to a particular constant register. If the variable type will not fit into a single register, consecutive registers are used. See Binding a Shader Parameter to a Particular Register.

Remarks

Here are a few sample declarations:

float4 color;
uniform float4 position : POSITION;
const float3 lightDirection = {0,0,1};


Basic Types
Microsoft DirectX 9.0 SDK Update (October 2004)

Basic Types

High-level shader language (HLSL) supports the following scalar types:

BOOL | true or false (Boolean)
int | 32-bit signed integer
half | 16-bit floating point value
float | 32-bit floating point value
double | 64-bit floating point value

Not all target platforms have native support for integer values. Integer values may need to be emulated using floating point hardware. Integer operations that go outside the range (of integers that can be expressed as floats) are not guaranteed to function as expected.

Not all target platforms have native support for half or double values. If the target platform does not, these are emulated using float. Intermediate results of floating point expressions may be evaluated at a precision higher than the operands or the result.

HLSL also supports the ASCII string type. There are no operations or states that accept strings. String parameters and annotations can, however, be queried by effects.


Vector Type Syntax
Microsoft DirectX 9.0 SDK Update (October 2004)

Vector Type Syntax

A vector is a special data type that contains between one and four components. Every component of a vector must be of the same type.

Syntax

Type Number VariableName

where:

Type | The data type, which is one of the basic types.
Number | A positive integer that specifies the number of components. A vector must have at least one component, and can have no more than of four components.
VariableName | An ASCII string that uniquely identifies the variable name.

Remarks

Here are some examples:

bool    bVector;   // scalar containing 1 Boolean
half2   hVector;   // vector containing 2 halfs
int1    iVector = 1;
float3  fVector = { 0.2f, 0.3f, 0.4f };

A vector can be declared using this syntax also:

vector <Type, Number> VariableName

Here are some examples:

vector <int,    1> iVector = 1;
vector <double, 4> dVector = { 0.2, 0.3, 0.4, 0.5 };


Matrix Type Syntax
Microsoft DirectX 9.0 SDK Update (October 2004)

Matrix Type Syntax

A matrix is a special data type that contains between one and sixteen components. Every component of a matrix must be of the same type.

Syntax

TypeRxC VariableName

where:

TypeRxC | Identifies the data types, and number of components in each row and column. The type is one of the basic types. The number of rows and columns is a positive integer between 1 and 4.
VariableName | An ASCII string that uniquely identifies the variable name.

Remarks

Here are some examples:

int1x1    iMatrix;   // integer matrix with 1 row,  1 column
int4x1    iMatrix;   // integer matrix with 4 rows, 1 column
int1x4    iMatrix;   // integer matrix with 1 row, 4 columns
double3x3 dMatrix;   // double matrix with 3 rows, 3 columns

float2x2 fMatrix = { 0.0f, 0.1, // row 1
                     2.1f, 2.2f // row 2
                   };

A matrix can be declared using this syntax also:

matrix <Type, Number> VariableName

The matrix type uses the angle brackets to specify the type, the number of rows, and the number of columns. This example creates a floating-point matrix, with two rows and two columns. Any of the scalar data types can be used.

Here is an example:

matrix <float, 2, 2> fMatrix = { 0.0f, 0.1, // row 1
                                 2.1f, 2.2f // row 2
                               };


Shader Type Syntax
Microsoft DirectX 9.0 SDK Update (October 2004)

Shader Type Syntax

Syntax

ShaderType vs = compile vs_2_0 psmain();

or

ShaderType ShaderName [= asm { ShaderAssemblyInstructions }];

where:

ShaderType | Can be either vertexshader or pixelshader.
ShaderName | An ASCII string that uniquely identifies the name of a variable within a shader.
ShaderAssemblyInstructions | Optional. Any set of assembly instructions. For vertex shader and pixel shader assembly instructions, see Asm Shader Reference.

Remarks

Vertex Shader

A vertexshader object represents a vertex shader object. While no operation within a shader function directly accepts vertex shaders, a vertex shader can be set to the device from within a technique.

Literal vertexshader values can be expressed as an assembly block in one line,

vertexshader vs = asm { vs.2.0 mov oC0, c0 };

or across several lines,

vertexshader vs =
  asm
  {
    vs_2_0
    mov oC0, c0
  };

or as a compile call.

vertexshader vs = compile vs_2_0 psmain();

Pixel Shader

A pixelshader object represents a pixel shader object. While no operation within a shader function directly accepts pixel shaders, a pixel shader can be set to the device from within a technique.

Literal pixelshader values can be expressed as an assembly block in one line,

pixelshader ps = asm { ps.2.0 mov oC0, c0 };

or across several lines,

pixelshader ps =
  asm
  {
    ps_2_0
    mov oC0, c0
  };

or as a compile call.

pixelshader ps = compile ps_2_0 psmain();


Sampler Type Syntax
Microsoft DirectX 9.0 SDK Update (October 2004)

Sampler Type Syntax

Syntax

sampler SamplerName[Array_Index] [= Initializers];

where:

sampler | The sampler keyword must appear here.
SamplerName[Array_Index] | An ASCII string that uniquely identifies the name of a variable within a shader. Each variable can be defined as a single variable or optionally as an array of variables. Array_Index is the optional array size and is specified as a positive integer greater than or equal to 1.
Initializers Initializers specify default sampler state. Initializers are optional. If initializers are used, they must appear within a statement block (delimited by {}) with the sampler_state keyword as shown here:
= sampler_state
{
  ...; // sampling state
  ...; // sampling state
};

Remarks

This sampler is initialized with linear filtering.

sampler s = sampler_state
{
  texture = NULL;
  mipfilter = LINEAR;
};


Struct Type Syntax
Microsoft DirectX 9.0 SDK Update (October 2004)

Struct Type Syntax

A struct is a user-customizable data type that contains any number of components. Each component of a struct must be one of the basic data types.

Syntax

struct
{
   Type[RxC] VariableName;
   ...
}

where:

Type[RxC] | A structure member. Each member has a data type, and and optional number of components in each row and column. The type is one of the basic types. The number of rows and columns is a positive integer between 1 and 4.
VariableName | An ASCII string that uniquely identifies the variable name.
... | Any number of additional members.

Remarks

Here are some examples:

struct struct1
{
  int    a;   // single integer
}

struct struct2
{
  int    a;         // single integer
  float  b;         // single float
  int4x1 iMatrix;   // integer matrix with 4 rows, 1 column
}

When compiled into shader code using the HLSL Command-Line Compiler, each structure member is assigned to a separate shader register, which is consistent with how variables are packed by a language compiler.

struct L
{
  float4 pos;
  float3 diff;
  float  att;
};

Even though the second and third members could theoretically be packed into a single, four-component register, the compiler will assign pos to the first available register, diff to the second available register, and att to the third available register.


User Defined Type Syntax
Microsoft DirectX 9.0 SDK Update (October 2004)

User Defined Type Syntax

In addition to the built-in intrinsic data types, high-level shader language (HLSL) supports user-defined or custom types which follow this syntax:

Syntax

typedef [const] type id [array_suffix];

where:

typedef | Declares a name for a type.
const | This keyword explicitly marks the type as a constant.
type | Identifies the data type, it must be one of the HLSL intrinsic data types.
id | Identifies the variable name.
array_suffix | Optional array brackets identify whether the variable contains a single value, or contains an array of values.

Remarks

For compatibility with Microsoft DirectX 8.0 effects, the following types are automatically defined at super-global scope:

typedef int DWORD;
typedef float FLOAT;
typedef vector <float, 4> VECTOR;
typedef matrix <float, 4, 4> MATRIX;
typedef string STRING;
typedef texture TEXTURE;
typedef pixelshader PIXELSHADER;
typedef vertexshader VERTEXSHADER;

These types are not case-insensitive.

For convenience, the following types are automatically defined at super-global scope. Note that the pound sign (#) represents an integer digit between 1 and 4.

typedef vector <bool, #> bool#;
typedef vector <int, #> int#;
typedef vector <half, #> half#;
typedef vector <float, #> float#;
typedef vector <double, #> double#;

typedef matrix <bool, #, #> bool#x#;
typedef matrix <int, #, #> int#x#;
typedef matrix <half, #, #> half#x#;
typedef matrix <float, #, #> float#x#;
typedef matrix <double, #, #> double#x#;


Function Declaration Syntax
Microsoft DirectX 9.0 SDK Update (October 2004)

Function Declaration Syntax

User defined functions are very similar to C functions.

Syntax

Functions are declared with one or more of these components:

[Storage Class Modifiers] [Type Modifiers]
FunctionType FunctionName ( [ParameterList] ) { [StatementBlock] } ;

Components

Storage Class Modifiers

static At global scope, the static keyword prevents a shader variable from being exposed to an application. None of the application programming interface (API) methods (GetVertexShaderConstantx or SetVertexShaderConstantx) and none of the ID3DXConstantTable interface methods can be used to get or set a static variable.
static float fConstant_Hidden_From_the_App = 0.2f;
At local scope, a static variable has a value that persists from one invocation of the function to the next.
inline | Each copy of a function may have its own function body to decrease the overhead of calling the function. All functions are currently inlined. Recursion is not supported.
target | The target represents an optional identifier specifying the platform for which the function has been authored.

Type Modifiers

Type modifiers are optional keywords placed immediately before the variable type, which give the compiler additional information about the data type.

const The const modifier indicates a variable whose value cannot be changed by a shader. Declaring a variable with const allows the compiler to put the value in a portion of memory that does not need write access. Because the variable cannot be changed, it must be initialized in the declaration.

FunctionType

Any valid type including: basic types, vector types, matrix types, shader types, sampler type, user defined types.

Function Name

An ASCII string that uniquely identifies the name of the shader function.

Parameter List

One or more parameters separated by commas. See Function Parameter List Syntax.

Statement Block

One or more statements that make up the body of the function. See Statement Block Syntax.

If a function is defined without a body, it is considered to be a prototype. The function must be redefined, with a body, later on in the code.

Remarks

Functions can be overloaded. A function is uniquely identified by its name, the types of its parameters, and the target platform, if provided. For a list of the built in functions, see Intrinsic Functions.


Function Parameter List Syntax
Microsoft DirectX 9.0 SDK Update (October 2004)

Function Parameter List Syntax

A parameter list is a comma-separated list of parameters that make up the function declaration. Function parameter lists are defined very much like C functions.

Syntax

Each parameter can be declared with one or more of the following components:

[Parameter Modifiers]
ParameterType ParameterName [: Semantic] [= Initializers]

Parameter Modifiers

Optionally identifies a parameter as an input, an output, or both.

uniform | A uniform shader variable whose value comes from a constant register. This is a variable that is initialized in the constant registers with the ID3DXConstantTable interface. All the vertices (if you are using a vertex shader) or pixels (if you are using a pixel shader) see the same initial value in a uniform variable. Global variables are treated as if they are declared uniform.
in | Marks a parameter as input only.
out | Marks a parameter as output only.
inout | Marks a parameter as both an input and an output.

Parameters are always passed by value. in indicates that the value of the parameter should be copied in from the calling application before the function begins. out indicates that the last value of the parameter should be copied out, and returned to the calling application when the function returns. inout is a shorthand for specifying both.

uniform is a special of kind of in, indicating to a top-level function that the value for the parameter comes from constant data. For non-top-level functions, uniform is synonymous with in. If no parameter usage is specified, the parameter usage is assumed to be in.

Parameter Type

Any valid type including:

  • basic types
  • vector types
  • matrix types
  • shader types
  • sampler type
  • user defined types

ParameterName

An ASCII string that uniquely identifies the name of the shader function.

Semantics

Semantics attach shader input and output parameters with pipeline data, or other shader parameters. See Shader Semantic Syntax.

Parameter Initializers

An initializer is an optional, default value.


Statement Block Syntax
Microsoft DirectX 9.0 SDK Update (October 2004)

Statement Block Syntax

A statement block contains one or more expressions.

Syntax

{
   expression 1;
   expression 2;
   ...
   expression n;
}

Expressions are sequences of variables and literals, punctuated by operators. A literal is an explicit data value, such as 1 for an integer or 2.1 for a floating-point number. Literals are often used to assign a value to a variable.

An expression followed by a semicolon (;) is called a statement. Statements range in complexity from simple expressions to blocks of statements that accomplish a sequence of actions. Flow-control statements determine the order statements are executed.

A statement block also indicates subscope. Variables declared within a statement block are only recognized within the block. High-level shader language (HLSL) statements determine the order in which expressions are evaluated. Each expression can be one of the following:

  • An expression
  • A statement block
  • A return statement
  • A flow-control statement

Operators

Operators determine how the variables and literals are combined, compared, selected, and so on. The operators include:

Operator Name | Operators
Additive and Multiplicative Operators | +, -, *, /, %
Array Operator | [i]
Assignment Operators | =, +=, -=, *=, /=
Boolean Math Operators | &&, ||, ?:
Cast Operator | (type)
Comma Operator | ,
Comparison Operators | <, >, ==, !=, <=, >=
Prefix or Postfix Operators | ++, --
Structure Operator | .
Unary Operators | !, -, +

Many of the operators are "per component." This means that the operation is performed independently for each component of each variable. For example, a single component variable has one operation performed. On the other hand, a four-component variable has four operations performed, one for each component.

Additive and Multiplicative Operators

The additive and multiplicative operators are: +, -, *, /, %

int i1 = 1;
int i2 = 2;
int i3 = i1 + i2;  // i3 = 3
i3 = i1 * i2;        // i3 = 1 * 2 = 2

i3 = i1/i2;       // i3 = 1/3 = 0.333. Truncated to 0 because i3 is an integer.
i3 = i2/i1;       // i3 = 2/1 = 2

float f1 = 1.0;
float f2 = 2.0f;
float f3 = f1 - f2; // f3 = 1.0 - 2.0 = -1.0
f3 = f1 * f2;         // f3 = 1.0 * 2.0 = 2.0

f3 = f1/f2;        // f3 = 1.0/2.0 = 0.5
f3 = f2/f1;        // f3 = 2.0/1.0 = 2.0

The modulus operator returns the remainder of a division. This produces different results when using integers and floating-point numbers. Integer remainders that are fractional will be truncated.

int i1 = 1;
int i2 = 2;
i3 = i1 % i2;      // i3 = remainder of 1/2, which is 1
i3 = i2 % i1;      // i3 = remainder of 2/1, which is 0
i3 = 5 % 2;        // i3 = remainder of 5/2, which is 1
i3 = 9 % 2;        // i3 = remainder of 9/2, which is 1

The modulus operator truncates a fractional remainder when using integers.

f3 = f1 % f2;      // f3 = remainder or 1.0/2.0, which is 0.5
f3 = f2 % f1;      // f3 = remainder of 2.0/1.0, which is 0.0

The % operator is defined only in cases where either both sides are positive or both sides are negative. Unlike C, it also operates on floating-point data types, as well as integers.

Array Operator

The array member selection operator "[i]" selects one or more components in an array. It is a set of square brackets that contain a zero-based index.

int arrayOfInts[4] = { 0,1,2,3 };
arrayOfInts[0] = 2;
arrayOfInts[1] = arrayOfInts[0];

The array operator can also be used to access a vector.

float4 4D_Vector = { 0.0f, 1.0f, 2.0f, 3.0f  };
float 1DFloat = 4D_Vector[1];          // 1.0f

By adding an additional index, the array operator can also access a matrix.

float4x4 mat4x4 = {{0,0,0,0}, {1,1,1,1}, {2,2,2,2}, {3,3,3,3} };
mat4x4[0][1] = 1.1f;
float 1DFloat = mat4x4[0][1];      // 0.0f

The first index is the zero-based row index. The second index is the zero-based column index.

Assignment Operators

The assignment operators are: =, +=, -=, *=, /=

Variables can be assigned literal values:

int i = 1;
half h = 3.0;
float f2 = 3.1f;
bool b = false;
string str = "string";

Variables can also be assigned the result of a mathematical operation:

int i1 = 1;
i1 += 2;           // i1 = 1 + 2 = 3

A variable can be used on either side of the equals sign:

float f3 = 0.5f;
f3 *= f3;          // f3 = 0.5 * 0.5 = 0.25

Division for floating-point variables is as expected because decimal remainders are not a problem.

float f1 = 1.0;
f1 /= 3.0f;        // f1 = 1.0/3.0 = 0.333

Be careful if you are using integers that may get divided, especially when truncation affects the result. This example is identical to the previous example, except for the data type. The truncation causes a very different result.

int i1 = 1;
i1 /= 3;           // i1 = 1/3 = 0.333, which gets truncated to 0

Boolean Math Operators

The Boolean math operators are: &&, ||, ?:

bool b1 = true;
bool b2 = false;
bool b3 = b1 && b2 // b3 = true AND false = false
b3 = b1 || b2               // b3 = true OR false = true

Unlike short-circuit evaluation of &&, ||, and ?: in C, HLSL expressions never short-circuit an evaluation because they are vector operations. All sides of the expression are always evaluated.

Boolean operators function on a per-component basis. This means that if you compare two vectors, the result is a vector containing the Boolean result of the comparison for each component.

For expressions that use Boolean operators, the size and component type of each variable are promoted to be the same before the operation occurs. The promoted type determines the resolution at which the operation takes place, as well as the result type of the expression. For example an int3 + float expression would be promoted to float3 + float3 for evaluation, and its result would be of type float3.

Cast Operator

An expression preceded by a type name in parenthesis is an explicit type cast. A type cast converts the original expression to the data type of the cast. In general, the simple data types can be cast to the more complex data types (with a promotion cast), but only some complex data types can be cast into simple data types (with a demotion cast).

Comma Operator

The comma operator (,) separates one or more expressions that are to be evaluated in order. The value of the last expression in the sequence is used as the value of the sequence.

Here is one case worth calling attention to. If the constructor type is accidentally left off the right side of the equals sign, the right side now contains four expressions, separated by three commas.

// Instead of using a constructor
float4 x = float4(0,0,0,1);

// The type on the right side is accidentally left off
float4 x = (0,0,0,1);

The comma operator evaluates an expression from left to right. This reduces the right hand side to:

float4 x = 1;

HLSL uses scalar promotion in this case, so the result is as if this were written as follows:

float4 x = float4(1,1,1,1);

In this instance, leaving off the float4 type from the right side is probably a mistake that the compiler is unable to detect because this is a valid statement.

Comparison Operators

The comparison operators are: <, >, ==, !=, <=, >=.

Compare values that are greater than (or less than) any scalar value:

if( dot(lightDirection, normalVector)  >  0 )
   // Do something; the face is lit

if( dot(lightDirection, normalVector)  <  0 )
   // Do nothing; the face is backwards

Or, compare values equal to (or not equal to) any scalar value:

if(color.a  == 0)
   // Skip processing because the face is invisible

if(color.a  != 0)
   // Blend two colors together using the alpha value

Or combine both and compare values that are greater than or equal to (or less than or equal to) any scalar value:

if( position.z >= oldPosition.z )
   // Skip the new face because it is behind the existing face

if( currentValue <= someInitialCondition )
   // Reset the current value to its initial condition

Each of these comparisons can be done with any scalar data type. Comparison operators do not support the complex data types such as vector, matrix, or the object types.

Prefix or Postfix Operators

The prefix and postfix operators are: ++, --. Prefix operators change the contents of the variable before the expression is evaluated. Postfix operators change the contents of the variable after the expression is evaluated.

In this case, a loop uses the contents of i to keep track of the loop count.

float4 arrayOfFloats[4] = { 1.0f, 2.0f, 3.0f, 4.4f };

for (int i = 0; i < 4; )
{
    arrayOfFloats[i++] *= 2;
}

Because the postfix increment operator "++" is used, "arrayOfFloats[i]" is multiplied by 2 before i is incremented. This could be slightly rearranged to use the prefix increment operator. This one is harder to read, although both examples are equivalent.

float4 arrayOfFloats[4] = { 1.0f, 2.0f, 3.0f, 4.4f };

for (int i = 0; i < 4; )
{
    arrayOfFloats[++i - 1] *= 2;
}

Because the prefix operator "++" is used, "arrayOfFloats[i+1 - 1]" is multiplied by 2 after i is incremented.

The prefix decrement and postfix decrement operator "--" are applied in the same sequence as the increment operator. The difference is that decrement subtracts 1 instead of adding 1.

Structure Operator

The structure member selection operator (.) is a period. Given this structure:

struct position
{
float4 x;
float4 y;
float4 z;
};

It can be read like this:

struct position pos = { 1,2,3 };

float 1D_Float = pos.x
1D_Float = pos.y

Each member can be read or written with the structure operator:

struct position pos = { 1,2,3 };
pos.x = 2.0f;
pos.z = 1.0f;       // z = 1.0f
pos.z = pos.x      // z = 2.0f

Unary Operators

The unary operators are: !, -, +

Unary operators operate on a single operand.

bool b = false;
bool b2 = !b;      // b2 = true
int i = 2;
int i2 = -i;       // i2 = -2
int j = +i2;       // j = +2

Operator Precedence

When an expression contains more than one operator, operator precedence determines the order of evaluation.

Remarks

Curly braces ({,}) start and end a statement block. When a statement block uses a single statement, the curly braces are optional.


Shader Semantic Syntax
Microsoft DirectX 9.0 SDK Update (October 2004)

Shader Semantic Syntax

Shader semantics bind shader input and output registers with pipeline data or other shader parameters. For more about using shader semantics, see Varying Shader Inputs and Semantics.

Syntax

Semantics are attached to function parameters like this:

[Parameter Modifiers]
ParameterType ParameterName [: Semantic] [= Initializers]

Each of these is covered in detail on the function declaration syntax page.

Vertex Shader Semantics

The vertex shader input semantics are:

Vertex Shader Input Semantic | Description
BINORMAL[n] | Binormal
BLENDINDICES[n] | Blend indices
BLENDWEIGHT[n] | Blend weights
COLOR[n] | Diffuse and specular color
NORMAL[n] | Normal vector
POSITION[n] | Vertex position in object space
POSITIONT | Transformed vertex position. POSITIONT tells the runtime that the vertex is transformed and that the vertex shader should not be executed.
PSIZE[n] | Point size
TANGENT[n] | Tangent
TESSFACTOR[n] | Tessellation factor
TEXCOORD[n] | Texture coordinates

n is an optional integer between 0 and the number of resources supported. For example, PSIZE0, COLOR1, etc.

The vertex shader output semantics are:

Vertex Shader Output Semantic | Description
COLOR[n] | Diffuse or specular color. Any vertex shader prior to vs_3_0 should clamp a parameter that uses this semantic between 0 and 1, inclusive. A vs_3_0 vertex shader has no restriction on the data range.
FOG | Vertex fog.
POSITION[n] | Position of a vertex in homogenous space. Compute position in screen-space by dividing (x,y,z) by w. Every vertex shader must write out a parameter with this semantic.
PSIZE | Point size.
TEXCOORD[n] | Texture coordinates.

Pixel Shader Semantics

The pixel shader input semantics are:

Pixel Shader Input Semantic | Description
COLOR[n] | Diffuse or specular color. For shaders prior to vs_3_0 and ps_3_0, this data ranges between 0 and 1, inclusive. Starting with ps_3_0, there is no restriction on the data range.
TEXCOORD[n] | Texture coordinates.
VFACE | Floating-point scalar that indicates a back-facing primitive. A negative value faces backwards, while a positive value faces the camera. See Face Register.
VPOS | Contains the current pixel (x,y) location. See Position Register.

The pixel shader output semantics are:

Pixel Shader Output Semantic | Description
COLOR[n] | Ouput color. Any pixel shader prior to ps_3_0 should clamp a parameter that uses this semantic between 0 and 1, inclusive. For ps_3_0 shaders, the data range is dependent on the render target format.
DEPTH[n] | Output depth.

Double Binding Semantics

You can also double-bind semantics. That is, apply the same semantic to more than one parameter. For instance:

float4x4 WorldView[60]  : WORLDVIEW : register(c16);

float4 main( float3 Pos  : POSITION, int4 IPos : POSITION ) : POSITION
{
    float3 P = mul(float4(Pos, 1), (float4x3)WorldView[IPos.w]);
    return float4(P,1);
}

This function takes two arguments: a three-component, floating-point position and a four-component, integer position. The integer position is used as an index into the array of world-view matrices.


Fragment Declaration Syntax
Microsoft DirectX 9.0 SDK Update (October 2004)

Fragment Declaration Syntax

Each high-level shader language (HLSL) function can be converted into a shader fragment with the addition of a fragment declaration.

Syntax

fragmentKeyword FragmentName = compile_fragment shaderProfile FunctionName();

where:

fragmentKeyword | Required keyword. Either pixelfragment or vertexfragment.
FragmentName | An ASCII text string that specifies the compiled fragment name.
compile_fragment | Required keyword.
shaderProfile | The shader model to compile against. Any valid vertex shader profile (see D3DXGetVertexShaderProfile) or pixel shader profile (see D3DXGetPixelShaderProfile).
FunctionName() | The shader function name, followed by parentheses.

Shared fragment parameters are marked by adding an 'r_' prefix to their semantic. Here is an example of a vertex shader fragment declaration from the FragmentLinker Sample:

void AmbientDiffuse( float3 vPosWorld: r_PosWorld,
                     float3 vNormalWorld: r_NormalWorld,
                     out float4 vColor: COLOR0 )
{
    // Compute the light vector
    float3 vLight = normalize( g_vLightPosition - vPosWorld );

    // Compute the ambient and diffuse components of illumination
    vColor = g_vLightColor * g_vMaterialAmbient;
    vColor += g_vLightColor * g_vMaterialDiffuse * saturate( dot( vLight, vNormalWorld ) );
}
vertexfragment AmbientDiffuseFragment = compile_fragment vs_1_1 AmbientDiffuse();

In this example, the r_PosWorld and r_NormalWorld semantics identify that these two parameters are shared parameters among other fragments.


Appendix
Microsoft DirectX 9.0 SDK Update (October 2004)

Appendix

The high-level shader language (HLSL) appendix lists the reserved keywords, preprocessor directives, and the grammar for the language.

  • Keywords
  • Reserved Words
  • Preprocessor Operator
  • Preprocessor Directives
  • Lexical Conventions
  • Language Syntax

Keywords

Keywords are predefined reserved identifiers that have special meanings. They cannot be used as identifiers in your program.

asm1 | asm_fragment | bool | column_major | compile
compile_fragment | const | discard | decl1 | do
double | else | extern | false | float
for | half | if | in | inline
inout | int | matrix | out | pass1
pixelfragment | return | register | row_major | sampler
sampler1D | sampler2D | sampler3D | samplerCUBE | sampler_state
shared | stateblock | stateblock_state | static | string
struct | technique1 | texture | texture1D | texture2D
texture3D | textureCUBE | true | typedef | uniform
vector | vertexfragment | void | volatile | while
  1. These keywords are not case sensitive.

Reserved Words

The following keywords are unused, but are reserved.

auto | break | case | catch
char | class | const_cast | continue
default | delete | dynamic_cast | enum
explicit | friend | goto | long
mutable | namespace | new | operator
private | protected | public | reinterpret_cast
short | signed | sizeof | static_cast
switch | template | this | throw
try | typename | union | unsigned
using | virtual |  |

Preprocessor Operator

The following preprocessor operator is recognized:

defined

Refer to the preprocessor operator reference in the C++ Preprocessor Operator World Wide Web link documentation for a full description.

Preprocessor Directives

The preprocessor recognizes the following directives. These are all implemented to be compatible with the Microsoft Visual C++ preprocessor, except as noted below. Please refer to the preprocessor reference in the C++ Language Reference World Wide Web link documentation for a full description of these directives.

#define | #elif | #else | #endif
#error | #if | #ifdef | #ifndef
#include | #line | #pragma | #undef

The #include directive is valid only when compiling from a file or when the ID3DXInclude handler is used, and supports both of the following syntax alternatives:

  • <filename>
  • "filename"
When the include handler is not used, the local path is assumed.

Pragmas

Three pragma operators are supported:

pack_matrix warning def

The pack_matrix pragma specifies how matrices are packed by the compiler:

#pragma pack_matrix (row_major)
#pragma pack_matrix (column_major)

The #pragma warning directive allows modification of the behavior of compiler warning messages. The warning pragma supports the following specifiers:

  • once
  • default
  • disable
  • error
For example:

#pragma warning( disable : 4507 34 )  // Disable warning messages
                                      //  4507 and 34.
#pragma warning( once : 4385 )        // Issue warning 4385
                                      //  only once.
#pragma warning( error : 164 )        // Report warning 164
                                      //  as an error.

The def pragma conveys literal hints to the compiler. For example, the following pragma indicates to the compiler that c10 contains literal values (1, 2, 3, 4) when compiling to the vs_2_0 profile. As it's an optimization hint, using it or not is up to the compiler.

#pragma def(vs_2_0, c10, 1, 2, 3, 4)

The following are the shader profiles for the def pragma:

vs | vs_1_1 |  |  |  | vs_2_0 | vs_2_a
ps | ps_1_1 | ps_1_2 | ps_1_3 | ps_1_4 | ps_2_0 | ps_2_a

Note that the def pragma only supports float constant register (c#).

The following tokens are automatically defined:

#define D3DX
#define D3DX_VERSION 0x0901
#define DIRECT3D
#define DIRECT3D_VERSION 0x0900
#define __FILE__
#define __LINE__

For more information, see C++ Language - pragma World Wide Web link.

Lexical Conventions

Lexical conventions for the language are as follows.

Whitespace

The following characters are recognized as white space.

SPACE
TAB
EOL
C style comments (/* */)
C++ style comments (//)
Assembly style comments in asm blocks (;)

Floating point numbers

Floating point numbers are represented in HLSL as follows:

  • fractional-constant exponent-part(opt) floating-suffix(opt)

    digit-sequence exponent-part floating-suffix(opt)

  • fractional-constant :

    digit-sequence(opt) . digit-sequence

    digit-sequence .

  • exponent-part :

    e sign(opt) digit-sequence

    E sign(opt) digit-sequence

  • sign : one of

    + -

  • digit-sequence :

    digit

    digit-sequence digit

  • floating-suffix : one of

    h H f F

Integer numbers

Integer numbers are represented in HLSL as follows:

  • integer-constant integer-suffix(opt)
  • integer-constant: one of

    # (decimal number)

    0# (octal number)

    0x# (hex number)

  • integer-suffix can be any one of these:

    u U l L

Characters

Characters are represented in HLSL as follows:

'c' | (character)
'\a' '\b' '\f' '\b' '\r' '\t' '\v' | (escapes)
'\###' | (octal escape, each # is an octal digit)
'\x#' | (hex escape, # is hex number, any number of digits)
'\c' | (c is other character, including backslash and quotation marks)

Escapes are not supported in preprocessor expressions.

Strings

Strings are represented in HLSL as follows:

"s" (s is any string with escapes).

Identifiers

Identifiers are represented in HLSL as follows:

    [A-Za-z_][A-Za-z0-9_]*

Operators

    ##, #@, ++, --, &&, ||, ==, ::, <<, <<=, >>, >>=, ...,
    <=, >=, !=, *=, /=, +=, -=, %=, &=, |=, ^=, ->

Also any other single character that did not match another rule.

Language Syntax

The following is a listing of the language constructs, from which the HLSL statements are constructed.

Program :
Program : Decls

Decls : Decl
Decls : Decls Decl
Decl : ';'
Decl : TypeDecl
Decl : VariableDecl
Decl : VarStructDecl
Decl : FunctionDecl
Decl : TechniqueDecl

Usages : Usage
Usages : Usages Usage
Usage : T_KW_STATIC
Usage : T_KW_UNIFORM
Usage : T_KW_EXTERN
Usage : T_KW_VOLATILE
Usage : T_KW_INLINE
Usage : T_KW_SHARED
Usage : ConstUsage
Usage : Target

ConstUsages : ConstUsage
ConstUsages : ConstUsages ConstUsage
ConstUsage : T_KW_CONST
ConstUsage : T_KW_ROW_MAJOR
ConstUsage : T_KW_COLUMN_MAJOR

UsageType : Type
UsageType : Usages Type

UsageStructDecl : StructDecl
UsageStructDecl : Usages StructDecl

TypeDecl : T_KW_TYPEDEF ConstType TypeDefs ';'
TypeDecl : T_KW_TYPEDEF ConstStructDecl TypeDefs ';'
TypeDecl : StructDecl ';'
TypeDefs : VariableDim
TypeDefs : VariableDim ',' TypeDefs

Type : BaseType
Type : Struct
Type : TypeId
Type : T_KW_STRUCT TypeId

ConstType : Type
ConstType : ConstUsages Type
ConstTypeDim : ConstType
ConstTypeDim : ConstTypeDim '[' ConstantExpr ']'

BaseType : T_KW_VOID
BaseType : ScalarType
BaseType : VectorType
BaseType : MatrixType
BaseType : ObjectType

ScalarType : T_KW_BOOL
ScalarType : T_KW_INT
ScalarType : T_KW_HALF
ScalarType : T_KW_FLOAT
ScalarType : T_KW_DOUBLE

VectorType : T_KW_VECTOR
VectorType : T_KW_VECTOR '<' ScalarType ',' AddExpr '>'

MatrixType : T_KW_MATRIX
MatrixType : T_KW_MATRIX '<' ScalarType ',' ConstantExpr ',' AddExpr '>'

ObjectType : T_KW_STRING
ObjectType : T_KW_TEXTURE
ObjectType : T_KW_TEXTURE1D
ObjectType : T_KW_TEXTURE2D
ObjectType : T_KW_TEXTURE3D
ObjectType : T_KW_TEXTURECUBE
ObjectType : T_KW_SAMPLER
ObjectType : T_KW_SAMPLER1D
ObjectType : T_KW_SAMPLER2D
ObjectType : T_KW_SAMPLER3D
ObjectType : T_KW_SAMPLERCUBE
ObjectType : T_KW_PIXELSHADER
ObjectType : T_KW_VERTEXSHADER
ObjectType : T_KW_PIXELFRAGMENT
ObjectType : T_KW_VERTEXFRAGMENT
ObjectType : T_KW_STATEBLOCK

Struct : T_KW_STRUCT StructBegin StructEnd
Struct : T_KW_STRUCT StructBegin StructDecls StructEnd
StructDecl : T_KW_STRUCT Id StructBegin StructEnd
StructDecl : T_KW_STRUCT Id StructBegin StructDecls StructEnd

ConstStructDecl : StructDecl
ConstStructDecl : ConstUsages StructDecl

StructBegin : '{'
StructDecls : VariableDecl
StructDecls : VariableDecl StructDecls
StructEnd : '}'

Semantic : ':' Id
Semantic : ':' T_KW_REGISTER '(' Register ')'
Semantics : Semantic
Semantics : Semantics Semantic
SemanticsOpt :
SemanticsOpt : Semantics

Register : Id
Register : Target ',' Id

Annotation : AnnotationBegin AnnotationEnd
Annotation : AnnotationBegin AnnotationDecls AnnotationEnd
AnnotationOpt :
AnnotationOpt : Annotation
AnnotationBegin : '<'
AnnotationDecls : VariableDecl
AnnotationDecls : VariableDecl AnnotationDecls
AnnotationEnd : '>'

Initializer : '=' AssignmentExpr
Initializer : '=' '{' InitExprs '}'
Initializer : '=' '{' InitExprs ',' '}'
InitializerOpt :
InitializerOpt : Initializer

VariableDecl : UsageType Variables ';'
VarStructDecl : UsageStructDecl Variables ';'
Variables : Variable
Variables : Variables ',' Variable
Variable : VariableDim SemanticsOpt AnnotationOpt InitializerOpt
VariableDim : Id
VariableDim : VariableDim '[' ']'
VariableDim : VariableDim '[' ConstantExpr ']'

FunctionDecl : FunctionDef ';'
FunctionDecl : FunctionDef AnnotationOpt StmtBlock
FunctionDef : UsageType Id ParamList SemanticsOpt

ParamList : ParamListBegin ParamListEnd
ParamList : ParamListBegin T_KW_VOID ParamListEnd
ParamList : ParamListBegin ParameterDecls ParamListEnd
ParamListBegin : '('
ParamListEnd : ')'

ParameterDecls : ParameterDecl
ParameterDecls : ParameterDecls ',' ParameterDecl
ParameterDecl : ParamUsageType Variable

ParamUsageType : Type
ParamUsageType : ParamUsages Type

ParamUsages : ParamUsage
ParamUsages : ParamUsages ParamUsage
ParamUsage : T_KW_IN
ParamUsage : T_KW_OUT
ParamUsage : T_KW_INOUT
ParamUsage : T_KW_UNIFORM
ParamUsage : ConstUsage
TechniqueDecl : T_KW_TECHNIQUE IdOpt AnnotationOpt TechniqueBody
TechniqueBody : TechniqueBegin TechniqueEnd
TechniqueBody : TechniqueBegin PassDecls TechniqueEnd
TechniqueBegin : '{'
TechniqueEnd : '}'

PassDecls : PassDecl
PassDecls : PassDecls PassDecl
PassDecl : T_KW_PASS IdOpt AnnotationOpt StateBlock

StateBlock : StateBlockBegin StateBlockEnd
StateBlock : StateBlockBegin States StateBlockEnd
StateBlockBegin : '{'
StateBlockEnd : '}'

States : State
States : States State
State : Id StateIndex StateExprBegin StateExpr StateExprEnd

StateIndex :
StateIndex : '[' Uint ']'
StateExprBegin : '='
StateExprEnd : ';'

StmtBlock : StmtBlockBegin StmtBlockEnd
StmtBlock : StmtBlockBegin Stmts StmtBlockEnd
StmtBlockBegin : '{'
StmtBlockEnd : '}'
Stmts : Stmt
Stmts : Stmts Stmt
SimpleStmt : ';'
SimpleStmt : Expr ';'
SimpleStmt : T_KW_RETURN ';'
SimpleStmt : T_KW_RETURN Expr ';'
SimpleStmt : T_KW_DO Stmt T_KW_WHILE '(' Expr ')' ';'
SimpleStmt : StmtBlock
SimpleStmt : T_KW_DISCARD ';'
SimpleStmt : TypeDecl
SimpleStmt : VariableDecl
SimpleStmt : VarStructDecl

NonIfStmt : SimpleStmt
NonIfStmt : T_KW_WHILE '(' Expr ')' NonIfStmt
NonIfStmt : For '(' ForInit ForCond ForStep ')' NonIfStmt

Stmt : SimpleStmt
Stmt : T_KW_WHILE '(' Expr ')' Stmt
Stmt : For '(' ForInit ForCond ForStep ')' Stmt
Stmt : T_KW_IF '(' Expr ')' Stmt
Stmt : T_KW_IF '(' Expr ')' NonIfStmt T_KW_ELSE Stmt

For : T_KW_FOR
ForInit : ';'
ForInit : Expr ';'
ForInit : VariableDecl
ForCond : ';'
ForCond : Expr ';'
ForStep :
ForStep : Expr

DwordExpr : Dword
DwordExpr : Dword '|' DwordExpr

StateExpr : DwordExpr
StateExpr : ComplexExpr
StateExpr : '{' InitExprs '}'
StateExpr : '{' InitExprs ',' '}'
StateExpr : '<' RelationalExpr '>'

SimpleExpr : T_KW_TRUE
SimpleExpr : T_KW_FALSE
SimpleExpr : Uint
SimpleExpr : Float
SimpleExpr : Strings
SimpleExpr : NonTypeId

ComplexExpr : '(' Expr ')'
ComplexExpr : TypeId '(' ArgumentsOpt ')'
ComplexExpr : BaseType '(' ArgumentsOpt ')'
ComplexExpr : NonTypeId '(' ArgumentsOpt ')'
ComplexExpr : ObjectExpr

ObjectExpr : AsmDecl
ObjectExpr : AsmDecl Asm
ObjectExpr : Asm
ObjectExpr : AsmFragment
ObjectExpr : T_KW_COMPILE Target NonTypeId '(' ArgumentsOpt ')'
ObjectExpr : T_KW_SAMPLER_STATE StateBlock
ObjectExpr : T_KW_COMPILE_FRAGMENT Target NonTypeId '(' ArgumentsOpt ')'
ObjectExpr : T_KW_STATEBLOCK_STATE StateBlock

PrimaryExpr : SimpleExpr
PrimaryExpr : ComplexExpr
PostfixExpr : PrimaryExpr
PostfixExpr : PostfixExpr '[' Expr ']'
PostfixExpr : PostfixExpr '.' Id
PostfixExpr : PostfixExpr T_OP_INC
PostfixExpr : PostfixExpr T_OP_DEC

UnaryExpr : PostfixExpr
UnaryExpr : T_OP_INC UnaryExpr
UnaryExpr : T_OP_DEC UnaryExpr
UnaryExpr : '!' CastExpr
UnaryExpr : '-' CastExpr
UnaryExpr : '+' CastExpr

CastExpr : UnaryExpr
CastExpr : '(' ConstTypeDim ')' CastExpr

MulExpr : CastExpr
MulExpr : MulExpr '*' CastExpr
MulExpr : MulExpr '/' CastExpr
MulExpr : MulExpr '%' CastExpr

AddExpr : MulExpr
AddExpr : AddExpr '+' MulExpr
AddExpr : AddExpr '-' MulExpr

RelationalExpr : AddExpr
RelationalExpr : RelationalExpr '<' AddExpr
RelationalExpr : RelationalExpr '>' AddExpr
RelationalExpr : RelationalExpr T_OP_LE AddExpr
RelationalExpr : RelationalExpr T_OP_GE AddExpr

EqualityExpr : RelationalExpr
EqualityExpr : EqualityExpr T_OP_EQ RelationalExpr
EqualityExpr : EqualityExpr T_OP_NE RelationalExpr

AndExpr : EqualityExpr
AndExpr : AndExpr T_OP_AND EqualityExpr
OrExpr : AndExpr
OrExpr : OrExpr T_OP_OR AndExpr
ConditionalExpr : OrExpr
ConditionalExpr : OrExpr '?' AssignmentExpr ':' ConditionalExpr

AssignmentExpr : ConditionalExpr
AssignmentExpr : CastExpr '=' AssignmentExpr
AssignmentExpr : CastExpr T_OP_ME AssignmentExpr
AssignmentExpr : CastExpr T_OP_DE AssignmentExpr
AssignmentExpr : CastExpr T_OP_RE AssignmentExpr
AssignmentExpr : CastExpr T_OP_AE AssignmentExpr
AssignmentExpr : CastExpr T_OP_SE AssignmentExpr

Arguments : AssignmentExpr
Arguments : Arguments ',' AssignmentExpr
ArgumentsOpt :
ArgumentsOpt : Arguments

InitExpr : AssignmentExpr
InitExpr : '{' InitExprs '}'
InitExpr : '{' InitExprs ',' '}'
InitExprs : InitExpr
InitExprs : InitExprs ',' InitExpr

ConstantExpr : AssignmentExpr
Expr : AssignmentExpr
Expr : Expr ',' AssignmentExpr

Dword : Uint
Dword : '-' Uint
Dword : Float
Dword : '-' Float
Dword : DwordId
Dword : Uint DwordId
DwordId : Id
DwordId : T_KW_TRUE
DwordId : T_KW_FALSE
DwordId : T_KW_TEXTURE

Id : TypeId
Id : NonTypeId
IdOpt :
IdOpt : Id

Target : NonTypeId

Uint : T_UINT
Uint : T_INT32
Uint : T_UINT32

Float : T_FLOAT
Float : T_FLOAT16
Float : T_FLOAT32
Float : T_FLOAT64

Strings : String
Strings : Strings String
String : T_STRING

TypeId : T_TYPE_ID
NonTypeId : T_NON_TYPE_ID

AsmDecl : T_KW_DECL '{'
Asm : T_KW_ASM '{'
AsmFragment : T_KW_ASM_FRAGMENT '{'


HLSL Intrinsic Functions
Microsoft DirectX 9.0 SDK Update (October 2004)

HLSL Intrinsic Functions

HLSL intrinsic functions are made up of

  • A return type.
  • A function name.
  • One or more arguments.

For example, the abs intrinsic function could be called like this:

float3 retValue;
retValue = abs(float3(0,0,1));

Where:

  • retValue is a float3 return type.
  • abs is the function name.
  • The input argument is a float3(0,0,1).

The input argument is made up of one or more template types, where each template type is made up of one or more data types. The return value is also made up of a template type and a data type, and the return value is dependent on the choices made for the input argument and the operation of the function.

Template Type

These are the template types for input arguments and return values:

  • scalar (1 component)
  • vector (up to 4 components)
  • matrix (up to 16 components)
  • object (sampler object)

Component Type

The component data types for input arguments and return values are the high-level shader language (HLSL) types:

  • Boolean: bool
  • Integer: int
  • Float types: half, float, or double
  • Numeric: int, half, float, or double
  • Sampler: sampler, sampler, sampler1D, sampler2D, sampler3D, samplerCUBE

The template type must be compatible with the component type:

  • The scalar, vector, and matrix templates can use any component type except the Sampler type.
  • The object template can only use the Sampler types.

Intrinsic Function Listing

The following table lists the intrinsic functions available in HLSL. Each function has a brief description, and a link to a reference page that has more detail about the input argument and return type.

Name | Syntax | Description
abs - HLSL | value abs(value a) | Absolute value (per component).
acos | acos(x) | Returns the arccosine of each component of x. Each component should be in the range [-1, 1].
all | all(x) | Test if all components of x are nonzero.
any | any(x) | Test if any component of x is nonzero.
asin | asin(x) | Returns the arcsine of each component of x. Each component should be in the range [-pi/2, pi/2].
atan | atan(x) | Returns the arctangent of x. The return values are in the range [-pi/2, pi/2].
atan2 | atan2(y, x) | Returns the arctangent of y/x. The signs of y and x are used to determine the quadrant of the return values in the range [-pi, pi]. atan2 is well-defined for every point other than the origin, even if x equals 0 and y does not equal 0.
ceil | ceil(x) | Returns the smallest integer which is greater than or equal to x.
clamp | clamp(x, min, max) | Clamps x to the range [min, max].
clip | clip(x) | Discards the current pixel, if any component of x is less than zero. This can be used to simulate clip planes, if each component of x represents the distance from a plane.
cos | cos(x) | Returns the cosine of x.
cosh | cosh(x) | Returns the hyperbolic cosine of x.
cross | cross(a, b) | Returns the cross product of two 3-D vectors a and b.
D3DCOLORtoUBYTE4 | D3DCOLORtoUBYTE4(x) | Swizzles and scales components of the 4-D vector x to compensate for the lack of UBYTE4 support in some hardware.
ddx | ddx(x) | Returns the partial derivative of x with respect to the screen-space x-coordinate.
ddy | ddy(x) | Returns the partial derivative of x with respect to the screen-space y-coordinate.
degrees | degrees(x) | Converts x from radians to degrees.
determinant | determinant(m) | Returns the determinant of the square matrix m.
distance | distance(a, b) | Returns the distance between two points, a and b.
dot | dot(a, b) | Returns the • product of two vectors, a and b.
exp | exp(x) | Returns the base-e exponent.
exp2 | value exp2(value a) | Base 2 Exp (per component).
faceforward | faceforward(n, i, ng) | Returns -n * sign(•(i, ng)).
floor | floor(x) | Returns the greatest integer which is less than or equal to x.
fmod | fmod(a, b) | Returns the floating point remainder f of a / b such that a = i * b + f, where i is an integer, f has the same sign as x, and the absolute value of f is less than the absolute value of b.
frac | frac(x) | Returns the fractional part f of x, such that f is a value greater than or equal to 0, and less than 1.
frexp | frexp(x, out exp) | Returns the mantissa and exponent of x. frexp returns the mantissa, and the exponent is stored in the output parameter exp. If x is 0, the function returns 0 for both the mantissa and the exponent.
fwidth | fwidth(x) | Returns abs(ddx(x)) + abs(ddy(x)).
isfinite | isfinite(x) | Returns true if x is finite, false otherwise.
isinf | isinf(x) | Returns true if x is +INF or -INF, false otherwise.
isnan | isnan(x) | Returns true if x is NAN or QNAN, false otherwise.
ldexp | ldexp(x, exp) | Returns x * 2exp.
length | length(v) | Returns the length of the vector v.
lerp | lerp(a, b, s) | Returns a + s(b - a). This linearly interpolates between a and b, such that the return value is a when s is 0, and b when s is 1.
lit | lit(n • l, n • h, m) | Returns a lighting vector (ambient, diffuse, specular, 1): ambient = 1; diffuse = (n • l < 0) ? 0 : n • l; specular = (n • l < 0) || (n • h < 0) ? 0 : (n • h * m);
log | log(x) | Returns the base-e logarithm of x. If x is negative, the function returns indefinite. If x is 0, the function returns +INF.
log10 | log10(x) | Returns the base-10 logarithm of x. If x is negative, the function returns indefinite. If x is 0, the function returns +INF.
log2 | log2(x) | Returns the base-2 logarithm of x. If x is negative, the function returns indefinite. If x is 0, the function returns +INF.
max | max(a, b) | Selects the greater of a and b.
min | min(a, b) | Selects the lesser of a and b.
modf | modf(x, out ip) | Splits the value x into fractional and integer parts, each of which has the same sign and x. The signed fractional portion of x is returned. The integer portion is stored in the output parameter ip.
mul | mul(a, b) | Performs matrix multiplication between a and b. If a is a vector, it is treated as a row vector. If b is a vector, it is treated as a column vector. The inner dimension acolumns and brows must be equal. The result has the dimension arows x bcolumns.
noise | noise(x) | Not yet implemented.
normalize | normalize(v) | Returns the normalized vector v / length(v). If the length of v is 0, the result is indefinite.
pow | pow(x, y) | Returns xy.
radians | radians(x) | Converts x from degrees to radians.
reflect | reflect(i, n) | Returns the reflection vector v, given the entering ray direction i, and the surface normal n, such that v = i - 2 * •(i, n) * n.
refract | refract(i, n, ?) | Returns the refraction vector v, given the entering ray direction i, the surface normal n, and the relative index of refraction ?. If the angle between i and n is too great for a given ?, refract returns (0,0,0).
round | round(x) | Rounds x to the nearest integer
rsqrt | rsqrt(x) | Returns 1 / sqrt(x)
saturate | saturate(x) | Clamps x to the range [0, 1]
sign | sign(x) | Computes the sign of x. Returns -1 if x is less than 0, 0 if x equals 0, and 1 if x is greater than zero.
sin | sin(x) | Returns the sine of x
sincos | sincos(x, out s, out c) | Returns the sine and cosine of x. sin(x) is stored in the output parameter s. cos(x) is stored in the output parameter c.
sinh | sinh(x) | Returns the hyperbolic sine of x
smoothstep | smoothstep(min, max, x) | Returns 0 if x < min. Returns 1 if x > max. Returns a smooth Hermite interpolation between 0 and 1, if x is in the range [min, max].
sqrt | value sqrt(value a) | Square root (per component)
step | step(a, x) | Returns (x >= a) ? 1 : 0
tan | tan(x) | Returns the tangent of x
tanh | tanh(x) | Returns the hyperbolic tangent of x
tex1D | tex1D(s, t) | 1-D texture lookup. s is a sampler or a sampler1D object. t is a scalar.
tex1D | tex1D(s, t, ddx, ddy) | 1-D texture lookup, with derivatives. s is a sampler or sampler1D object. t, ddx, and ddy are scalars.
tex1Dproj | tex1Dproj(s, t) | 1-D projective texture lookup. s is a sampler or sampler1D object. t is a 4-D vector. t is divided by its last component before the lookup takes place.
tex1Dbias | tex1Dbias(s, t) | 1-D biased texture lookup. s is a sampler or sampler1D object. t is a 4-D vector. The mip level is biased by t.w before the lookup takes place.
tex2D | tex2D(s, t) | 2-D texture lookup. s is a sampler or a sampler2D object. t is a 2-D texture coordinate.
tex2D | tex2D(s, t, ddx, ddy) | 2-D texture lookup, with derivatives. s is a sampler or sampler2D object. t, ddx, and ddy are 2-D vectors.
tex2Dproj | tex2Dproj(s, t) | 2-D projective texture lookup. s is a sampler or sampler2D object. t is a 4-D vector. t is divided by its last component before the lookup takes place.
tex2Dbias | tex2Dbias(s, t) | 2-D biased texture lookup. s is a sampler or sampler2D object. t is a 4-D vector. The mip level is biased by t.w before the lookup takes place.
tex3D | tex3D(s, t) | 3-D volume texture lookup. s is a sampler or a sampler3D object. t is a 3-D texture coordinate.
tex3D | tex3D(s, t, ddx, ddy) | 3-D volume texture lookup, with derivatives. s is a sampler or sampler3D object. t, ddx, and ddy are 3-D vectors.
tex3Dproj | tex3Dproj(s, t) | 3-D projective volume texture lookup. s is a sampler or sampler3D object. t is a 4-D vector. t is divided by its last component before the lookup takes place.
tex3Dbias | tex3Dbias(s, t) | 3-D biased texture lookup. s is a sampler or sampler3D object. t is a 4-D vector. The mip level is biased by t.w before the lookup takes place.
texCUBE | texCUBE(s, t) | 3-D cube texture lookup. s is a sampler or a samplerCUBE object. t is a 3-D texture coordinate.
texCUBE | texCUBE(s, t, ddx, ddy) | 3-D cube texture lookup, with derivatives. s is a sampler or samplerCUBE object. t, ddx, and ddy are 3-D vectors.
texCUBEproj | texCUBEproj(s, t) | 3-D projective cube texture lookup. s is a sampler or samplerCUBE object. t is a 4-D vector. t is divided by its last component before the lookup takes place.
texCUBEbias | texCUBEbias(s, t) | 3-D biased cube texture lookup. s is a sampler or samplerCUBE object. t is a 4-dimensional vector. The mip level is biased by t.w before the lookup takes place.
transpose | transpose(m) | Returns the transpose of the matrix m. If the source is dimension mrows x mcolumns, the result is dimension mcolumns x mrows.


abs - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

abs - HLSL

Computes the absolute value of each component.

Syntax

ret abs(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float, int | any
ret | out | same as input x | same as input x | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_1_4


acos - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

acos - HLSL

Returns the arccosine of each component of x. Each component should be in the range [-1, 1].

Syntax

ret acos(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


all - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

all - HLSL

Test if all components of x are nonzero.

Syntax

ret all(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float, int, bool | any
ret | out | scalar | bool | 1

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_1_4


any - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

any - HLSL

Test if any component of x is nonzero.

Syntax

ret any(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float, int, bool | any
ret | out | scalar | bool | 1

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_1_4


asin - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

asin - HLSL

Returns the arcsine of each component of x. Each component should be in the range [-pi/2, pi/2].

Syntax

ret asin(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


atan - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

atan - HLSL

Returns the arctangent of x. The return values are in the range [-pi/2, pi/2].

Syntax

ret atan(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


atan2 - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

atan2 - HLSL

Returns the arctangent of x/y. The signs of x and y are used to determine the quadrant of the return values in the range [-pi, pi]. atan2 is well-defined for every point other than the origin, even if y equals 0 and x does not equal 0.

Syntax

ret atan2(x, y)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
y | in | same as input x | float | same dimension(s) as input x
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


ceil - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

ceil - HLSL

Returns the smallest integer which is greater than or equal to x.

Syntax

ret ceil(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


clamp - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

clamp - HLSL

Clamps x to the range [min, max].

Syntax

ret clamp(x, min, max)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float, int | any
min | in | same as input x | float, int | same dimension(s) as input x
max | in | same as input x | float, int | same dimension(s) as input x
ret | out | same as input x | float, int | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_1_4


clip - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

clip - HLSL

Discards the current pixel if any component of x is less than zero. This can be used to simulate clip planes if each component of x represents the distance from a plane.

Syntax

clip(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_1_1


cos - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

cos - HLSL

Returns the cosine of x.

Syntax

ret cos(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


cosh - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

cosh - HLSL

Returns the hyperbolic cosine of x.

Syntax

ret cosh(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


cross - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

cross - HLSL

Returns the cross product of two 3-D vectors.

Syntax

ret cross(x, y)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | vector | float | 3
y | in | vector | float | 3
ret | out | vector | float | 3

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_1_4


D3DCOLORtoUBYTE4 - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DCOLORtoUBYTE4 - HLSL

Swizzles and scales components of the 4-D vector x to compensate for the lack of UBYTE4 support in some hardware.

Syntax

ret D3DCOLORtoUBYTE4(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | vector | float | 4
ret | out | vector | integer | 4

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


ddx - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

ddx - HLSL

Returns the partial derivative of x with respect to the screen-space x coordinate.

Syntax

ret ddx(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_2_x


ddy - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

ddy - HLSL

Returns the partial derivative of y with respect to the screen-space y coordinate.

Syntax

ret ddy(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_2_x


degrees - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

degrees - HLSL

Converts x from radians to degrees.

Syntax

ret degrees(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


determinant - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

determinant - HLSL

Returns the determinant of the square matrix m.

Syntax

ret determinant(m)

Where:

Name | In/Out | Template Type | Component Type | Size
m | in | matrix | float | any (number of rows = number of columns)
ret | out | scalar | float | 1

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_1_4


distance - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

distance - HLSL

Returns the distance between two points x and y.

Syntax

ret distance(x, y)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | vector | float | any
y | in | vector | float | same dimension(s) as input x
ret | out | scalar | float | 1

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


dot - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

dot - HLSL

Returns the • product of two vectors, x and y.

Syntax

ret dot(x, y)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | vector | float, int | any
y | in | vector | float, int | same dimensions(s) as input x
ret | out | scalar | float, int | 1

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


exp - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

exp - HLSL

Returns the base-e exponential, or ex.

Syntax

ret exp(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


exp2 - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

exp2 - HLSL

Calculates the base 2 exponential of x (per component), or 2x.

Syntax

ret exp2(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


faceforward - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

faceforward - HLSL

Tests if a face is visible. Returns -n * sign(dot(i, ng))

Syntax

ret faceforward(n, i, ng)

Where:

Name | In/Out | Template Type | Component Type | Size
n | in | vector | float | any
i | in | vector | float | same dimension(s) as input n
ng | in | vector | float | same dimensions as input n
ret | out | vector | float | same dimensions as input n

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_1_4


floor - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

floor - HLSL

Returns the greatest integer which is less than or equal to x.

Syntax

ret floor(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


fmod - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

fmod - HLSL

Returns the floating point remainder f of x / y such that x = i * y + f, where i is an integer, f has the same sign as x, and the absolute value of f is less than the absolute value of y.

Syntax

ret fmod(x, y)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
y | in | same as input x | float | same dimension(s) as input x
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


frac - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

frac - HLSL

Returns the fractional part f of x, such that f is a value greater than or equal to 0, and less than 1.

Syntax

ret frac(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


frexp - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

frexp - HLSL

Returns the mantissa and exponent of x. The return value of the function is the mantissa, and the exponent is returned by exp. If x is 0, the function returns 0 for both the mantissa and the exponent.

Syntax

ret frexp(x, out exp)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
exp | in | same as input x | float | same dimension(s) as input x
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


fwidth - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

fwidth - HLSL

Returns the absolute value of the partial derivatives, or abs(ddx(x)) + abs(ddy(x)).

Syntax

ret fwidth(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_2_x


isfinite - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

isfinite - HLSL

Returns true if x is finite, false otherwise.

Syntax

ret isfinite(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | scalar | bool | 1

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


isinf - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

isinf - HLSL

Returns true if x is +INF or -INF, false otherwise.

Syntax

ret isinf(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | scalar | bool | 1

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


isnan - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

isnan - HLSL

Returns true if x is NAN or QNAN, false otherwise.

Syntax

ret isnan(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | scalar | bool | 1

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


ldexp - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

ldexp - HLSL

Returns x * 2exp.

Syntax

ret ldexp(x, exp)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, matrix | float | any
exp | in | same as input x | float | same dimension(s) as input x
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


length - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

length - HLSL

Returns the length of the vector x.

Syntax

ret length(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | vector | float | any
ret | out | scalar | float | 1

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


lerp - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

lerp - HLSL

Returns x + s(y - x). This linearly interpolates between x and y, such that the return value is x when s is 0, and y when s is 1.

Syntax

ret lerp(x, y, s)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
y | in | same as input x | float | same dimension(s) as input x
s | in | same as input x | float | same dimension(s) as input x
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_1_4


lit - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

lit - HLSL

Returns a lighting vector (ambient, diffuse, specular, 1) where:

  • ambient = 1.
  • diffuse = ((n • l) < 0) ? 0 : n • l.
  • specular = ((n • l) < 0) || ((n • h) < 0) ? 0 : ((n • h) * m).

Syntax

ret lit(n dot l, n dot h, m)

Where:

Name | In/Out | Template Type | Component Type | Size
l | in | scalar | float | 1
h | in | scalar | float | 1
m | in | scalar | float | 1
ret | out | vector | float | 4

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


log - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

log - HLSL

Returns the base-e logarithm of x. If x is negative, the function returns indefinite. If x is 0, the function returns +INF.

Syntax

ret log(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


log2 - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

log2 - HLSL

Returns the base-2 logarithm of x. If x is negative, the function returns indefinite. If x is 0, the function returns +INF.

Syntax

ret log2(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


log10 - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

log10 - HLSL

Returns the base-10 logarithm of x. If x is negative, the function returns indefinite. If x is 0, the function returns +INF.

Syntax

ret log10(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


max - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

max - HLSL

Selects the greater of x and y.

Syntax

ret max(x, y)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float, int | any
y | in | same as input x | float, int | same dimension(s) as input x
ret | return type | same as input x | float, int | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_1_4


min - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

min - HLSL

Selects the lesser of x and y.

Syntax

ret min(x, y)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float, int | any
y | in | same as input x | float, int | same dimension(s) as input x
ret | return type | same as input x | float, int | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_1_4


modf - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

modf - HLSL

Splits the value x into fractional and integer parts, each of which has the same sign as x. The signed fractional portion of x is returned. The integer portion is stored in the output parameter ip.

Syntax

ret modf(x, out ip)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float, int | any
ip | out | same as input x | float, int | same dimension(s) as input x
ret | out | same as input x | float, int | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


mul - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

mul - HLSL

Performs matrix multiplication between x and y. If x is a vector, it treated as a row vector. If y is a vector, it is treated as a column vector. The inner dimension x-columns and y-rows must be equal. The result has the dimension x-rows x y-columns.

Syntax

ret mul(x, y)

There are 9 overloaded versions of this function, to handle the different cases for the types and sizes of the x and y input arguments. The following table lists these versions.

Version | Name | Purpose | Template Type | Component Type | Size
1 |  |  |  |  |
 | x | in | scalar | float, int | 1
 | y | in | scalar | same as input x | 1
 | ret | out | scalar | same as input x | 1
2 |  |  |  |  |
 | x | in | scalar | float, int | 1
 | y | in | vector | float, int | any
 | ret | out | vector | float, int | same dimension(s) as input y
3 |  |  |  |  |
 | x | in | scalar | float, int | 1
 | y | in | matrix | float, int | any
 | ret | out | matrix | same as input y | same dimension(s) as input y
4 |  |  |  |  |
 | x | in | vector | float, int | any
 | y | in | scalar | float, int | 1
 | ret | out | vector | float, int | same dimension(s) as input x
5 |  |  |  |  |
 | x | in | vector | float, int | any
 | y | in | vector | float, int | same dimension(s) as input x
 | ret | out | scalar | float, int | 1
6 |  |  |  |  |
 | x | in | vector | float, int | any
 | y | in | matrix | float, int | rows = same dimension(s) as input x, columns = any
 | ret | out | vector | float, int | same dimension(s) as input y columns
7 |  |  |  |  |
 | x | in | matrix | float, int | any
 | y | in | scalar | float, int | 1
 | ret | out | matrix | float, int | same dimension(s) as input x
8 |  |  |  |  |
 | x | in | matrix | float, int | any
 | y | in | vector | float, int | number of columns in input x
 | ret | out | vector | float, int | number of rows in input x
9 |  |  |  |  |
 | x | in | matrix | float, int | any
 | y | in | matrix | float, int | rows = number of columns in input x, columns = number of rows in input x
 | ret | out | matrix | float, int | rows = number of rows in input x, columns = number of columns in input y

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_1_1


noise - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

noise - HLSL

Generates Perlin noise values, which are noise values that change smoothly as you move from one point to another over a space.

Syntax

ret noise(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | vector | float | any
ret | out | scalar | float | 1

The output range is between -1 and 1.

Minimum Shader Version

This intrinsic function is only supported for a texture shader.

Vertex Shader | Pixel Shader | Texture Shader
n/a | n/a | tx_1_0


normalize - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

normalize - HLSL

Returns the normalized vector x / length(x). If the length of x is 0, the result is indefinite.

Syntax

ret normalize(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | vector | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


pow - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

pow - HLSL

Returns xy.

Syntax

ret pow(x, y)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
y | in | same as input x | float | same dimension(s) as input x
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


radians - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

radians - HLSL

Converts x from degrees to radians.

Syntax

ret radians(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_1_1


reflect - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

reflect - HLSL

Returns the reflection vector v, given the entering ray direction i, and the surface normal n, as in:

v = i - 2 * dot(i, n) * n

Syntax

ret reflect(i, n)

Where:

Name | In/Out | Template Type | Component Type | Size
i | in | vector | float | any
n | in | vector | float | same dimension(s) as input i
ret | out | vector | float | same dimension(s) as input i

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_1_1


refract - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

refract - HLSL

Returns the refraction vector given the entering ray direction i, the surface normal n, and the refraction index ri. If the angle between i and n is too great for a given eta, refract returns (0,0,0).

Syntax

ret refract(i, n, ri)

Where:

Name | In/Out | Template Type | Component Type | Size
i | in | vector | float | any
n | in | vector | float | same dimension(s) as input i
ri | in | scalar | float | 1
refraction vector | out | vector | float | same dimension(s) as input i

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


round - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

round - HLSL

Rounds x to the nearest integer.

Syntax

ret round(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


rsqrt - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

rsqrt - HLSL

Returns 1 / sqrt(x).

Syntax

ret rsqrt(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


saturate - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

saturate - HLSL

Clamps x to the range [0, 1].

Syntax

ret saturate(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_1_1


sign - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

sign - HLSL

Computes the sign of x. Returns -1 if x is less than 0, 0 if x equals 0, and 1 if x is greater than zero.

Syntax

ret sign(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float, int | any
ret | out | same as input x | int | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_1_4


sin - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

sin - HLSL

Returns the sine of x.

Syntax

ret sin(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


sincos - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

sincos - HLSL

Returns the sine and cosine of x. sin(x) is stored in the output parameter s. cos(x) is stored in the output parameter c.

Syntax

sincos(x, out s, out c)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
s | out | same as input x | float | same dimension(s) as input x
c | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


sinh - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

sinh - HLSL

Returns the hyperbolic sine of x.

Syntax

ret sinh(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


smoothstep - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

smoothstep - HLSL

Returns 0 if x < min. Returns 1 if x > max. Returns a smooth Hermite interpolation between 0 and 1, if x is in the range [min, max].

Syntax

ret smoothstep(min, max, x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
min | in | same as input x | float | same dimension(s) as input x
max | in | same as input x | float | same dimension(s) as input x
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


sqrt - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

sqrt - HLSL

Square root (per component).

Syntax

ret sqrt(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


step - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

step - HLSL

Returns (x >= y) ? 1 : 0.

Syntax

ret step(y, x)

Where:

Name | In/Out | Template Type | Component Type | Size
y | in | scalar, vector, or matrix | float | any
x | in | same as input y | float | same dimension(s) as input y
ret | out | same as input y | float | same dimension(s) as input y

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_1_4


tan - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

tan - HLSL

Returns the tangent of x.

Syntax

ret tan(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


tanh - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

tanh - HLSL

Returns the hyperbolic tangent of x.

Syntax

ret tanh(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | scalar, vector, or matrix | float | any
ret | out | same as input x | float | same dimension(s) as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_2_0


tex1D - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

tex1D - HLSL

There are two overloaded tex1D texture lookup functions:

  • 1-D texture lookup
  • 1-D texture lookup with partial derivatives

1-D texture lookup

This function performs a 1-D texture lookup.

Syntax

ret tex1D(s, t)

Where:

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler1D | 1
t | in | scalar | float | 1
ret | out | vector | float | 4

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_1_1

1-D texture lookup with partial derivatives

This function performas a 1-D texture lookup also, but also uses the partial derivatives to help pick the level of detail (LOD).

Syntax

ret tex1D(s, t, ddx, ddy)

Where:

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler1D | 1
t | in | scalar | float | 1
ddx | in | scalar | float | 1
ddy | in | scalar | float | 1
ret | out | vector | float | 4

See Also

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_2_0


tex1Dbias - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

tex1Dbias - HLSL

1-D biased texture lookup. The mip level is biased by t.w before the lookup takes place.

Syntax

ret tex1Dbias(s, t)

Where:

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler1D | 1
t | in | vector | float | 4
ret | out | vector | float | 4

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_2_0


tex1Dlod - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

tex1Dlod - HLSL

1-D texture lookup with level of detail (LOD).

Syntax

ret tex1Dlod(s, t)

Where:

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler1D | 1
t | in | vector | float | 4
ret | out | vector | float | 4

The mipmap LOD is specified in t.

Minimum Shader Version

This intrinsic function is supported in the following (or later) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_3_0


tex1Dgrad - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

tex1Dgrad - HLSL

1-D gradient texture lookup.

Syntax

ret tex1Dgrad(s, t, ddx, ddy)

Where:

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler1D | 1
t | in | vector | float | 1
ddx | in | vector | float | 1
ddy | in | vector | float | 1
ret | out | vector | float | 4

This function samples a texture using the sampler specified by s, the texture coordinate in t, the x gradient in ddx, and the y gradient in ddy. The gradient values select the appropriate mipmap level of the texture for sampling.

When compiling code to ps_3_0, significant code reordering is done to move gradient computations outside of flow control.

Minimum Shader Version

This intrinsic function is supported in the following (or later) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_2_0


tex1Dproj - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

tex1Dproj - HLSL

1-D projective texture lookup. t is a 2-D vector. t is divided by its last component before the lookup takes place.

Syntax

ret tex1Dproj(s, t)

Where:

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler1D | 1
t | in | vector | float | 4
ret | out | vector | float | 4

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_2_0


tex2D - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

tex2D - HLSL

There are two overloaded tex2D texture lookup functions:

  • 2-D texture lookup
  • 2-D texture lookup with partial derivatives

2-D texture lookup

This function performs a 2-D texture lookup.

Syntax

ret tex2D(s, t)

Where:

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler2D | 1
t | in | vector | float | 2
ret | out | vector | float | 4

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_1_1

2-D texture lookup with partial derivatives

This function performas a 2-D texture lookup also, but also uses the partial derivatives to help pick the level of detail (LOD).

Syntax

ret tex2D(s, t, ddx, ddy)

Where:

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler2D | 1
t | in | vector | float | 2
ddx | in | vector | float | 2
ddy | in | vector | float | 2
ret | out | vector | float | 4

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_2_0


tex2Dbias - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

tex2Dbias - HLSL

2-D biased texture lookup. The mip level is biased by t.w before the lookup takes place.

Syntax

ret tex2Dbias(s, t)

Where:

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler2D | 1
t | in | vector | float | 4
ret | out | vector | float | 4

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_2_0


tex2Dlod - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

tex2Dlod - HLSL

2-D texture lookup with level of detail (LOD).

Syntax

ret tex2Dlod(s, t)

Where:

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler2D | 1
t | in | vector | float | 4
ret | out | vector | float | 4

The mipmap LOD is specified in t.

Minimum Shader Version

This intrinsic function is supported in the following (or later) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_3_0


tex2Dgrad - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

tex2Dgrad - HLSL

2-D gradient texture lookup.

Syntax

ret tex2Dgrad(s, t, ddx, ddy)

Where:

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler1D | 1
t | in | vector | float | 2
ddx | in | vector | float | 2
ddy | in | vector | float | 2
ret | out | vector | float | 4

This function samples a texture using the sampler specified by s, the texture coordinates in t, the x gradient in ddx, and the y gradient in ddy. The gradient values select the appropriate mipmap level of the texture for sampling.

When compiling code to ps_3_0, significant code reordering is done to move gradient computations outside of flow control.

Minimum Shader Version

This intrinsic function is supported in the following (or later) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_2_0 *

* - If the D3DPS20CAPS cap is set with D3DPS20CAPS_GRADIENTINSTRUCTIONS, the compiler maps this statement to texldd.


tex2Dproj - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

tex2Dproj - HLSL

2-D projective texture lookup. t is divided by its last component before the lookup takes place.

Syntax

ret tex2Dproj(s, t)

Where:

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler2D | 1
t | in | vector | float | 4
ret | out | vector | float | 4

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_1_4


tex3D - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

tex3D - HLSL

There are two overloaded tex3D volume texture lookup functions:

  • 3-D texture lookup
  • 3-D texture lookup with partial derivatives

3-D texture lookup

This function performs a 3-D volume texture lookup.

Syntax

ret tex3D(s, t)

Where:

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler3D | 3
t | in | vector | float | 3
ret | out | vector | float | 4

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_1_1

3-D texture lookup with partial derivatives

This function performas a 3-D volume texture lookup also, but also uses the partial derivatives to help pick the level of detail (LOD).

Syntax

ret tex3D(s, t, ddx, ddy)

Where:

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler3D | 1
t | in | vector | float | 3
ddx | in | vector | float | 3
ddy | in | vector | float | 3
ret | out | vector | float | 4

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_2_0


tex3Dbias - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

tex3Dbias - HLSL

3-D biased volume texture lookup. The mip level is biased by t.w before the lookup takes place.

Syntax

ret tex3Dbias(s, t)

Where:

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler3D | 1
t | in | vector | float | 4
ret | out | vector | float | 4

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_2_0


tex3Dlod - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

tex3Dlod - HLSL

3-D volume texture lookup with level of detail (LOD).

Syntax

ret tex3Dlod(s, t)

Where:

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler3D | 1
t | in | vector | float | 4
ret | out | vector | float | 4

The mipmap LOD is specified in t.

Minimum Shader Version

This intrinsic function is supported in the following (or later) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_3_0


tex3Dgrad - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

tex3Dgrad - HLSL

3-D gradient volume texture lookup.

Syntax

ret tex3Dgrad(s, t, ddx, ddy)

Where:

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler1D | 1
t | in | vector | float | 3
ddx | in | vector | float | 3
ddy | in | vector | float | 3
ret | out | vector | float | 4

This function samples a texture using the sampler specified by s, the texture coordinates in t, the x gradient in ddx, and the y gradient in ddy. The gradient values select the appropriate mipmap level of the texture for sampling.

When compiling code to ps_3_0, significant code reordering is done to move gradient computations outside of flow control.

Minimum Shader Version

This intrinsic function is supported in the following (or later) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_2_0 *

* - If the D3DPS20CAPS cap is set with D3DPS20CAPS_GRADIENTINSTRUCTIONS, the compiler maps this statement to texldd.


tex3Dproj - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

tex3Dproj - HLSL

3-D projective volume texture lookup. t is divided by its last component before the lookup takes place.

Syntax

ret tex3Dproj(s, t, ddx, ddy)

Where:

Name | In/Out | Template Type | Component Type | Size
s | input sampler | object | sampler3D | 1
t | 3-D input texture coordinate and a projective divide value | vector | float | 3
ddx | 3 component partial derivative in x | vector | float | 3
ddy | 3 component partial derivative in y | vector | float | 3
ret | out | vector | float | 4

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_2_0


texCUBE - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

texCUBE - HLSL

There are two overloaded tex3D cube texture lookup functions:

  • 3-D cube texture lookup
  • 3-D cube texture lookup with partial derivatives

3-D cube texture lookup

This function performs a 3-D cube texture lookup.

Syntax

ret texCUBE(s, t)

Where:

Name | In/Out | Template Type | Component Type | Size
s | in | object | samplerCUBE | 1
t | in | vector | float | 3
ret | out | vector | float | 4

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_1_1

3-D cube texture lookup with partial derivatives

This function performs a 3-D cube texture lookup also, but also uses the partial derivatives to help pick the level of detail (LOD).

Syntax

ret texCUBE(s, t, ddx, ddy)

Where:

Name | In/Out | Template Type | Component Type | Size
s | in | object | samplerCUBE | 1
t | in | vector | float | 3
ddx | in | vector | float | 3
ddy | in | vector | float | 3
ret | out | vector | float | 4

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_2_0


texCUBEbias - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

texCUBEbias - HLSL

3-D biased cube texture lookup. The mip level is biased by t.w before the lookup takes place.

Syntax

ret texCUBE(s, t)

Where:

Name | In/Out | Template Type | Component Type | Size
s | in | object | samplerCUBE | 1
t | in | vector | float | 4
ret | out | vector | float | 4

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_2_0


texCUBElod - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

texCUBElod - HLSL

3-D cube texture lookup with level of detail (LOD).

Syntax

ret texCUBElod(s, t)

Where:

Name | In/Out | Template Type | Component Type | Size
s | in | object | samplerCUBE | 1
t | in | vector | float | 4
ret | out | vector | float | 4

The mipmap LOD is specified in t.

Minimum Shader Version

This intrinsic function is supported in the following (or later) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_3_0


texCUBEgrad - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

texCUBEgrad - HLSL

3-D gradient cube texture lookup.

Syntax

ret texCUBEgrad(s, t, ddx, ddy)

Where:

Name | In/Out | Template Type | Component Type | Size
s | in | object | sampler1D | 1
t | in | vector | float | 3
ddx | in | vector | float | 3
ddy | in | vector | float | 3
ret | out | vector | float | 4

This function samples a texture using the sampler specified by s, the texture coordinates in t, the x gradient in ddx, and the y gradient in ddy. The gradient values select the appropriate mipmap level of the texture for sampling.

When compiling code to ps_3_0, significant code reordering is done to move gradient computations outside of flow control.

Minimum Shader Version

This intrinsic function is supported in the following (or later) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_2_0 *

* If the D3DPS20CAPS cap is set with D3DPS20CAPS_GRADIENTINSTRUCTIONS, the compiler maps this statement to texldd.


texCUBEproj - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

texCUBEproj - HLSL

3-D projective cube texture lookup. t is divided by its last component before the lookup takes place.

Syntax

ret texCUBEproj(s, t)

Where:

Name | In/Out | Template Type | Component Type | Size
s | in | object | samplerCUBE | 1
t | in | vector | float | 4
ret | out | vector | float | 4

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
n/a | ps_2_0


transpose - HLSL
Microsoft DirectX 9.0 SDK Update (October 2004)

transpose - HLSL

Returns the transpose of the input matrix x. If the dimensions of the source matrix is p-rows x q-columns, the resulting matrix is q-columns x p-rows.

Syntax

ret transpose(x)

Where:

Name | In/Out | Template Type | Component Type | Size
x | in | matrix | float, int, bool | any
ret | out | matrix | float, int, bool | rows = same number of columns as input x, columns = same number of rows as input x

Minimum Shader Version

This intrinsic function is supported in the following (or above) shader versions:

Vertex Shader | Pixel Shader
vs_1_1 | ps_1_1


Asm Shader Reference
Microsoft DirectX 9.0 SDK Update (October 2004)

Asm Shader Reference

Shaders drive the programmable graphics pipeline.

Vertex Shader Reference

  • vs_1_1
  • vs_2_0
  • vs_2_x
  • vs_3_0

Vertex Shader Differences summarizes the differences between vertex shader versions.

Pixel Shader Reference

  • ps_1_1, ps_1_2, ps_1_3, ps_1_4
  • ps_2_0
  • ps_2_x
  • ps_3_0

Pixel Shader Differences summarizes the differences between pixel shader versions.

Behavior of Constant Registers in Assembly Shaders

There are two ways to set constant registers in an assembly shader:

  • Declare a shader constant in assembly code using one of the def* instructions.
  • Use one of the Set***ShaderConstant* application programming interface (API) methods.

DirectX 9 Shader Constants

In Microsoft DirectX 9.0 the lifetime of defined constants in a given shader is confined to the execution of that shader only (and is non-overridable). Defined constants in DirectX 9.0 have no side effects outside of the shader.

Here's an example using DirectX 9.0:

Given:
    Create shader1 which references c4 and defines it with the def instruction

Scenario 1:
    Call Set***Shader shader1
    Call Set***ShaderConstant* to set c4
    Call Draw
    Result: The shader will see the def'd value in c4

Given:
    Scenario 1 has just completed
    Create shader2 (which references c4 but does not use the def instruction
      to define it)

Scenario 2:
    Call Set***Shader shader2
    Call Draw
    Result: The shader will see the value last set in c4 by
     Set***ShaderConstant* in scenario 1. This is because shader 2
     didn't def c4.

In DirectX 9.0, calling Get***ShaderConstant* will only retrieve constant values set via Set***ShaderConstant*.

DirectX 8 Shader Constants

This behavior is different in DirectX 8.x.

Given:
    Create shader1 which references c4 and defines it with the def instruction

Scenario 1 (repeated with DirectX 8):
    Call Set***Shader with shader1
    Call Set***ShaderConstant to set c4
    Call Draw
    Result: The shader will see the value in c4 from Set***ShaderConstant

In DirectX 8.x Set***ShaderConstant takes effect immediately. Consider this scenario:

Given:
    Create shader1 which references c4 and defines it with the def instruction

Scenario 3:
    Call Set***Shader with shader1
    Call Draw
    Result: The shader will see the def'd value in c4

Given:
    Scenario 3 has just completed
    Create shader2 (which references c4 but does not use the def instruction
      to define it)

Scenario 4 :
    Call Set***Shader with shader2
    Call Draw
    Result: The shader will see the def'd value in c4 (set by def in shader 1)

The undesirable result is that the order in which the shaders are set could affect the observed behavior of individual shaders.

Shader Driver Model Requirements

DirectX 9.0 interfaces are restricted to device driver interface (DDI) drivers that are DirectX 7.0-level and above. To check the DDI level, run the DirectX Diagnostic Tool and examine the saved text file.

For reference, DirectX 8.0 interfaces work only on DDI drivers that are DirectX 6.0-level and above.

Shader Binary Format

The bitwise layout of the shader instruction stream is defined in D3d9types.h. If you want to design your own shader compiler or construction tools and you want more information about the shader token stream, refer to the DirectX 9.0 Driver Development Kit (DDK).

C-like Shader Language

See HLSL Shader Reference to experience a C-like shader language.


Vertex Shaders
Microsoft DirectX 9.0 SDK Update (October 2004)

Vertex Shaders

  • vs_1_1
  • vs_2_0
  • vs_2_x
  • vs_3_0
  • Vertex Shader Differences
  • Vertex Shader Instructions
  • Registers

To see the newest features introduced in shader model 3.0, see:

  • Shader Model 3


vs_1_1
Microsoft DirectX 9.0 SDK Update (October 2004)

vs_1_1

A programmable vertex shader is made up of a set of instructions that operate on vertex data. Registers transfer data in and out of the arithmetic logic unit (ALU). Additional control can be applied to modify the instruction, the results, or what data gets written out.

  • vs_1_1 Instructions contains a list of the available instructions.
  • Registers - vs_1_1 lists the different types of registers used by the vertex shader ALU.
  • Vertex Shader Instruction Modifiers are used to modify the way an instruction works.
  • Vertex Shader Source Register Modifiers alter the source register data before the instruction runs.
  • Source Register Swizzling gives additional control over which register components are read, copied or written.
  • Destination Register Masking determines what components of the destination register get written.


vs_2_0
Microsoft DirectX 9.0 SDK Update (October 2004)

vs_2_0

A programmable vertex shader is made up of a set of instructions that operate on vertex data. Registers transfer data in and out of the arithmetic logic unit (ALU). Additional control can be applied to modify the instruction, the results, or what data gets written out.

  • vs_2_0 Instructions contains a list of the available instructions.
  • Registers - vs_2_0 lists the different types of registers used by the vertex shader ALU.
  • Vertex Shader Instruction Modifiers are used to modify the way an instruction works.
  • Vertex Shader Source Register Modifiers alter the source register data before the instruction runs.
  • Source Register Swizzling gives additional control over which register components are read, copied, or written.
  • Destination Register Masking determines what components of the destination register get written.

Instruction Count

Each vertex shader can have up to 256 instructions stored. The number of instructions run can be much higher (because of the loop/rep support), and is capped by D3DCAPS9.MaxVShaderInstructionsExecuted, which should be at least 0xFFFF.


vs_2_x
Microsoft DirectX 9.0 SDK Update (October 2004)

vs_2_x

A programmable vertex shader is made up of a set of instructions that operate on vertex data. Registers transfer data in and out of the arithmetic logic unit (ALU). Additional control can be applied to modify the instruction, the results, or what data gets written out.

Vertex shader version vs_2_x extends the feature set supported by vs_2_0. Each additional feature is represented by a corresponding cap in the D3DCAPS9 structure within the VS20Caps member. To use any of the enhanced features represented by these caps, the vertex shader version must be specified as vs_2_x.

  • vs_2_x Instructions contains a list of the available instructions.
  • Registers - vs_2_x lists the different types of registers used by the vertex shader ALU.
  • Vertex Shader Instruction Modifiers are used to modify the way an instruction works.
  • Vertex Shader Source Register Modifiers alter the source register data before the instruction runs.
  • Source Register Swizzling gives additional control over which register components are read, copied, or written.
  • Destination Register Masking determines what components of the destination register get written.

New Features

New features are as follows:

Dynamic Flow Control

If D3DCAPS9.VS20Caps.DynamicFlowControlDepth > 0, then the following dynamic flow control instructions are supported:

  • if_comp
  • break
  • break_comp
If the D3DVS20CAPS_PREDICATION flag is also set on D3DCAPS9.VS20Caps.Caps, then the following additional flow control instructions are supported:
  • setp_comp
  • if pred
  • callnz pred
  • breakp
The range of values for dynamic flow control depth is 0 to 24 and is equal to the nesting depth of the dynamic flow control instructions (see Flow Control Nesting Limits for details). If this cap is zero, the device does not support dynamic flow control instructions.

Number of Temporary Registers

D3DCAPS9.VS20Caps.NumTemps represents the number of temporary registers (r#) supported by the device. The range of values for this cap is 12 to 32.

Static Flow Control Nesting Depth

D3DCAPS9.VS20Caps.StaticFlowControlDepth represents the nesting depth of two types of static flow control instructions: loop/rep and call/callnz bool. The range of values for this cap is 1 to 4. loop/rep instructions can be nested up to StaticFlowControlDepth deep. Independently, call/callnz bool instructions can be nested up to StaticFlowControlDepth deep. If D3DVS20CAPS_PREDICATION is also set, then callnz pred is counted toward the nesting depth of call/callnz bool (see Flow Control Nesting Limits for details).

Predication

If D3DVS20CAPS_PREDICATION is set on D3DCAPS9.VS20Caps, the device supports setp_comp and instruction predication. If D3DCAPS9.VS20Caps.DynamicFlowControlDepth is also greater then 0, then the following additional dynamic flow control instructions are supported:

  • if pred
  • callnz pred
  • breakp

Instruction Count

Each vertex shader can have up to 256 instructions stored. The number of instructions run can be much higher (because of the loop/rep support), and is capped by D3DCAPS9.MaxVShaderInstructionsExecutedin D3DCAPS9, which should be at least 0xFFFF.


vs_3_0
Microsoft DirectX 9.0 SDK Update (October 2004)

vs_3_0

A programmable vertex shader is made up of a set of instructions that operate on vertex data. Registers transfer data in and out of the arithmetic logic unit (ALU). Additional control can be applied to modify the instruction, the results, or what data gets written out.

Vertex shader version vs_3_0 extends the feature set supported by vs_2_x. Each of the features in vs_2_X that requires a cap to be set, is available in vs_3_0 without requiring the cap.

  • vs_3_0 Instructions contains a list of the available instructions.
  • Registers - vs_3_0 lists the different types of registers used by the vertex shader ALU.
  • Vertex Shader Instruction Modifiers are used to modify the way an instruction works.
  • Vertex Shader Source Register Modifiers alter the source register data before the instruction runs.
  • Source Register Swizzling gives additional control over which register components are read, copied, or written.
  • Destination Register Masking determines what components of the destination register get written.

New Features

New features of vertex shader version vs_3_0 are listed in the following sections.

Indexing Registers

In the earlier shader models, only the constant register bank could be indexed. In this model, the following register banks can be indexed, using the loop counter register (aL):

  • Input register (v#)
  • Output register (o#)

Vertex Textures

This shader model supports texture lookup in the vertex shader using texldl. The vertex engine has four texture sampler stages (distinct from the displacement map sampler and the texture samplers in the pixel engine) that can be used to sample textures set at those stages. See Vertex Textures in vs_3_0.

Vertex Stream Frequency

This feature allows a subset of the input registers to be initialized at a rate different from once per vertex. See Drawing Non-Indexed Geometry.

Shader Output

Similar to vs_2_0, the output of the shader can vary with static flow control. Be careful with dynamic branching as this can cause shader outputs to vary per vertex. This will produce unpredictable results on different hardware.

Dynamic flow control

All dynamic flow control instructions are supported. The maximum nesting depth value allowed is 24. (See Flow Control Nesting Limits for details.)

Temporary Registers

A total of 32 temporary registers (r#) is supported.

Static Flow Control

The maximum nesting depth for loop/rep is 4. The maximum nesting depth for call/callnz bool/callnz pred is 4. For if bool, the maximum nesting depth value allowed is 24. (See Flow Control Nesting Limits for details.)

Predication

Instruction predication is supported. Use setp_comp to set the predicate register.

Instruction Count

Each vertex shader is allowed anywhere from 512 up to the number of slots in MaxVertexShader30InstructionSlots in D3DCAPS9. The number of instructions run can be much higher because of the loop/rep support; however, this is capped by MaxVShaderInstructionsExecuted in D3DCAPS9 which should be at least 0xFFFF.

Device Caps

If Vertex Shader 3_0 is supported, the following caps are supported in hardware (at a minimum):

Cap | Capability
Shader caps
  • DynamicFlowControlDepth is 24
  • NumTemps is 32
  • StaticFlowControlDepth is 4
  • Predication is supported.
GuardBandLeft, GuardBandTop, GuardBandRight, GuardBandBottom | 8K
VertexShaderVersion | 3_0
MaxVertexShaderConst | 256
MaxVertexShader30InstructionSlots | 512
Fog support | RasterCaps
VertexTextureFilterCaps
  • D3DPTFILTERCAPS_MINFPOINT
  • D3DPTFILTERCAPS_MAGFPOINT
D3DDEVCAPS2_VERTEXELEMENTSCANSHARESTREAMOFFSET | Vertex elements in a vertex declaration can share the same stream offset.
Vertex formats
  • D3DDECLTYPE_UBYTE4
  • D3DDECLTYPE_UBYTE4N
  • D3DDECLTYPE_SHORT2N
  • D3DDECLTYPE_SHORT4N
  • D3DDECLTYPE_FLOAT16_2
  • D3DDECLTYPE_FLOAT16_4


Vertex Shader Differences
Microsoft DirectX 9.0 SDK Update (October 2004)

Vertex Shader Differences

Instruction Slots

Each version supports a differing number of maximum instruction slots.

Version | Maximum number of instruction slots
vs_1_1 | 128
vs_2_0 | 256
vs_2_x | 256
vs_3_0 | 512 minimum, and up to the number of slots in D3DCAPS9.MaxVertexShader30InstructionSlots. See D3DCAPS9.

For information about the limitations of software shaders, see Software Shaders.

Flow Control Nesting Limits

  • See Flow Control Nesting Limits.

vs_1_1 Features

New instructions:

See vs_1_1 Instructions.

New registers:

See Registers - vs_1_1.

vs_2_0 Features

New features:

  • Static flow control
  • All four components of the Address Register (a0) are available.

New instructions:

  • Setup instructions - defb, defi
  • Arithmetic instructions - abs, crs, lrp, mova, nrm, pow, sgn, sincos
  • Static flow control instructions - call, callnz bool, else, endif, endloop, endrep, if bool, label, loop, rep, ret

New registers:

  • Constant Boolean Register (b#)
  • Constant Integer Register (i#)
  • Loop Counter Register (aL)

vs_2_x Features

New features (D3DCAPS9.VS20Caps):

  • Dynamic flow control
  • Nesting for dynamic and static flow control instructions
  • Number of Temporary Registers (r#) increased
  • Predication

New Instructions:

  • Dynamic flow control instructions - break, break_comp, breakp, callnz pred, if_comp, if pred, setp_comp

New registers:

  • Predicate Register (p0)

vs_3_0 Features

New features :

  • Texture lookup
  • Indexable Output Registers (o#)
  • Number of Temporary Registers (r#) increased to 32

New instructions:

  • Setup instruction - dcl_samplerType
  • Texture instruction - texldl

New registers:

  • Sampler (s#)


Vertex Shader Instructions
Microsoft DirectX 9.0 SDK Update (October 2004)

Vertex Shader Instructions

  • vs_1_1 Instructions
  • vs_2_0 Instructions
  • vs_2_x Instructions
  • vs_3_0 Instructions
  • Vertex Shader Instruction Modifiers
  • Flow Control Nesting Limits


Instructions - vs_1_1
Microsoft DirectX 9.0 SDK Update (October 2004)

Instructions - vs_1_1

This section contains reference information for the vertex shader version 1_1 instructions.

There are several types of vertex shader instructions, as shown in the table. Columns to the right mean the following:

  • Instruction slots - Number of instruction slots used by each instruction.
  • Setup - Non-arithmetic instructions. Every shader must have a version instruction and it must be the first instruction.
  • Arithmetic - These instructions provide the mathematical operations in a shader.
  • New - These instructions are new to this version.

Instruction Set

Name | Description | Instruction slots | Setup | Arithmetic | New
add | Add two vectors | 1 |  | x | x
dcl_usage input register - vs | Declare input vertex registers (see Registers - vs_1_1) | 0 | x |  | x
def | Define constants | 0 | x |  | x
dp3 | Three-component dot product | 1 |  | x | x
dp4 | Four-component dot product | 1 |  | x | x
dst | Calculate the distance vector | 1 |  | x | x
exp | Full precision 2x | 10 |  | x | x
expp | Partial precision 2x | 1 |  | x | x
frc | Fractional component | 3 |  | x | x
lit | Partial lighting calculation | 1 |  | x | x
log | Full precision log2(x) | 10 |  | x | x
logp | Partial precision log2(x) | 1 |  | x | x
m3x2 | 3x2 multiply | 2 |  | x | x
m3x3 | 3x3 multiply | 3 |  | x | x
m3x4 | 3x4 multiply | 4 |  | x | x
m4x3 | 4x3 multiply | 3 |  | x | x
m4x4 | 4x4 multiply | 4 |  | x | x
mad | Multiply and add | 1 |  | x | x
max | Maximum | 1 |  | x | x
min | Minimum | 1 |  | x | x
mov | Move | 1 |  | x | x
mul | Multiply | 1 |  | x | x
nop | No operation | 1 |  | x | x
rcp | Reciprocal | 1 |  | x | x
rsq | Reciprocal square root | 1 |  | x | x
sge | Greater than or equal compare | 1 |  | x | x
slt | Less than compare | 1 |  | x | x
sub | Subtract | 1 |  | x | x
vs | Version | 0 | x |  | x


Instructions - vs_2_0
Microsoft DirectX 9.0 SDK Update (October 2004)

Instructions - vs_2_0

This section contains reference information for the vertex shader version 2_0 instructions.

There are several types of vertex shader instructions, as shown in the table. Columns to the right mean the following:

  • Instruction slots - Number of instruction slots used by each instruction.
  • Setup - Non-arithmetic instructions. Every shader must have a version instruction and it must be the first instruction.
  • Arithmetic - These instructions provide the mathematical operations in a shader.
  • Flow control - These instructions add flow control capabilities such as loop...endloop, if...else...endif, and subroutine calls.
  • New - These instructions are new to this version.

Instruction Set

Name | Description | Instruction slots | Setup | Arithmetic | Flow control | New
abs | Absolute value | 1 |  | x |  | x
add | Add two vectors | 1 |  | x |  |
call | Call a subroutine | 2 |  |  | x | x
callnz bool | Call a subroutine if a Boolean register is not zero | 3 |  |  | x | x
crs | Cross product | 2 |  | x |  | x
dcl_usage input register - vs | Declare input vertex registers (see Registers - vs_2_0) | 0 | x |  |  |
def | Define constants | 0 | x |  |  |
defb | Define a Boolean constant | 0 | x |  |  | x
defi | Define an integer constant | 0 | x |  |  | x
dp3 | Three-component dot product | 1 |  | x |  |
dp4 | Four-component dot product | 1 |  | x |  |
dst | Calculate the distance vector | 1 |  | x |  |
else | Begin an else block | 1 |  |  | x | x
endif | End an if bool...else block | 1 |  |  | x | x
endloop | End of a loop block | 2 |  |  | x | x
endrep | End of a repeat block | 2 |  |  | x | x
exp | Full precision 2x | 1 |  | x |  |
expp | Partial precision 2x | 1 |  | x |  |
frc | Fractional component | 1 |  | x |  |
if bool | Begin an if bool block (using a Boolean condition) | 3 |  |  | x | x
label | Label | 0 |  |  | x | x
lit | Partial lighting calculation | 3 |  | x |  |
log | Full precision log2(x) | 1 |  | x |  |
logp | Partial precision log2(x) | 1 |  | x |  |
loop | Loop | 3 |  |  | x | x
lrp | Linear interpolation | 2 |  | x |  | x
m3x2 | 3x2 multiply | 2 |  | x |  |
m3x3 | 3x3 multiply | 3 |  | x |  |
m3x4 | 3x4 multiply | 4 |  | x |  |
m4x3 | 4x3 multiply | 3 |  | x |  |
m4x4 | 4x4 multiply | 4 |  | x |  |
mad | Multiply and add | 1 |  | x |  |
max | Maximum | 1 |  | x |  |
min | Minimum | 1 |  | x |  |
mov | Move | 1 |  | x |  |
mova | Move data from a floating-point register to the address register (a0) | 1 |  | x |  | x
mul | Multiply | 1 |  | x |  |
nop | No operation | 1 |  | x |  |
nrm | Normalize a 4-D vector | 3 |  | x |  | x
pow | xy | 3 |  | x |  | x
rcp | Reciprocal | 1 |  | x |  |
rep | Repeat | 3 |  |  | x | x
ret | End of either a subroutine or main | 1 |  |  | x | x
rsq | Reciprocal square root | 1 |  | x |  |
sge | Greater than or equal compare | 1 |  | x |  |
sgn | Sign | 3 |  | x |  | x
sincos | Sine and cosine | 8 |  | x |  | x
slt | Less than compare | 1 |  | x |  |
sub | Subtract | 1 |  | x |  |
vs | Version | 0 | x |  |  |


Instructions - vs_2_x
Microsoft DirectX 9.0 SDK Update (October 2004)

Instructions - vs_2_x

This section contains reference information for the vertex shader version 2_x instructions.

There are several types of vertex shader instructions, as shown in the table. Columns to the right mean the following:

  • Instruction slots - Number of instruction slots used by each instruction.
  • Setup - Non-arithmetic instructions. Every shader must have a version instruction and it must be the first instruction.
  • Arithmetic - These instructions provide the mathematical operations in a shader.
  • Flow control - These instructions add flow control capabilities such as loop...endloop, if bool...else...endif, and subroutine calls.
  • New - These instructions are new to this version.

Instruction Set

Name | Description | Instruction slots | Setup | Arithmetic | Flow control | New
abs | Absolute value | 1 |  | x |  |
add | Add two vectors | 1 |  | x |  |
break | Break out of a loop...endloop or rep...endrep block | 1 |  |  | x | x
break_comp | Conditionally break out of a loop...endloop or rep...endrep block, with a comparison | 3 |  |  | x | x
breakp | Break out of a loop...endloop or rep...endrep block, based on a predicate | 3 |  |  | x | x
call | Call a subroutine | 2 |  |  | x |
callnz bool | Call a subroutine if a Boolean register is not zero | 3 |  |  | x |
callnz pred | Call a subroutine if a predicate register is not zero | 3 |  |  | x | x
crs | Cross product | 2 |  | x |  |
dcl_usage input register - vs | Declare input vertex registers (see Registers - vs_2_x) | 0 | x |  |  |
def | Define constants | 0 | x |  |  |
defb | Define a Boolean constant | 0 | x |  |  |
defi | Define an integer constant | 0 | x |  |  |
dp3 | Three-component dot product | 1 |  | x |  |
dp4 | Four-component dot product | 1 |  | x |  |
dst | Calculate the distance vector | 1 |  | x |  |
else | Begin an else block | 1 |  |  | x |
endif | End an if bool...else block | 1 |  |  | x |
endloop | End of a loop block | 2 |  |  | x |
endrep | End of a repeat block | 2 |  |  | x |
exp | Full precision 2x | 1 |  | x |  |
expp | Partial precision 2x | 1 |  | x |  |
frc | Fractional component | 1 |  | x |  |
if bool | Begin an if bool block (using a Boolean condition) | 3 |  |  | x |
if_comp | Begin an if bool block, with a comparison | 3 |  |  | x | x
if pred | Begin an if bool block with a predicate condition | 3 |  |  | x | x
label | Label | 0 |  |  | x |
lit | Partial lighting calculation | 3 |  | x |  |
log | Full precision log2(x) | 1 |  | x |  |
logp | Partial precision log2(x) | 1 |  | x |  |
loop | Loop | 3 |  |  | x |
lrp | Linear interpolation | 2 |  | x |  |
m3x2 | 3x2 multiply | 2 |  | x |  |
m3x3 | 3x3 multiply | 3 |  | x |  |
m3x4 | 3x4 multiply | 4 |  | x |  |
m4x3 | 4x3 multiply | 3 |  | x |  |
m4x4 | 4x4 multiply | 4 |  | x |  |
mad | Multiply and add | 1 |  | x |  |
max | Maximum | 1 |  | x |  |
min | Minimum | 1 |  | x |  |
mov | Move | 1 |  | x |  |
mova | Move data from a floating-point register to the address register (a0) | 1 |  | x |  |
mul | Multiply | 1 |  | x |  |
nop | No operation | 1 |  | x |  |
nrm | Normalize a 4-D vector | 3 |  | x |  |
pow | xy | 3 |  | x |  |
rcp | Reciprocal | 1 |  | x |  |
rep | Repeat | 3 |  |  | x |
ret | End of either a subroutine or main | 1 |  |  | x |
rsq | Reciprocal square root | 1 |  | x |  |
setp_comp | Set the predicate register | 1 |  |  | x | x
sge | Greater than or equal compare | 1 |  | x |  |
sgn | Sign | 3 |  | x |  |
sincos | Sine and cosine | 8 |  | x |  |
slt | Less than compare | 1 |  | x |  |
sub | Subtract | 1 |  | x |  |
vs | Version | 0 | x |  |  |


Instructions - vs_3_0
Microsoft DirectX 9.0 SDK Update (October 2004)

Instructions - vs_3_0

This section contains reference information for the vertex shader version 3_0 instructions.

There are several types of vertex shader instructions, as shown in the table. Columns to the right mean the following:

  • Instruction slots - Number of instruction slots used by each instruction.
  • Setup - Non-arithmetic instructions. Every shader must have a version instruction and it must be the first instruction.
  • Arithmetic - These instructions provide the mathematical operations in a shader.
  • Texture - These instructions support texture address lookup.
  • Flow control - These instructions add flow control such as loops, repeats, and if bool...else...endif comparisons.
  • New - These instructions are new to this version.

Instruction Set

Name | Description | Instruction slots | Setup | Arithmetic | Texture | Flow control | New
abs | Absolute value | 1 |  | x |  |  |
add | Add two vectors | 1 |  | x |  |  |
break | Break out of a loop...endloop or rep...endrep block | 1 |  |  |  | x |
break_comp | Conditionally break out of a loop...endloop or rep...endrep block, with a comparison | 3 |  |  |  | x |
breakp | Break out of a loop...endloop or rep...endrep block, based on a predicate | 3 |  |  |  | x |
call | Call a subroutine | 2 |  |  |  | x |
callnz bool | Call a subroutine if a Boolean register is not zero | 3 |  |  |  | x |
callnz pred | Call a subroutine if a predicate register is not zero | 3 |  |  |  | x |
crs | Cross product | 2 |  | x |  |  |
dcl_usage outut register - vs | Declare input vertex registers (see Registers - vs_3_0) | 0 | x |  |  |  |
dcl_samplerType | Declare the texture dimension for a sampler | 0 | x |  |  |  | x
def | Define constants | 0 | x |  |  |  |
defb | Declare a Boolean constant | 0 | x |  |  |  |
defi | Declare an integer constant | 0 | x |  |  |  |
dp3 | Three-component dot product | 1 |  | x |  |  |
dp4 | Four-component dot product | 1 |  | x |  |  |
dst | Distance | 1 |  | x |  |  |
else | Begin an else block | 1 |  |  |  | x |
endif | End an if bool...else block | 1 |  |  |  | x |
endloop | End of a loop block | 2 |  |  |  | x |
endrep | End of a repeat block | 2 |  |  |  | x |
exp | Full precision 2x | 1 |  | x |  |  |
expp | Partial precision 2x | 1 |  | x |  |  |
frc | Fractional component | 1 |  | x |  |  |
if bool | Begin an if bool block (using a Boolean condition) | 3 |  |  |  | x |
if_comp | Begin an if bool block, with a comparison | 3 |  |  |  | x |
if pred | Begin an if bool block with a predicate condition | 3 |  |  |  | x |
label | Label | 0 |  |  |  | x |
lit | Calculate lighting | 3 |  | x |  |  |
log | Full precision log2(x) | 1 |  | x |  |  |
logp | Partial precision log2(x) | 1 |  | x |  |  |
loop | Loop | 3 |  |  |  | x |
lrp | Linear interpolation | 2 |  | x |  |  |
m3x2 | 3x2 multiply | 2 |  | x |  |  |
m3x3 | 3x3 multiply | 3 |  | x |  |  |
m3x4 | 3x4 multiply | 4 |  | x |  |  |
m4x3 | 4x3 multiply | 3 |  | x |  |  |
m4x4 | 4x4 multiply | 4 |  | x |  |  |
mad | Multiply and add | 1 |  | x |  |  |
max | Maximum | 1 |  | x |  |  |
min | Minimum | 1 |  | x |  |  |
mov | Move | 1 |  | x |  |  |
mova | Move data from a floating point register to an integer register | 1 |  | x |  |  |
mul | Multiply | 1 |  | x |  |  |
nop | No operation | 1 |  | x |  |  |
nrm | Normalize | 3 |  | x |  |  |
pow | xy | 3 |  | x |  |  |
rcp | Reciprocal | 1 |  | x |  |  |
rep | Repeat | 3 |  |  |  | x |
ret | End of a subroutine | 1 |  |  |  | x |
rsq | Reciprocal square root | 1 |  | x |  |  |
setp_comp | Set the predicate register | 1 |  |  |  | x |
sge | Greater than or equal compare | 1 |  | x |  |  |
sgn | Sign | 3 |  | x |  |  |
sincos | Sine and cosine | 8 |  | x |  |  |
slt | Less than compare | 1 |  | x |  |  |
sub | Subtract | 1 |  | x |  |  |
texldl | Texture load with user-adjustable level of detail (LOD) | See note 1 |  |  | x |  | x
vs | Version | 0 | x |  |  |  |

Notes:

  1. if the texture is a cube map, slots = 5; otherwise slots = 2


Flow Control Nesting Limits
Microsoft DirectX 9.0 SDK Update (October 2004)

Flow Control Nesting Limits

Vertex shader flow control instructions have two special restrictions. Nesting depths restrict the number of instructions that can be called inside of each other. In addition, each instruction has an instruction slot count that applies against the maximum number of instruction that a shader can support.

Depth Count per Instruction for vs_2_0

Each instruction counts against one or more nesting depth limits. This table shows the depth count that each instruction adds or subtracts from the existing depth:

Instruction | Static nesting | Dynamic nesting | loop/rep nesting | call nesting | Static flow count
if bool | 0 | 0 | 0 | 0 | 1
if_comp | n/a | n/a | n/a | n/a | n/a
if pred | n/a | n/a | n/a | n/a | n/a
else | 0 | 0 | 0 | 0 | 1(if bool only)
endif | -1 | 0 | 0 | 0 | 0
rep | 0 | 0 | 1 | 0 | 1
endrep | 0 | 0 | -1 | 0 | 0
loop | 0 | 0 | 1 | 0 | 1
endloop | 0 | 0 | -1 | 0 | 0
break | n/a | n/a | n/a | n/a | n/a
break_comp | n/a | n/a | n/a | n/a | n/a
breakp | n/a | n/a | n/a | n/a | n/a
call | 0 | 0 | 0 | 1 | 1
callnz bool | 0 | 0 | 0 | 1 | 1
callnz pred | n/a | n/a | n/a | n/a | n/a
ret | 0 | 0 | 0 | -1 | 0
setp_comp | n/a | n/a | n/a | n/a | n/a

Nesting Depth

Nesting depth define how many instructions can be called inside of each other. Each type of instruction has one or more nesting limits:

Instruction Type | Maximum
Static nesting | Only limited by the static flow count
Dynamic nesting | n/a
loop/rep nesting | 1
call nesting | 1
Static flow count | 16

Depth Count per Instruction for vs_2_x

Each instruction counts against one or more nesting depth limits. This table shows the depth count that each instruction adds or subtracts from the existing depth:

Instruction | Static nesting | Dynamic nesting | loop/rep nesting | call nesting | Static flow count
if bool | 1 | 0 | 0 | 0 | 1
if_comp | 0 | 1 | 0 | 0 | 0
if pred | 0 | 1 | 0 | 0 | 0
else | 0 | 0 | 0 | 0 | 1(if bool only)
endif | -1(if bool) | -1(if pred or if_comp) | 0 | 0 | 0
rep | 0 | 0 | 1 | 0 | 1
endrep | 0 | 0 | -1 | 0 | 0
loop | 0 | 0 | 1 | 0 | 1
endloop | 0 | 0 | -1 | 0 | 0
break | 0 | 0 | 0 | 0 | 0
break_comp | 0 | 1, -1 | 0 | 0 | 0
breakp | 0 | 0 | 0 | 0 | 0
call | 0 | 0 | 0 | 1 | 1
callnz bool | 0 | 0 | 0 | 1 | 1
callnz pred | 0 | 1 | 0 | 1 | 0
ret | 0 | -1 (callnz pred) | 0 | -1 | 0
setp_comp | 0 | 0 | 0 | 0 | 0

Nesting Depth

Nesting depth define how many instructions can be called inside of each other. Each type of instruction has one or more nesting limits:

Instruction Type | Maximum
Static nesting | Only limited by the static flow count
Dynamic nesting | 0 or 24, see D3DCAPS9.VS20Caps.DynamicFlowControlDepth
loop/rep nesting | 1 to 4, see D3DCAPS9.VS20Caps.StaticFlowControlDepth
call nesting | 1 to 4, see D3DCAPS9.VS20Caps.StaticFlowControlDepth (independent of loop/rep limit)
Static flow count | 16

Depth Count per Instruction for vs_2_sw

Each instruction counts against one or more nesting depth limits. This table shows the depth count that each instruction adds or subtracts from the existing depth:

Instruction | Static nesting | Dynamic nesting | loop/rep nesting | call nesting | Static flow count
if bool | 1 | 0 | 0 | 0 | n/a
if_comp | 0 | 1 | 0 | 0 | n/a
if pred | 0 | 1 | 0 | 0 | n/a
else | 0 | 0 | 0 | 0 | n/a
endif | -1(if bool) | -1(if pred or if_comp) | 0 | 0 | n/a
rep | 0 | 0 | 1 | 0 | n/a
endrep | 0 | 0 | -1 | 0 | n/a
loop | 0 | 0 | 1 | 0 | n/a
endloop | 0 | 0 | -1 | 0 | n/a
break | 0 | 0 | 0 | 0 | n/a
break_comp | 0 | 1, -1 | 0 | 0 | n/a
breakp | 0 | 0 | 0 | 0 | n/a
call | 0 | 0 | 0 | 1 | n/a
callnz bool | 0 | 0 | 0 | 1 | n/a
callnz pred | 0 | 1 | 0 | 1 | n/a
ret | 0 | -1 (callnz pred) | 0 | -1 | n/a
setp_comp | 0 | 0 | 0 | 0 | n/a

Nesting Depth

Nesting depth define how many instructions can be called inside of each other. Each type of instruction has one or more nesting limits:

Instruction Type | Maximum
Static nesting | 24
Dynamic nesting | 24
loop/rep nesting | 4
call nesting | 4
Static flow count | No limit

Depth Count per Instruction for vs_3_0

Each instruction counts against one or more nesting depth limits. This table shows the depth count that each instruction adds or subtracts from the existing depth:

Instruction | Static nesting | Dynamic nesting | loop/rep nesting | call nesting | Static flow count
if bool | 1 | 0 | 0 | 0 | n/a
if_comp | 0 | 1 | 0 | 0 | n/a
if pred | 0 | 1 | 0 | 0 | n/a
else | 0 | 0 | 0 | 0 | n/a
endif | -1(if bool) | -1(if pred or if_comp) | 0 | 0 | n/a
rep | 0 | 0 | 1 | 0 | n/a
endrep | 0 | 0 | -1 | 0 | n/a
loop | 0 | 0 | 1 | 0 | n/a
endloop | 0 | 0 | -1 | 0 | n/a
break | 0 | 0 | 0 | 0 | n/a
break_comp | 0 | 1, -1 | 0 | 0 | n/a
breakp | 0 | 0 | 0 | 0 | n/a
call | 0 | 0 | 0 | 1 | n/a
callnz bool | 0 | 0 | 0 | 1 | n/a
callnz pred | 0 | 1 | 0 | 1 | n/a
ret | 0 | -1 (callnz pred) | 0 | -1 | n/a
setp_comp | 0 | 0 | 0 | 0 | n/a

Nesting Depth

Nesting depth define how many instructions can be called inside of each other. Each type of instruction has one or more nesting limits:

Instruction Type | Maximum
Static nesting | 24
Dynamic nesting | 24
loop/rep nesting | 4
call nesting | 4
Static flow count | No limit

Depth Count per Instruction for vs_3_sw

Each instruction counts against one or more nesting depth limits. This table shows the depth count that each instruction adds or subtracts from the existing depth:

Instruction | Static nesting | Dynamic nesting | loop/rep nesting | call nesting | Static flow count
if bool | 1 | 0 | 0 | 0 | n/a
if_comp | 0 | 1 | 0 | 0 | n/a
if pred | 0 | 1 | 0 | 0 | n/a
else | 0 | 0 | 0 | 0 | n/a
endif | -1(if bool) | -1(if pred or if_comp) | 0 | 0 | n/a
rep | 0 | 0 | 1 | 0 | n/a
endrep | 0 | 0 | -1 | 0 | n/a
loop | 0 | 0 | 1 | 0 | n/a
endloop | 0 | 0 | -1 | 0 | n/a
break | 0 | 0 | 0 | 0 | n/a
break_comp | 0 | 1, -1 | 0 | 0 | n/a
breakp | 0 | 0 | 0 | 0 | n/a
call | 0 | 0 | 0 | 1 | n/a
callnz bool | 0 | 0 | 0 | 1 | n/a
callnz pred | 0 | 1 | 0 | 1 | n/a
ret | 0 | -1 (callnz pred) | 0 | -1 | n/a
setp_comp | 0 | 0 | 0 | 0 | n/a

Nesting Depth

Nesting depth define how many instructions can be called inside of each other. Each type of instruction has one or more nesting limits:

Instruction Type | Maximum
Static nesting | 24
Dynamic nesting | 24
loop/rep nesting | 4
call nesting | 4
Static flow count | No limit


Modifiers
Microsoft DirectX 9.0 SDK Update (October 2004)

Modifiers

Instruction modifiers affect the result of the instruction before it is written into the destination register.

_sat

Saturates (or clamps) the instruction result to [0,1] range before writing to the destination register.

For example:

add_sat dst, src0, src1

Where:

dst = clamp_between_0_and_1(src0 + src1)

The _sat instruction modifier costs no additional instruction slots.

If supported, the _sat instruction modifier can be used with any instruction except: frc, sincos, and texldl.

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
_sat |  |  |  |  | x | x


abs - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

abs - vs

Computes absolute value.

Syntax

abs dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
abs |  | x | x | x | x | x

This instruction works as shown here.

dest.x = abs(src.x)
dest.y = abs(src.y)
dest.z = abs(src.z)
dest.w = abs(src.w)


add - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

add - vs

Adds two vectors.

Syntax

add dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
add | x | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x = src0.x + src1.x;
dest.y = src0.y + src1.y;
dest.z = src0.z + src1.z;
dest.w = src0.w + src1.w;


break - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

break - vs

Break out of the current loop at the nearest endloop or endrep.

Syntax

break

Remarks

This instruction is supported in the following versions.

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
break |  |  | x | x | x | x


break_comp - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

break_comp - vs

Conditionally break out of the current loop at the nearest endloop or endrep.

Syntax

break_comp src0, src1

Where:

  • _comp is a comparison between the two source registers. It can be one of the following:
    Syntax | Comparison
    _gt | Greater than
    _lt | Less than
    _ge | Greater than or equal
    _le | Less than or equal
    _eq | Equal to
    _ne | Not equal to
  • src0 is a source register. Replicate swizzle is required to select a single component.
  • src1 is a source register. Replicate swizzle is required to select a single component.

Remarks

This instruction is supported in the following versions.

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
break_comp |  |  | x | x | x | x

When the comparison is true, it breaks out of the current loop, as shown.

if (src0 comparison src1)
   jump to the corresponding endloop or endrep instruction;


breakp - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

breakp - vs

Conditionally break out of the current loop at the nearest endloop or endrep. Use one of the components of the predicate register as a condition to determine whether or not to perform the instruction.

Syntax

breakp [!]p0.{x|y|z|w}

Where:

  • [!] optional boolean NOT.
  • p0 is the predicate register. See Predicate Register.
  • {x|y|z|w} is the required replicate swizzle on p0.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
breakp |  |  | x | x | x | x


call - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

call - vs

Performs a function call to the instruction marked with the provided label.

Syntax

call l#

where l# is a label marking the beginning of the subroutine to be called.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
call |  | x | x | x | x | x

This instruction does the following:

  1. Push address of the next instruction to the return address stack.
  2. Continue execution from the instruction marked by the label.

In vertex shader 2_0, nesting calls are not allowed.

In vertex shader 2_x, the nesting depth is limited by the StaticFlowControlDepth element of the D3DVSHADERCAPS2_0 structure. For more information, see IDirect3D9::GetDeviceCaps.

In vertex shader 3_0, four levels of call nesting are allowed.

Only forward calls are allowed. This means that the location of the label inside the vertex shader should be after the call instruction referencing it.

If a call instruction is invoked inside loop...endloop block, the value of the Loop Counter Register (aL) is accessible inside the subroutine.

If a subroutine is referencing the Loop Counter Register (aL) located outside of the subroutine, every instance of the call to this subroutine should be surrounded by a loop...endloop block.


callnz bool - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

callnz bool - vs

Call if not zero. Performs a conditional call to the instruction marked by the label index.

Syntax

callnz l#, [!]b#

where:

  • where l# is a label marking the beginning of the subroutine to be called.
  • [!] is the optional boolean NOT modifier.
  • b# identifies a Constant Boolean Register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
callnz bool |  | x | x | x | x | x

This instruction does the following:

if (specified boolean register is not zero)
{
    Push address of the next instruction to the return address stack.
    Continue execution from the instruction marked by the label.
}

This instruction consumes one vertex shader instruction slot.


callnz pred - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

callnz pred - vs

Call if not zero, with a predicate. Performs a conditional call to the instruction marked by the label index. Predication uses a boolean value to determine whether of not to perform the instruction.

Syntax

callnz l#, [!]p0.{x|y|z|w}

where:

  • l# is a label marking the beginning of the subroutine to be called.
  • [!] is an optional negate modifier.
  • p0 is the Predicate Register.
  • {x|y|z|w} is the required replicate swizzle on p0.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
callnz pred |  |  | x | x | x | x

This instruction does the following:

if (specified register component is not zero)
{
    Push address of the next instruction to the return address stack.
    Continue execution from the instruction marked by the label.
}

This instruction consumes one vertex shader instruction slot.


crs - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

crs - vs

Computes a cross product using the right-hand rule.

Syntax

crs dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
crs |  | x | x | x | x | x

This instruction works as shown here.

dest.x = src0.y * src1.z - src0.z * src1.y;
dest.y = src0.z * src1.x - src0.x * src1.z;
dest.z = src0.x * src1.y - src0.y * src1.x;

Some restrictions on use:

  • src0 cannot be the same register as dest.
  • src1 cannot be the same register as dest.
  • src0 cannot have any swizzle other than the default swizzle (.xyzw).
  • src1 cannot have any swizzle other than the default swizzle (.xyzw).
  • dest has to have exactly one of the following seven masks: .x | .y | .z | .xy | .xz | .yz | .xyz.
  • dest must be a temporary register.
  • dest must not be the same register as src0 or src1


dcl_samplerType - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

dcl_samplerType - vs

Declare a vertex shader sampler.

Syntax

dcl_samplerType s#

where:

  • _samplerType defines the sampler data type. This determines how many coordinates are required by each texture coordinate when sampling. The following texture coordinate dimensions are defined.
    • _2d
    • _cube
    • _volume
  • s# identifies a sampler where s is an abbreviation for the sampler, and # is the sampler number. Samplers are pseudo registers because you cannot directly read or write to them.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dcl_samplerType |  |  |  |  | x | x

All dcl_samplerType instructions must appear before the first executable instruction.


dcl_usage input register - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

dcl_usage input register - vs

Declare the association between a vertex element usage and a usage index for a vertex shader input register.

Syntax

dcl_usage[usage_index] v#

Where:

  • dcl_usage identifies how the register data will be used. This is the same value as the members of D3DDECLUSAGE without the D3DDECLUSAGE prefix.
  • usage_index is an optional integer index between 0 and 15. It modifies the usage data. The index matches the usage index in a vertex declaration. See Vertex Declaration. The index is appended to the usage value (dcl_usage) with no space. If it is not supplied, it is assumed to be 0.
  • v# is a Input Register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dcl_usage | x | x | x | x | x | x

All dcl_usage instructions must appear before the first executable instruction.


dcl_usage outut register - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

dcl_usage outut register - vs

The various types of output registers have been collapsed into twelve output registers (two for color, eight for texture, one for position, and one for fog and point size). These can be used for anything the user wants to interpolate for the pixel shader: texture coordinates, colors, fog, and so on.

Output registers require declarations that include semantics. For instance, the old position and point size registers are replaced by declaring an output register with a position or point-size semantic.

Of the twelve output registers, any ten (not necessarily o0 to o9) have four components (xyzw), another one must be declared as position (and must also include all four components), and optionally one more can be a scalar point size.

Syntax

The syntax for declaring output registers is similar to the declarations for the input register:

dcl_semantics o[.write_mask]

Where:

  • dcl_semantics can use the same set of semantics as for the input declaration. Semantic names come from D3DDECLUSAGE (and are paired with an index, such as position3). There always has to be one output register with the positiont0 semantic when not used for processing vertices. The positiont0 semantic and the pointsize0 semantic are the only ones that have meaning beyond simply allowing linkage from vertex to pixel shaders. For shaders with flow control, it is assumed that the worst case output is declared. There are no defaults if a shader does not actually output what it declares it should (due to flow control).
  • o is an output register. See Output Registers.
  • write_mask indicates the same output register that can be declared multiple times (so different semantics can be applied to individual components), each time with a unique write mask. However, the same semantic cannot be used multiple times in a declaration. This means that vectors must be four components or less, and cannot go across four-component register boundaries (individual registers). When the point-size semantic is used, it should have full write mask because it is considered a scalar. When the position semantic is used, it should have a full write mask because all four components have to be written.

Remarks

Vertex shader versions | 3_0 | 3_sw
dcl_usage | x | x

All dcl_usage instructions must appear before the first executable instruction.

Declaration Examples

vs_3_0
dcl_color4     o3.x    // color4 is a semantic name.
dcl_texcoord3  o3.yz   // Different semantics can be packed into one register.
dcl_fog        o3.w
dcl_tangent    o4.xyz
dcl_position   o7.xyzw // position must be declared to some unique register
                       //   in a vertex shader, with all 4 components.

dcl_psize      o6      // Pointsize cannot have a mask
                       //   (that is, mask is full .xyzw)
                       // This is an implied scalar register.
                       // No other semantics can be assigned to any components
                       //   of this register.
                       // If pointsize declaration is not used (typical),
                       //   only 11 "out" registers are available, not 12.
                       // Pixel shaders cannot see this value.


def - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

def - vs

Defines vertex shader constants.

Syntax

def dst, float1, float2, float3, float4

where

  • dst is the destination register.
  • float1, float2, float3, float4 are four floating point numbers.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
def | x | x | x | x | x | x

The def instruction defines a shader constant whose value is loaded anytime a shader is set to a device. These are called immediate constants. Immediate constants take precedence over constants set by application programming interface (API) methods SetVertexShaderConstantF.

There are two ways to set a constant in a shader.

  1. Use def - vs to define the constant directly inside a shader.

    def - vs can only define floating-point constants.

  2. Use the API methods to set a constant.
    • Use IDirect3DDevice9::SetVertexShaderConstantF to set a floating-point constant.

Related Topics

  • defi
  • defb


defb - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

defb - vs

Defines a Boolean constant value, which should be loaded anytime a shader is set to a device.

Syntax

defb dest, booleanValue

where

  • dst is the destination register.
  • booleanValue is a boolean value, either True or False.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
defb |  | x | x | x | x | x

The defb - vs instruction defines a boolean shader constant whose value is loaded anytime a shader is set to a device. These are called immediate constants. Immediate constants take precedence over constants set by the application programming interface (API) method SetVertexShaderConstantB.

There are two ways to set a boolean constant in a shader.

  1. Use defb - vs to define the constant directly inside a shader.
  2. Use the API methods to set a constant.
    • Use IDirect3DDevice9::SetVertexShaderConstantB to set a Boolean constant.

Related Topics

  • def
  • defi


defi - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

defi - vs

Defines an integer constant value, which should be loaded anytime a shader is set to a device.

Syntax

defi dst, integerValue0, integerValue1, integerValue2, integerValue3
  • dst is the destination register.
  • integerValue# is a constant integer value.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
defi |  | x | x | x | x | x

The defi instruction defines an integer shader constant whose value is loaded anytime a shader is set to a device. These are called immediate constants. Immediate constants take precedence over constants set by the application programming interface (API) method SetVertexShaderConstantI.

There are two ways to set an integer constant in a shader.

  1. Use defi to define the integer constant vector directly inside a shader.
  2. Use the API methods to set a constant.
    • Use IDirect3DDevice9::SetVertexShaderConstantI to set an integer constant.

Related Topics

  • def
  • defb


dp3 - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

dp3 - vs

Computes the three-component dot product of the source registers.

Syntax

dp3 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dp3 | x | x | x | x | x | x

The following code fragment shows the operations performed:

dest.w = (src0.x * src1.x) + (src0.y * src1.y) + (src0.z * src1.z);
dest.x = dest.y = dest.z = dest.w;


dp4 - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

dp4 - vs

Computes the four-component dot product of the source registers.

Syntax

dp4 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dp4 | x | x | x | x | x | x

The following code fragment shows the operations performed:

dest.w = (src0.x * src1.x) + (src0.y * src1.y) +
         (src0.z * src1.z) + (src0.w * src1.w);
dest.x = dest.y = dest.z = dest.w;


dst - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

dst - vs

Calculates a distance vector.

Syntax

dst dest, src0, src1

where

  • dest is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dst | x | x | x | x | x | x

The following code fragment shows the operations performed:

dest.x = 1;
dest.y = src0.y * src1.y;
dest.z = src0.z;
dest.w = src1.w;

The first source operand (src0) is assumed to be the vector (ignored, d*d, d*d, ignored) and the second source operand (src1) is assumed to be the vector (ignored, 1/d, ignored, 1/d). The destination (dest) is the result vector (1, d, d*d, 1/d).


else - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

else - vs

Start of an else block.

Syntax

else

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
else |  | x | x | x | x | x

If the condition in the corresponding if bool statement is true, the code enclosed by the if bool statement and the matching endif is run. Otherwise, the code enclosed by the else...endif statements is run.

Related Topics

  • if bool
  • endif


endif - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

endif - vs

Marks the end of an if bool...else block.

Syntax

endif

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
endif |  | x | x | x | x | x

Related Topics

  • if bool
  • else


endloop - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

endloop - vs

End of a loop...endloop block.

Syntax

endloop

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
endloop |  | x | x | x | x | x

This instruction works as shown here.

LoopCounter += LoopStep;
LoopInterationCount = LoopIterationCount - 1;
if (LoopIterationCount > 0)
    Continue execution at the StartLoopOffset

endloop must follow the last instruction of a loop block.

Example

loop aL, i3
    add r1, r0, c2[ aL ]
endloop


endrep - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

endrep - vs

End a rep...endrep block.

Syntax

endrep

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
endrep |  | x | x | x | x | x

Example

rep i2
    add r0, r0, c0
endrep


exp - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

exp - vs

Provides full precision exponential 2x.

Syntax

exp dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified. See Source Register Swizzling.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
exp | x | x | x | x | x | x

This instruction provides at least 21 bits of precision.

The following code fragment shows the operations performed:

dest.x = dest.y = dest.z = dest.w = (float)pow(2, src.replicateSwizzleComponent);


expp - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

expp - vs

Provides partial precision exponential 2x.

Syntax

expp dst, src.{x|y|z|w}

Where:

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.
  • {x|y|z|w} is the required replicate swizzle on source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
expp | x | x | x | x | x | x

vs_1_1

The expp - vs instruction operates differently depending on vertex shader versions.

In vs_1_1, the expp instruction gives the following results:

v = the scalar value from the source register with a replicate swizzle

dest.x = pow(2, floor(v))
dest.y = v - floor(v)
dest.z = pow(2, v) (partial-precision)
dest.w = 1

In vs_2_0 and up, the expp instruction gives the following results:

v = the scalar value from the source register with a replicate swizzle

dest.x = dest.y = dest.z = dest.y = pow(2, v) (partial-precision)

vs_2_0

In vs_2_0 and up, the instruction works like this:

float V = the scalar value from the source register with a replicate swizzle

dest.x = dest.y = dest.z = dest.y = pow( 2, V ) (partial-precision)

The instruction provides at least 10 bits of precision.


frc - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

frc - vs

Returns the fractional portion of each input component.

Syntax

frc dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
frc | x | x | x | x | x | x

The following code fragment shows conceptually how the instruction operates.

dest.x = src.x - (float)floor(src.x);
dest.y = src.y - (float)floor(src.y);
dest.z = src.z - (float)floor(src.z);
dest.w = src.w - (float)floor(src.w);

The floor function converts the argument passed in to the greatest integer that is less than (or equal to) the argument. This is converted to a float and then subtracted fom the original value. The resulting fractional value ranges from 0.0 through 1.0.

For version 1_1, the allowable write masks are .y and .xy (.x is not allowed).


if bool - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

if bool - vs

Starts an if...else...endif block.

Syntax

if bool

where bool is a bool register number. See Constant Boolean Register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
if bool |  | x | x | x | x | x

If the source Boolean register in the if statement is true, the code enclosed by the if statement and the matching else is run. Otherwise, the code enclosed by the else...endif statements is run. This instruction consumes one instruction slot.

if blocks can be nested.

An if block cannot straddle a loop block.

Example

This instruction provides conditional static flow control.

defb b2, TRUE

...

if b2
// Instructions to run if b2 is nonzero

else
// Instructions to run otherwise

endif

Related Topics

  • else
  • endif


if_comp - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

if_comp - vs

Start an if bool...else...endif block, with a condition based on values that could be computed in a shader. This instruction is used to skip a block of code, based on a condition.

Syntax

if_comp src0, src1

Where:

  • _comp is a comparison between the two source registers. It can be one of the following:
    Syntax | Comparison
    _gt | Greater than
    _lt | Less than
    _ge | Greater than or equal
    _le | Less than or equal
    _eq | Equal to
    _ne | Not equal to
  • src0 is a source register. Replicate swizzle is required to select a component.
  • src1 is a source register. Replicate swizzle is required to select a component.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
if_comp |  |  | x | x | x | x

This instruction is used to skip a block of code, based on a condition.

if_lt src0, src1
   jump to the corresponding else or endif instruction;

Be careful using the equals and not equals comparison modes on floating point numbers. Because rounding occurs during during floating point calculations, the comparison can be done against an epsilon value (small nonzero number) to avoid errors.

Restrictions include:

  • if_comp...else...endif blocks (along with the predicated if blocks) can be nested up to 24 layers deep.
  • src0 and src1 registers require a replicate swizzle.
  • if_comp blocks must end with an else or endif instruction.
  • if_comp...else...endif blocks cannot straddle a loop block. The if_comp block must be completely inside, or outside the loop block.

Example

This instruction provides conditional dynamic flow control.

if_lt r3.x, r4.y
// Instructions to run if r3.x < r4.y

else
// Instructions to run otherwise

endif


if pred - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

if pred - vs

Start of an if pred - vs...else...endif block, with the condition taken from the content of the predicate register.

Syntax

if [!]pred.replicateSwizzle

Where:

  • [!] an optional NOT modifier. This modifies the value in the predicate register.
  • pred is the predicate register, p0. See Predicate Register.
  • replicateSwizzle is a single component that is copied (or replicated) to all four components (swizzled). Valid components are: x, y, z, w or r, g, b, a.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
if pred |  |  | x | x | x | x

This instruction is used to skip a block of code, based on a channel of the predicate register. Each if_pred block must end with an else or endif instruction.

Restrictions include:

if_pred blocks can be nested. This counts to the total dynamic nesting depth along with if_comp blocks.

An if_pred block cannot straddle a loop block, it should be either completely inside it or surround it.


label - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

label - vs

Mark the next instruction as having a label index.

Syntax

label l#

where # identifies the label number.

For vs_2_0, and vs_2_x, the label number must be between between 0 and 15.

For vs_2_sw, vs_3_0 and vs_3_sw, the label number must be between between 0 and 2047.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
label |  | x | x | x | x | x

This instruction defines a label located at the next shader instruction. The label instruction can only be present directly after a ret instruction (which defines the end of the previous subroutine or main program).


lit - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

lit - vs

Provides partial support for lighting by calculating lighting coefficients from two dot products and an exponent.

Syntax

lit dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
lit | x | x | x | x | x | x

The source vector is assumed to contain the values shown in the following pseudocode.

src.x = N*L        ; The dot product between normal and direction to light
src.y = N*H        ; The dot product between normal and half vector
src.z = ignored    ; This value is ignored
src.w = exponent   ; The value must be between -128.0 and 128.0

The following code fragment shows the operations performed.

dest.x = 1;
dest.y = 0;
dest.z = 0;
dest.w = 1;

float power = src.w;
const float MAXPOWER = 127.9961f;
if (power < -MAXPOWER)
    power = -MAXPOWER;          // Fits into 8.8 fixed point format
else if (power > MAXPOWER)
    power = -MAXPOWER;          // Fits into 8.8 fixed point format

if (src.x > 0)
{
    dest.y = src.x;
    if (src.y > 0)
    {
        // Allowed approximation is EXP(power * LOG(src.y))
        dest.z = (float)(pow(src.y, power));
    }
}

Reduced precision arithmetic is acceptable in evaluating the destination y component (dest.y). An implementation must support at least eight fraction bits in the power argument. Dot products are calculated with normalized vectors, and clamp limits are -128 to 128.

Error should correspond to a logp and expp combination, or no more than approximately one significant bit for an 8-bit color component.


log - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

log - vs

Full precision log2(x).

Syntax

log dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
log | x | x | x | x | x | x

The following code fragment shows the operations performed.

float v = abs(src);
if (v != 0)
{
    dest.x = dest.y = dest.z = dest.w =
        (float)(log(v)/log(2));
}
else
{
    dest.x = dest.y = dest.z = dest.w = -FLT_MAX;
}

This instruction accepts a scalar source whose sign bit is ignored. The result is replicated to all four channels.

This instruction provides 21 bits of precision.


logp - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

logp - vs

Partial precision logp2(x).

Syntax

logp dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
logp | x | x | x | x | x | x

The following code fragment shows the operations performed.

float f = abs(src);
if (f != 0)
    dest.x = dest.y = dest.z = dest.w = (float)(log(f)/log(2));
else
    dest.x = dest.y = dest.z = dest.w = -FLT_MAX;

This instruction provides logarithm base 2 partial precision, up to 10 bits.


loop - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

loop - vs

Start a loop...endloop block.

Syntax

loop aL, i#

Where:

  • aL is the Loop Counter Register holding the current loop count.
  • i# is a Constant Integer Register. See remarks.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
loop |  | x | x | x | x | x
  • The Loop Counter Register holds the current loop count, and can be used for relative addressing into Constant Integer Register (c#) or Output Registers (o#) inside the loop block.
  • i#.x specifies the iteration count. The legal range is [0, 255].
  • i#.y specifies the initial value of the Loop Counter Register register. The legal range is [0, 255].
  • i#.z specifies the step/stride size. The legal range is [-128, 127].
  • i#.w is not used and must be set to 0.
  • Loop blocks may be nested. See Flow Control Nesting Limits.
  • When nested, the value of the Loop Counter Register refers to the immediate enclosing loop block.
  • Loop blocks are allowed to be either completely inside an if* block or completely surrounding it. No straddling is allowed.

Example

loop aL, i3
    add r1, r0, c2[aL]
endloop


lrp - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

lrp - vs

Interpolates linearly between the second and third source registers by a proportion specified in the first source register.

Syntax

lrp dst, src0, src1, src2

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.
  • src2 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
lrp |  | x | x | x | x | x

This instruction performs the linear interpolation based on the following formula.

dest.x = src0.x * (src1.x - src2.x) + src2.x;
dest.y = src0.y * (src1.y - src2.y) + src2.y;
dest.z = src0.z * (src1.z - src2.z) + src2.z;
dest.w = src0.w * (src1.w - src2.w) + src2.w;

Related Topics

    © 2004 Microsoft Corporation. All rights reserved.
    Feedback? Please provide us with your comments on this topic.
    For more help, visit the DirectX Developer Center.


m3x2 - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

m3x2 - vs

Computes the product of a 3-component vector and a 2x3 matrix.

Syntax

m3x2 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register that represents a 2x3 matrix. This means it represents 2 constant registers.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m3x2 | x | x | x | x | x | x

The xy mask is required for the destination register. Negate and swizzle modifiers are allowed for src0 but not for src1.

The following equations show how the instruction operates:

dest.x = (src0.x * src1.x) + (src0.x * src1.y) + (src0.x * src1.z);
dest.y = (src0.x * src2.x) + (src0.y * src2.y) + (src0.z * src2.z);

The input vector is in register src0. The input 3x2 matrix is in register src1 and the next higher register in the same register file, as shown in the following expansion. A 2-D result is produced, leaving the other elements of the destination register (dest.z and dest.w) unaffected.

This operation is commonly used for 2-D transforms. This instruction is implemented as a pair of dot products as shown here.

m3x2   r0.xy, r1, c0   which will be expanded to:

dp3   r0.x, r1, c0
dp3   r0.y, r1, c1

Swizzle and negate modifiers are invalid for the src1 register. The dest and src0 register, or any of src1+i registers, cannot be the same.


m3x3 - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

m3x3 - vs

Computes the product of a 3-component vector and a 3x3 matrix.

Syntax

m3x3 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register that represents a 3x3 matrix. This means it represents 3 constant registers.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m3x3 | x | x | x | x | x | x

The xyz mask is required for the destination register. Negate and swizzle modifiers are allowed for src0 but not for src1.

The following code fragment shows the operations performed.

dest.x = (src0.x * src1.x) + (src0.y * src1.y) + (src0.z * src1.z);
dest.y = (src0.x * src2.x) + (src0.y * src2.y) + (src0.z * src2.z);
dest.z = (src0.x * src3.x) + (src0.y * src3.y) + (src0.z * src3.z);

The input vector is in register src0. The input 3x3 matrix is in register src1, and the next two higher registers, as shown in the expansion below. A 3-D result is produced, leaving the other element of the destination register (dest.w) unaffected.

This operation is commonly used for transforming normal vectors during lighting computations. This instruction is implemented as a pair of dot products as shown below.

m3x3 r0.xyz, r1, c0  which will be expanded to:

dp3   r0.x, r1, c0
dp3   r0.y, r1, c1
dp3   r0.z, r1, c2


m3x4 - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

m3x4 - vs

Computes the product of a 3-component vector and a 4x3 matrix.

Syntax

m3x4 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register, which corresponds to the first of four consecutive constant registers.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m3x4 | x | x | x | x | x | x

The xyzw (default) mask is required for the destination register. Negate and swizzle modifiers are allowed for src0 but not for src1.

The following code fragment shows the operations performed.

dest.x = (src0.x * src1.x) + (src0.y * src1.y) + (src0.z * src1.z);
dest.y = (src0.x * src2.x) + (src0.y * src2.y) + (src0.z * src2.z);
dest.z = (src0.x * src3.x) + (src0.y * src3.y) + (src0.z * src3.z);
dest.w = (src0.x * src4.x) + (src0.y * src4.y) + (src0.z * src4.z);

The input vector is in register src0. The input 3x4 matrix is in register src1 and the next three higher registers, as shown in the expansion below.

This operation is commonly used for transforming a position vector by a matrix that has a projective effect but applies no translation. This instruction is implemented as a pair of dot products as shown here.

m3x4   r0.xyzw, r1, c0   will be expanded to:

dp3 r0.x, r1, c0
dp3 r0.y, r1, c1
dp3 r0.z, r1, c2
dp3 r0.w, r1, c3


m4x3 - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

m4x3 - vs

Computes the product of a 4-component vector and a 3x4 matrix.

Syntax

m4x3 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register that represents a 3x4 matrix. This means it represents 4 constant registers.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m4x3 | x | x | x | x | x | x

The xyz mask is required for the destination register. Negate and swizzle modifiers are allowed for src0, but not for src1.

The following code fragment shows the operations performed.

dest.x = (src0.x * src1.x) + (src0.y * src1.y) + (src0.z * src1.z) +
    (src0.w * src1.w);
dest.y = (src0.x * src2.x) + (src0.y * src2.y) + (src0.z * src2.z) +
    (src0.w * src2.w);
dest.z = (src0.x * src3.x) + (src0.y * src3.y) + (src0.z * src3.z) +
    (src0.w * src3.w);

The input vector is in register src0. The input 4x3 matrix is in register src1, and the next two higher registers, as shown in the expansion below. A 3-D result is produced, leaving the other element of the destination register (dest.w) unaffected.

This operation is commonly used for transforming a position vector by a matrix that has no projective effect, such as occurs in model-space transformations. This instruction is implemented as a pair of dot products as shown below.

m4x3   r0.xyz, r1, c0    will be expanded to:

dp4   r0.x, r1, c0
dp4   r0.y, r1, c1
dp4   r0.z, r1, c2

Swizzle and negate modifiers are invalid for the src1 register. The dst and src0 register cannot be the same.


m4x4 - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

m4x4 - vs

Computes the product of a 4-component vector and a 4x4 matrix.

Syntax

m4x4 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register that represents a 4x4 matrix. This means it represents 4 constant registers.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m4x4 | x | x | x | x | x | x

The xyzw (default) mask is required for the destination register. Negate and swizzle modifiers are allowed for src0, but not for src1.

Swizzle and negate modifiers are invalid for the src0 register. The dest and src0 registers cannot be the same.

The following code fragment shows the operations performed.

dest.x = (src0.x * src1.x) + (src0.y * src1.y) + (src0.z * src1.z) +
        (src0.w * src1.w);
dest.y = (src0.x * src2.x) + (src0.y * src2.y) + (src0.z * src2.z) +
        (src0.w * src2.w);
dest.z = (src0.x * src3.x) + (src0.y * src3.y) + (src0.z * src3.z) +
        (src0.w * src3.w);
dest.w = (src0.x * src4.x) + (src0.y * src4.y) + (src0.z * src4.z) +
        (src0.w * src4.w);

The input vector is in register src0. The input 4x4 matrix is in register src1, and the next three higher registers, as shown in the expansion below.

This operation is commonly used for transforming a position by a projection matrix. This instruction is implemented as a series of dot products as shown here.

m4x4   r0.xyzw, r1, c0    will be expanded to:

dp4   r0.x, r1, c0
dp4   r0.y, r1, c1
dp4   r0.z, r1, c2
dp4   r0.w, r1, c3


mad - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

mad - vs

Multiplies and adds sources.

Syntax

mad dst, src0, src1, src2

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.
  • src2 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
mad | x | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x = src0.x * src1.x + src2.x;
dest.y = src0.y * src1.y + src2.y;
dest.z = src0.z * src1.z + src2.z;
dest.w = src0.w * src1.w + src2.w;


max - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

max - vs

Calculates the maximum of the sources.

Syntax

max dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
max | x | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x=(src0.x >= src1.x) ? src0.x : src1.x;
dest.y=(src0.y >= src1.y) ? src0.y : src1.y;
dest.z=(src0.z >= src1.z) ? src0.z : src1.z;
dest.w=(src0.w >= src1.w) ? src0.w : src1.w;


min - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

min - vs

Calculates the minimum of the sources.

Syntax

min dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
min | x | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x=(src0.x < src1.x) ? src0.x : src1.x;
dest.y=(src0.y < src1.y) ? src0.y : src1.y;
dest.z=(src0.z < src1.z) ? src0.z : src1.z;
dest.w=(src0.w < src1.w) ? src0.w : src1.w;


mov - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

mov - vs

Move floating-point data between registers.

Syntax

mov dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
mov | x | x | x | x | x | x

Can be used for floating point data. For version vs_1_1, it can also be used to write the address register. When used to update address registers, the values are converted from floating point using rounding to nearest.

The following code fragment shows the operations performed.

if(dest is an integer register)
{
    int intSrc = RoundToNearest(src.w);
    dest = intSrc;
}
else
{
    dest = src;
}


mova - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

mova - vs

Move data from a floating point register to the Address Register, a0.

Syntax

mova dst, src

where

  • dst must be the Address Register, a0.
  • src is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
mova |  | x | x | x | x | x

Moves floating point data to an integer register. The values are converted from floating point using rounding to nearest.

The address register is the only destination register allowed.

The following code fragment shows the operations performed.

if(dest is an integer register)
{
    int intSrc = RoundToNearest(src);
    dest = intSrc;
}
else
{
    dest = src;
}

For versions 2_x and above, the address register is a component vector. Therefore, any write mask is allowed.

mova a0.xz, r0


mul - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

mul - vs

Multiplies sources into the destination.

Syntax

mul dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
mul | x | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x = src0.x * src1.x;
dest.y = src0.y * src1.y;
dest.z = src0.z * src1.z;
dest.w = src0.w * src1.w;


nop - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

nop - vs

No operation is performed.

Syntax

nop

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
nop | x | x | x | x | x | x

This instruction performs a no-op, or no operation. The syntax for calling it is as follows:

nop


nrm - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

nrm - vs

Normalize a 3-D vector.

Syntax

nrm dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
nrm |  | x | x | x | x | x

This instruction works conceptually as shown here.

squareRootOfTheSum = (src0.x*src0.x + src0.y*src0.y + src0.z*src0.z)1/2;
dest.x = src0.x * (1 / squareRootOfTheSum);
dest.y = src0.y * (1 / squareRootOfTheSum);
dest.z = src0.z * (1 / squareRootOfTheSum);
dest.w = src0.w * (1 / squareRootOfTheSum);

The dest and src registers cannot be the same. The dest register must be a temporary register.

This instruction performs the linear interpolation based on the following formula.

float f = src0.x*src0.x + src0.y*src0.y + src0.z*src0.z;
if (f != 0)
    f = (float)(1/sqrt(f));
else
    f = FLT_MAX;

dest.x = src0.x*f;
dest.y = src0.y*f;
dest.z = src0.z*f;
dest.w = src0.w*f;


pow - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

pow - vs

Full precision abs(src0)src1.

Syntax

pow dst, src0, src1

where

  • dst is the destination register.
  • src0 is an input source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.
  • src1 is an input source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
pow |  | x | x | x | x | x

This instruction works as shown here.

dest = pow(abs(src0), src1);

This is a scalar instruction, therefore the source registers should have replicate swizzles to indicate which channels are used.

The scalar result is replicated to all four output channels.

This instruction could be expanded as exp(src1 * log(src0)).

Precision is not lower than 15 bits.

The dest register should be a temporary register, and should not be the same register as src1.


rcp - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

rcp - vs

Computes the reciprocal of the source scalar.

Syntax

rcp dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
rcp | x | x | x | x | x | x

The following code fragment shows the operations performed.

float f = src0;
if(f == 0.0f)
{
    f = FLT_MAX;
}
else
{
    if(f != 1.0)
    {
        f = 1/f;
    }
}

dest = f;

The output must be exactly 1.0 if the input is exactly 1.0. A source of 0.0 yields infinity.

Precision should be at least 1.0/(222) absolute error over the range (1.0, 2.0) because common implementations will separate mantissa and exponent.

If the source has no subscripts, the x-component is used.


rep - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

rep - vs

Start a rep...endrep block.

Syntax

rep i#

where i# is an integer register that specifies the repeat count in the .x component. See Constant Integer Register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
rep |  | x | x | x | x | x

  • i#.x specifies the iteration count. The legal range is [0, 255].
  • i#.yzw are not used by the repeat block.
  • Repeat blocks may be nested. See Flow Control Nesting Limits.
  • Repeat blocks are allowed to be either completely inside an if* block or completely surrounding it. No straddling is allowed.

Example

rep i2
    add r0, r0, c0
endrep


ret - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

ret - vs

Return from a subroutine or a main function.

Syntax

ret

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
ret |  | x | x | x | x | x

This instruction takes the address of an instruction from the return address stack and continues execution from it. In the case of the main function, this instruction stops shader execution.

The ret instruction consumes one vertex shader instruction slot.

If a shader contains no subroutines, using ret at the end of the main program is optional.

Multiple return statements are not permitted in the main program or in any subroutine, the first return statement is treated as the end of the main program or subroutine.


rsq - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

rsq - vs

Computes the reciprocal square root (positive only) of the source scalar.

Syntax

rsq dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
rsq | x | x | x | x | x | x

The following code fragment shows the operations performed.

float f = abs(src0);
if (f == 0)
    f = FLT_MAX
else
{
    if (f != 1.0)
        f = 1.0/(float)sqrt(f);
}

dest.z = dest.y = dest.z = dest.w = f;

The absolute value is taken before processing.

Precision should be at least 1.0/(222) absolute error over the range (1.0, 4.0) because common implementations will separate mantissa and exponent.

If source has no subscripts, the x-component is used. The output must be exactly 1.0 if the input is exactly 1.0. A source of 0.0 yields infinity.


setp_comp - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

setp_comp - vs

Set the predicate register.

Syntax

setp_comp dst, src0, src1

Where:

  • _comp is a per-channel comparison between the two source registers. It can be one of the following:
    Syntax | Comparison
    _gt | Greater than
    _lt | Less than
    _ge | Greater than or equal
    _le | Less than or equal
    _eq | Equal to
    _ne | Not equal to
  • dst is the Predicate Register register, p0.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
setp_comp |  |  | x | x | x | x

This instruction operates as:

per channel in destination write mask
{
  dst.channel = src0.channel cmp src1.channel
}

For each channel that can be written according to the destination write mask, save the boolean result of the comparison operation between the corresponding channels of src0 and src1 (after the source modifier swizzles have been resolved).

Source registers allow arbitrary component swizzles to be specified.

The destination register allows arbitrary write masks.

The dest register must be the predicate register.

Applying the Predicate Register

Once the predicate register has been initialized with setp, it can be used to control an instruction per component. Here's the syntax:

([!]p0[.swizzle]) instruction dest, srcReg, ...

Where:

  • [!] is an optional boolean NOT
  • p0 is the predicate register
  • [.swizzle] is an optional swizzle to apply to the contents of the predicate register before using it to mask the instruction. The available swizzles are: .xyzw (default when none specified), or any replicate swizzle: .x/.r, .y/.g, .z/.b or .a/.w.
  • instruction is any aritmetic, or texture instruction. This cannot be a static or dynamic flow control instruction.
  • dest, srcReg, ... are the registers required by the instruction

Assuming the predicate register has been set up with (true, true, false, false) component values, it can be applied to this instruction:

// given r0 = 0,0,1,1
// given r1 = 1,1,0,0
setp_le p0, r0, r1
(p0) add r2, r3, r4

to perform a 2 component add.

r2.x = r3.x + r4.x
r2.y = r3.y + r4.y

The x and y components of r2 will not be written since the predicate register contained false in components z and w.

Applying the predicate register to an arithmetic or texture instruction increases its instruction slot count by 1.

The predicate register can also be applied to if pred, callnz pred and breakp instructions. These flow control instructions do not have any increase in the instruction slot count when using the predicate register.


sge - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

sge - vs

Computes the sign if the first source is greater than or equal to the second source.

Syntax

sge dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
sge | x | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x = (src0.x >= src1.x) ? 1.0f : 0.0f;
dest.y = (src0.y >= src1.y) ? 1.0f : 0.0f;
dest.z = (src0.z >= src1.z) ? 1.0f : 0.0f;
dest.w = (src0.w >= src1.w) ? 1.0f : 0.0f;


sgn - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

sgn - vs

Computes the sign of the input.

Syntax

sgn dst, src0, src1, src2

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a temporary register that holds intermediate results. Following execution, contents are undefined.
  • src2 is a temporary register that holds intermediate results. Following execution, contents are undefined.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
sgn |  | x | x | x | x | x

This instruction works as shown below.

for each component in src0
{
   if (src0.component <  0)
       dest.component = -1;
   else
       if (src0.component == 0)
           dest.component = 0;
       else
           dest.component = 1;
}

src1 and src2 must be different Temporary Registers.


sincos - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

sincos - vs

Computes sine and cosine, in radians.

Syntax

vs_2_0 and vs_2_x

sincos dst.{x|y|xy}, src0.{x|y|z|w}, src1, src2

Where:

  • dst is the destination register and has to be a Temporary Register (r#). The destination register must have exactly one of the following three masks: .x | .y | .xy.
  • src0 is a source register that provides the input angle, which must be within [-pi, +pi]. {x|y|z|w} is the required replicate swizzle.
  • src1 and src2 are source registers and must be two different Constant Float Register (c#). The values of src1 and src2 must be that of the macros D3DSINCOSCONST1 and D3DSINCOSCONST2 respectively.

vs_3_0

sincos dst.{x|y|xy}, src0.{x|y|z|w}

Where:

  • dst is a destination register and has to be a Temporary Register (r#). The destination register must have exactly one of the following three masks: .x | .y | .xy.
  • src0 is a source register that provides the input angle, which must be within [-pi, +pi]. {x|y|z|w} is the required replicate swizzle.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
sincos |  | x | x | x | x | x

vs_2_0 and vs_2_x Remarks

For vs_2_0 and vs_2_x, sincos can be used with predication, but with one restriction to the swizzle of the Predicate Register (p0): only replicate swizzle (.x | .y | .z | .w) is allowed.

For vs_2_0 and vs_2_x, the instruction operates as follows: (V = the scalar value from src0 with a replicate swizzle):

  • If the write mask is .x:
    dest.x = cos( V )
dest.y is undefined when the instruction completes
dest.z is undefined when the instruction completes
dest.w is not touched by the instruction
  • If the write mask is .y:
    dest.x is undefined when the instruction completes
dest.y = sin( V )
dest.z is undefined when the instruction completes
dest.w is not touched by the instruction
  • If the write mask is .xy:
    dest.x = cos( V )
dest.y = sin( V )
dest.z is undefined when the instruction completes
dest.w is not touched by the instruction

vs_3_0 Remarks

For vs_3_0, sincos can be used with predication without any restriction. See Predicate Register.

For vs_3_0, the instruction operates as follows: (V = the scalar value from src0 with a replicate swizzle)

  • If the write mask is .x:
    dest.x = cos( V )
dest.y is not touched by the instruction
dest.z is not touched by the instruction
dest.w is not touched by the instruction
  • If the write mask is .y:
    dest.x is not touched by the instruction
dest.y = sin( V )
dest.z is not touched by the instruction
dest.w is not touched by the instruction
  • If the write mask is .xy:
    dest.x = cos( V )
dest.y = sin( V )
dest.z is not touched by the instruction
dest.w is not touched by the instruction

The application can map an arbitrary angle (in radians) to the range [-pi, +pi] using the following shader pseudocode:

def c0, pi, 0.5, 2*pi, 1/(2*pi)
mad r0.x, input_angle, c0.w, c0.y
frc r0.x, r0.x
mad r0.x, r0.x, c0.z, -c0.x


slt - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

slt - vs

Computes the sign if the first source is less than the second source.

Syntax

slt dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
slt | x | x | x | x | x | x

The following code fragment shows the operations performed.

dest.x = (src0.x < src1.x) ? 1.0f : 0.0f;
dest.y = (src0.y < src1.y) ? 1.0f : 0.0f;
dest.z = (src0.z < src1.z) ? 1.0f : 0.0f;
dest.w = (src0.w < src1.w) ? 1.0f : 0.0f;


sub - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

sub - vs

Subtracts sources.

Syntax

sub dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
sub | x | x | x | x | x | x

This instruction performs the subtraction shown in this formula.

dest.x = src0.x - src1.x
dest.y = src0.y - src1.y
dest.z = src0.z - src1.z
dest.w = src0.w - src1.w


texldl - vs
Microsoft DirectX 9.0 SDK Update (October 2004)

texldl - vs

Sample a texture with a particular sampler. The particular mipmap level of detail (LOD) being sampled has to be specified as the fourth component of the texture coordinate.

Syntax

texldl dst, src0, src1

Where:

  • dst is a destination register.
  • src0 is a source register that provides the texture coordinates for the texture sample.
  • src1 identifies the source sampler register (s#), where # specifies which texture sampler number to sample. The sampler has associated with it a texture and a control state defined by the D3DSAMPLERSTATETYPE enumeration (for example, D3DSAMP_MINFILTER).

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texldl |  |  |  |  | x | x

texldl looks up the texture set at the sampler stage referenced by src1. The LOD is selected from src0.w. This value can be negative, in which case the LOD selected is the "zeroth one" (biggest map) with the MAGFILTER. Because src0.w is a floating point value, the fractional value is used to interpolate (if MIPFILTER is LINEAR) between two mip levels. Sampler states MIPMAPLODBIAS and MAXMIPLEVEL are honored. For more information about sampler states, see D3DSAMPLERSTATETYPE.

If a shader program samples from a sampler that does not have a texture set, 0001 is obtained in the destination register.

This is an approximation to the reference device algorithm.

LOD = src0.w + LODBIAS;
if (LOD <= 0 )
{
   LOD = 0;
   Filter = MagFilter;
   tex = Lookup( MAX(MAXMIPLEVEL, LOD), Filter );
}
else
{
   Filter = MinFilter;
   LOD = MAX( MAXMIPLEVEL, LOD);
   tex = Lookup( Floor(LOD), Filter );
   if( MipFilter == LINEAR )
   {
      tex1 = Lookup( Ceil(LOD), Filter );
      tex = (1 - frac(src0.w))*tex + frac(src0.w)*tex1;
   }
}

Restrictions:

  • The texture coordinates should not be scaled by texture size.
  • dst must be a Temporary Register (r#).
  • dst can accept a write mask. See Destination Register Masking.
  • Defaults for missing components are either 0 or 1, and depend on the texture format.
  • src1 must be a Sampler (s#). src1 may not use a negate modifier. src1 may use swizzle, which is applied after sampling before the write mask is honored. The sampler must have been declared (using dcl_samplerType) at the beginning of the shader.
  • The number of coordinates required to perform the texture sample depends on how the sampler was declared. If it was declared as a cube, a three-component texture coordinate is required (.rgb). Validation enforces that coordinates provided to texldl are sufficient for the texture dimension declared for the sampler. However, it is not guaranteed that the application actually set a texture (through the application programming interface (API)) with dimensions equal to the dimension declared for the sampler. In such a case, the runtime will attempt to detect mismatches (possibly in debug only). Sampling a texture with fewer dimensions than are present in the texture coordinate will be allowed, and will be assumed to ignore the extra texture coordinate components. Conversely, sampling a texture with more dimensions than are present in the texture coordinate is not allowed.
  • If the src0 (texture coordinate) is a Temporary Register (r#), the components required for the lookup (described above) must have been previously written.
  • Sampling unsigned RGB textures will result in float values between 0.0 and 1.0.
  • Sampling signed textures will result in float values between -1.0 to 1.0.
  • When sampling floating point textures, Float16 means that the data will range within MAX_FLOAT16. Float32 means the maximum range of the pipeline will be used. Sampling outside of either range is undefined.
  • There is no dependent read limit.


vs
Microsoft DirectX 9.0 SDK Update (October 2004)

vs

This instruction specifies the shader version number. This instruction works on all shader versions.

Syntax

vs_mainVer_subVer

Input Arguments

Input arguments contain a single main version number with a single sub version number. The allowable combinations are listed in the table below.

Main versions | Sub versions
1 | 1
2 | 0, sw (software), x (extended)
3 | 0, sw (software)

Remarks

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
vs | x | x | x | x | x | x

This instruction must be the first non-comment instruction in a vertex shader.

This instruction is supported in all vertex shader versions.

Hardware accelerated versions of the software (versions without _sw in the version number), can process vertices with hardware accelearation or use software vertex processing. Software versions (versions with _sw in the version number) process vertices only with software.

Examples

This partial example declares a version 1_1 vertex shader.

vs_1_1

This partial example declares a version 2 software vertex shader.

vs_2_sw


Vertex Shader Registers
Microsoft DirectX 9.0 SDK Update (October 2004)

Vertex Shader Registers

  • Registers - vs_1_1
  • Registers - vs_2_0
  • Registers - vs_2_x
  • Registers - vs_3_0
  • Vertex Shader Register Modifiers


Vertex Shader Register Modifiers
Microsoft DirectX 9.0 SDK Update (October 2004)

Vertex Shader Register Modifiers

  • Vertex Shader Source Register Modifiers
  • Source Register Swizzling
  • Destination Register Masking


Vertex Shader Source Register Modifiers
Microsoft DirectX 9.0 SDK Update (October 2004)

Vertex Shader Source Register Modifiers

Source modifiers can be applied to modify the data read from a source register before the data is used by the instruction.

Negate

Negate the contents of the source register.

Component modifier | Description
- r | Source negation

The negate modifier cannot be used on second source register of these instructions: m3x2, m3x3, m3x4, m4x3, m4x4.

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
- | x | x | x | x | x | x

Absolute Value

Take the absolute value of the register.

Vertex shader versions | 1_1 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
abs |  |  |  |  | x | x

If any version 3 shader reads from one or more constant float registers (c#), one of the following must be true.

  • All of the constant floating-point registers must use the abs modifier.
  • None of the constant floating-point registers can use the abs modifier.


Source Register Swizzling
Microsoft DirectX 9.0 SDK Update (October 2004)

Source Register Swizzling

Before an instruction runs, the data in a source register is copied to a temporary register. Swizzling refers to the ability to copy any source register component to any temporary register component. Swizzling does not affect the source register data.

Component Swizzling

As shown in the following table, swizzling can be applied to the individual components of the source register data (where r is one of the valid vertex shader input Registers - vs_1_1).

Component modifier | Description
r.[xyzw][xyzw][xyzw][xyzw] | Source swizzle
  • All four components are always copied. If fewer than four components are specified, the last component is repeated (xy means .xyyy). If no components are specified, x is repeated (.xxxx).
  • The components can appear in any order. v0.ywx results in v0.wwxx.
  • The rgba components can be used respectively for xyzw (r for x, g for b, etc.).
  • These instructions implement source-register single component swizzles: exp, expp, log, logp, pow, rcp, rsq. The result of these instructions is copied to all four destination register components.

Swizzling cannot be used on the m3x2, m3x3, m4x3, and m4x4 instructions.


Destination Register Masking
Microsoft DirectX 9.0 SDK Update (October 2004)

Destination Register Masking

Masking specifies which components of the destination register will be updated with the result of an instruction. Texture registers have one set of rules and nontexture registers have another set of rules.

  • Destination_Register_Masking - This section contains rules for applying masks to destination registers.
  • Texture_Register_Masks - Texture registers have some unique rules.

Destination Register Masking

As shown in the following table, masking (where r is one of the valid vertex shader Registers) can be applied to the individual components of the vector data.

Component modifier | Description
r.{x}{y}{z}{w} | Destination mask
  • In general, specifying destination register write masks is good coding style. It makes code easier to read and maintain.
  • Any combination of components may be specified (including none) as long as x precedes y, y precedes z, and z precedes w.
  • The oPts and oFog output registers must use only one mask.
  • Certain instructions require the destination register to use a single write mask: exp, expp, log, logp, pow, rcp, and rsq.
  • In version 1.0, the frc instruction required one of the following mask combinations: .x or .y or .xy. Version 2.0 has no mask restriction.
  • sincos requires one of the following mask combinations: .x or .y or .xyz.
  • m3x2 requires the .xy write mask.
  • m3x3 and m4x3 require the .xyz write mask.
  • m3x4 and m4x4 require either the .xyz write mask or the default write mask (xyzw).

Texture Register Masks

The validation rules for using modifiers on texture coordinate registers are tighter than the validation rules for other registers.

  • If oTn is written, all previous registers (oTn-1 ~ oT0) have to be written as well.
  • The "combined" write mask for any oT# register must be exactly one of the following:
    • .x
    • .xy
    • .xyz
    • .xyzw (which is equivalent to not using any component modifiers)

For example, a vertex shader can output to texture registers in separate instructions.

    oT1.y
    oT0.y
    oT2
    oT0.xz
    oT1.x

Or, the instructions can be combined.

    oT0.xyz
    oT1.xy
    oT2.xyzw

These restrictions apply only to the texture coordinate registers.


Registers - vs_1_1
Microsoft DirectX 9.0 SDK Update (October 2004)

Registers - vs_1_1

This section contains reference information for the input and output registers implemented by vertex shader version 1_1.

Input Registers

Register | Name | Count | R/W | # Read ports | # Reads / inst | Dimension | RelAddr | Defaults | Requires DCL
a0 | Address Register | 1 | R/W | 1 | Unlimited | See note 3 | No | None | No
c# | Constant Float Register | See note 2 | R | 1 | Unlimited | 4 | a0.x | (0, 0, 0, 0) | No
v# | Input Register | 16 | R | 1 | Unlimited | 4 | No | See note 1 | Yes
r# | Temporary Register | 12 | R/W | 3 | Unlimited | 4 | No | None | No

Notes:

  1. Partial (0, 0, 0, 1) - If only a subset of channels are updated, the remaining channels will default to (0, 0, 0, 1).
  2. Equal to D3DCAPS9.MaxVertexShaderConst (at least 96 for vs_1_1).
  3. Only .x channel is available.

Output Registers

Register | Name | Count | R/W | Dimension | RelAddr | Defaults | Requires DCL
oPos | Position Register | 1 | W | 4 | No | None | No
oFog | Fog Register | 1 | W | 1 | No | None | No
oPts | Point Size Register | 1 | W | 1 | No | None | No
oD# | Color Register; See note 1 | 2 | W | 4 | No | None | No
oT# | Texture Coordinate Register | 8 | W | 4 | No | None | No

Notes:

  1. oD0 is the diffuse color output; oD1 is the specular color output.


Registers - vs_2_0
Microsoft DirectX 9.0 SDK Update (October 2004)

Registers - vs_2_0

This section contains reference information for the input and output registers implemented by vertex shader version 2_0.

Input Registers

Register | Name | Count | R/W | # Read ports | # Reads / inst | Dimension | RelAddr | Defaults | Requires DCL
v# | Input Register | 16 | R | 1 | Unlimited | 4 | No | See note 1 | Yes
r# | Temporary Register | 12 | R/W | 3 | Unlimited | 4 | No | None | No
c# | Constant Float Register | See note 2 | R | 1 | 2 | 4 | a0 / aL | (0, 0, 0, 0) | No
a0 | Address Register | 1 | R/W | 1 | 2 | 4 | No | None | No
b# | Constant Boolean Register | 16 | R | 1 | 1 | 1 | No | FALSE | No
i# | Constant Integer Register | 16 | R | 1 | 1 | 4 | No | (0, 0, 0, 0) | No
aL | Loop Counter Register | 1 | R | 1 | 2 | 1 | No | None | No

Notes:

  1. Partial (0, 0, 0, 1) - If only a subset of channels are updated, the remaining channels will default to (0, 0, 0, 1).
  2. Equal to D3DCAPS9.MaxVertexShaderConst (at least 256 for vs_2_0).

Output Registers

Register | Name | Count | R/W | Dimension | RelAddr | Defaults | Requires DCL
oPos | Position Register | 1 | W | 4 | No | None | No
oFog | Fog Register | 1 | W | 1 | No | None | No
oPts | Point Size Register | 1 | W | 1 | No | None | No
oD# | Color Register; See note 1 | 2 | W | 4 | No | None | No
oT# | Texture Coordinate Register | 8 | W | 4 | No | None | No

Notes:

  1. oD0 is the diffuse color output; oD1 is the specular color output.


Registers - vs_2_x
Microsoft DirectX 9.0 SDK Update (October 2004)

Registers - vs_2_x

This section contains reference information for the input and output registers implemented by vertex shader version 2_x.

Input Registers

Register | Name | Count | R/W | # Read ports | # Reads / inst | Dimension | RelAddr | Defaults | Requires DCL
v# | Input Register | 16 | R | 1 | Unlimited | 4 | No | See note 1 | Yes
r# | Temporary Register | See note 2 | R/W | 3 | Unlimited | 4 | No | None | No
c# | Constant Float Register | See note 3 | R | 1 | 2 | 4 | a0 / aL | (0, 0, 0, 0) | No
a0 | Address Register | 1 | R/W | 1 | 2 | 4 | No | None | No
b# | Constant Boolean Register | 16 | R | 1 | 1 | 1 | No | FALSE | No
i# | Constant Integer Register | 16 | R | 1 | 1 | 4 | No | (0, 0, 0, 0) | No
aL | Loop Counter Register | 1 | R | 1 | 2 | 1 | No | None | No
p0 | Predicate Register | 1 | R/W | 1 | 1 | 4 | No | None | No

Notes:

  1. Partial (0, 0, 0, 1) - If only a subset of channels are updated, the remaining channels will default to (0, 0, 0, 1).
  2. Equal to D3DCAPS9.VS20Caps.NumTemps (at least 12 for vs_2_x).
  3. Equal to D3DCAPS9.MaxVertexShaderConst (at least 256 for vs_2_x).

Output Registers

Register | Name | Count | R/W | Dimension | RelAddr | Defaults | Requires DCL
oPos | Position Register | 1 | W | 4 | No | None | No
oFog | Fog Register | 1 | W | 1 | No | None | No
oPts | Point Size Register | 1 | W | 1 | No | None | No
oD# | Color Register; See note 1 | 2 | W | 4 | No | None | No
oT# | Texture Coordinate Register | 8 | W | 4 | No | None | No

Notes:

  1. oD0 is the diffuse color output; oD1 is the specular color output.


Registers - vs_3_0
Microsoft DirectX 9.0 SDK Update (October 2004)

Registers - vs_3_0

This section contains reference information for the input and output registers implemented by vertex shader version 3_0.

Input Registers

Register | Name | Count | R/W | # Read ports | # Reads / inst | Dimension | RelAddr | Defaults | Requires DCL
v# | Input Register | 16 | R | 1 | Unlimited | 4 | No | See note 1 | Yes
r# | Temporary Register | 32 | R/W | 3 | Unlimited | 4 | No | None | No
c# | Constant Float Register | See note 2 | R | 1 | Unlimited | 4 | a0 / aL | (0, 0, 0, 0) | No
a0 | Address Register | 1 | R/W | 1 | Unlimited | 4 | No | None | No
b# | Constant Boolean Register | 16 | R | 1 | 1 | 1 | No | FALSE | No
i# | Constant Integer Register | 16 | R | 1 | 1 | 4 | No | (0, 0, 0, 0) | No
aL | Loop Counter Register | 1 | R | 1 | Unlimited | 1 | No | None | No
p0 | Predicate Register | 1 | R/W | 1 | 1 | 4 | no | none | no
s# | Sampler | 4 | R | 1 | 1 | 4 | No | See note 3 | Yes

Notes:

  1. Partial (0, 0, 0, 1) - If only a subset of channels are updated, the remaining channels will default to (0, 0, 0, 1).
  2. Equal to D3DCAPS9.MaxVertexShaderConst (at least 256 for vs_3_0).
  3. Defaults for sampler lookup exist, but values depend on texture format.

Output Registers

Output registers have been collapsed into 12 o# (output) registers. These can be used for anything the user wants to interpolate for the pixel shader: texture coordinates, colors, fog, etc.

Register | Name | Count | R/W | Dimension | RelAddr | Defaults | Requires DCL
o# | Output Register | 12 | W | 4 | aL | None | Yes


Relative Addressing
Microsoft DirectX 9.0 SDK Update (October 2004)

Relative Addressing

The [ ] syntax can be used only in register types that can be relatively addressed in certain shader models. The supported forms of [ ] syntax are listed as follows:

Where:

  • "R" denotes any register type that can be relatively addressed.
  • "A" denotes any register that can be used as an index to relatively address other registers.
  • n0 - ni, m0 - mj, and k are integers >= 0.
[ ] syntax | Effective index | Examples
R[ A + m0 + ... + mj ] | A + m0 + ... + mj | c[ a0.x + 3 + 7 ]
R[ k ] ( = Rk ) | k | c[ 10 ] ( = c10 )
R[ A ] | A | c[ a0.y ]
Rk[ n0 + ... + ni + A + m0 + ... + mj ] | A + k + n0 + ... + ni + m0 + ... + mj | c8[ 3 + 2 + a0.w + 5 + 6 + 1 ]
R[ n0 + ... + ni + A + m0 + ... + mj ] | A + n0 + ... + ni + m0 + ... + mj | c[ 2 + 1 + aL + 3 + 4 + 5 ]
Rk[ A ] | A + k | c12[ aL ], c0[ a0.z ]
Rk[ A + m0 + ... + mj ] | A + k + m0 + ... + mj | v1[ aL + 4 + 8 ]
R[ n0 + ... + ni + A ] | A + n0 + ... + ni | o[ 3 + 1 + aL ]
Rk[ n0 + ... + ni + A ] | A + k + n0 + ... + ni | o1[ 2 + 1 + 3 + aL ]

The registers are available in the following versions:

Register type | Vertex Shader Versions
a0 | All
aL | vs_2_0 and higher
cn | vs_1_1 and higher
on | vs_3_0


Address Register
Microsoft DirectX 9.0 SDK Update (October 2004)

Address Register

The a0 register is an address register. A single register is available in version vs_1_1. The address register, designated as a0.x in vs_1_1, can be used as a signed integer offset for relative addressing into the constant register file. For versions vs_2_0 and above, all four components (.x, .y, .z, .w) are available for relative addressing.

c[a0.x + n]

The address register cannot be read by a vertex shader, it can only be used for relative addressing of a constant register. Reading values outside of the legal range will return (0.0, 0.0, 0.0, 0.0). The address register can only be a destination for the mov instruction. If a floating-point number is moved into an integer register, a round-to-nearest conversion happens.

All shaders must initialize the address register before using it. For version vs_2_0 and above, the mova instruction can move a floating-point value to an address register.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Address Register | x | x | x | x | x | x


Constant Float Register
Microsoft DirectX 9.0 SDK Update (October 2004)

Constant Float Register

Vertex shader input register for a four component floating-point constant. Set a constant register with either def or IDirect3DDevice9::SetVertexShaderConstantF.

The constant register file is read-only from the perspective of the vertex shader. Any single instruction may access only one constant register. However, each source in that instruction may independently swizzle and negate that vector as it is read.

The behavior of shader constants has changed between Microsoft DirectX 8.0 and DirectX 9.0.

  • For DirectX 9.0, constants set with defx assign values to the shader constant space. The lifetime of a constant declared with defx is confined to the execution of that shader only. Conversely, constants set using the application programming interfaces (APIs)SetXXXShaderConstantX initialize constants in global space. Constants in global space are not copied to local space (visible to the shader) until SetxxxShaderConstants is called.
  • For DirectX 8.0, constants set with defx or the APIs both assign values to the shader constant space. Each time the shader is executed, the constants are used by the current shader regardless of the technique used to set them.

A constant register is designated as either absolute or relative:

c[n]           ; absolute
c[a0.x + n]    ; relative - supported only in version 1_1

The constant register can be read, therefore, either by using an absolute index or with a relative index from an address register. Reads from out-of-range registers return (0.0, 0.0, 0.0, 0.0).

Examples

Here is an example declaring two floating-point constants within a shader.

def c40, 0.0f,0.0f,0.0f,0.0f;

These constants are loaded every time IDirect3DDevice9::SetVertexShader is called.

Here is an example using the API.

    // Set up the vertex shader constants.
    {
        D3DXMATRIXA16 mat;
        D3DXMatrixMultiply( &mat, &m_matView, &m_matProj );
        D3DXMatrixTranspose( &mat, &mat );

        D3DXVECTOR4 vA( sinf(m_fTime)*15.0f, 0.0f, 0.5f, 1.0f );
        D3DXVECTOR4 vD( D3DX_PI, 1.0f/(2.0f*D3DX_PI), 2.0f*D3DX_PI, 0.05f );

        // Taylor series coefficients for sin and cos.
        D3DXVECTOR4 vSin( 1.0f, -1.0f/6.0f, 1.0f/120.0f, -1.0f/5040.0f );
        D3DXVECTOR4 vCos( 1.0f, -1.0f/2.0f, 1.0f/ 24.0f, -1.0f/ 720.0f );

        m_pd3dDevice->SetVertexShaderConstantF(  0, (float*)&mat,  4 );
        m_pd3dDevice->SetVertexShaderConstantF(  4, (float*)&vA,   1 );
        m_pd3dDevice->SetVertexShaderConstantF(  7, (float*)&vD,   1 );
        m_pd3dDevice->SetVertexShaderConstantF( 10, (float*)&vSin, 1 );
        m_pd3dDevice->SetVertexShaderConstantF( 11, (float*)&vCos, 1 );
    }

If you are setting constant values with the API, there is no shader declaration required.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Constant Register | x | x | x | x | x | x


Constant Integer Register
Microsoft DirectX 9.0 SDK Update (October 2004)

Constant Integer Register

Constant integer registers are used only by loop and rep.

They can be set using defi or IDirect3DDevice9::SetVertexShaderConstantI.

When used as an argument to the loop instruction:

  • .x is the iteration count. (rep uses only this component).
  • .y is the initial value for the loop counter.
  • .z is the increment step for the loop counter.

The behavior of shader constants has changed between Microsoft DirectX 8.0 and DirectX 9.0.

  • For DirectX 9.0, constants set with defx assign values to the shader constant space. The lifetime of a constant declared with defx is confined to the execution of that shader only. Conversely, constants set using the application programming interfaces (APIs)SetXXXShaderConstantX initialize constants in global space. Constants in global space are not copied to local space (visible to the shader) until SetxxxShaderConstants is called.
  • For DirectX 8.0, constants set with defx or the APIs both assign values to the shader constant space. Each time the shader is executed, the constants are used by the current shader regardless of the technique used to set them.


Constant Boolean Register
Microsoft DirectX 9.0 SDK Update (October 2004)

Constant Boolean Register

This register is a collection of bits used in static flow control instructions (for example, if bool - else - endif). There are 16 of them, therefore, a shader can have 16 independent branch conditions. They can be set using defb or IDirect3DDevice9::SetVertexShaderConstantI.

The behavior of shader constants has changed between Microsoft DirectX 8.0 and DirectX 9.0.

  • For DirectX 9.0, constants set with defx assign values to the shader constant space. The lifetime of a constant declared with defx is confined to the execution of that shader only. Conversely, constants set using the application programming interfaces (APIs)SetXXXShaderConstantX initialize constants in global space. Constants in global space are not copied to local space (visible to the shader) until SetxxxShaderConstants is called.
  • For DirectX 8.0, constants set with defx or the APIs both assign values to the shader constant space. Each time the shader is executed, the constants are used by the current shader regardless of the technique used to set them.


Color Register
Microsoft DirectX 9.0 SDK Update (October 2004)

Color Register

These vertex shader output registers contain a color value.

Register | Description
oD0 | diffuse color register.
oD1 | specular color register.

The oD0 value is interpolated and is written to the pixel shader color register 0 (v0). The oD1 value is interpolated and written to the pixel shader color register 1 (v1). For more information about pixel shader color registers, see the pixel shader Input Color Register page.

Syntax

Color Register

Remarks

Example

min oD0, r0, c1.x


Fog Register
Microsoft DirectX 9.0 SDK Update (October 2004)

Fog Register

This vertex shader output register contains a per-vertex fog color.

Syntax

Fog Register

Remarks

A register consists of properties that determine how each register behaves.

Property | Description
Name | oFog
Count | One vector, of which only one component can be used and must be specified by the component mask
I/O permissions | Write-only.

The output fog value registers. The value is the fog factor to be interpolated and then routed to the fog table. Only the scalar x-component of the fog is used.


Input Register
Microsoft DirectX 9.0 SDK Update (October 2004)

Input Register

Vertex shader input register.

Data from each vertex (using one or more input vertex streams) is loaded into the vertex input registers before the vertex shader is run. The input registers consist of 16 four-component floating-point vectors, designated as v0 through v15. These registers are read-only. An input register is bound to vertex data through a vertex declaration.

The following register properties control how each register behaves:

Property | Description
Name | v[n] - n is an optional register number. 0 is the default value used, if it is omitted.
Count | A maximum of 16 registers, v0 - v15.
I/O permissions | Read-only. This register cannot be written by the application programming interface (API) or within the shader.
Read ports | 1. This is the number of times a register can be read within a single instruction. See below.

Any single instruction can access only one vertex input register. However, each source in the instruction can independently swizzle and negate that vector as it is read.

Example

Here is an example using a vertex declaration to bind 2-D vertex position data to register v0.

The vertex declaration belongs in the application:

D3DVERTEXELEMENT9 decl[] =
{
    { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
      D3DDECL_END()
};

Here is the corresponding vertex shader declaration:

dcl_position v0

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Position Register | x | x | x | x | x | x


Loop Counter Register
Microsoft DirectX 9.0 SDK Update (October 2004)

Loop Counter Register

The only register in this bank is the current loop counter (aL) register. It automatically gets incremented in each execution of the loop...endloop block. So it can be used in the block for relative addressing if needed and is invalid to use it outside the loop.


Output Registers
Microsoft DirectX 9.0 SDK Update (October 2004)

Output Registers

  • Vertex Color Register - oD0, oD1
  • Fog Register - oFog
  • Position Register - oPos
  • Point Size Register - oPts
  • Texture Coordinate Register - oT0 to oT7

Register names are preceded by a lowercase o (oh), indicating that the output registers are write-only.

Vertex Color Register - oD0, oD1

oD0 is the diffuse color register. oD1 is the specular color register. The oD0 value is interpolated and is written to the input color register 0 (v0) of the pixel shader. The oD1 value is interpolated and written to the input color register 1 (v1) of the pixel shader. For more information about pixel shader color registers, see Registers.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Vertex Color Register | x | x | x | x | x | x

Fog Register - oFog

The output fog value registers. The value is the fog factor to be interpolated and then routed to the fog table. Only the scalar x-component of the fog is used. Values are clamped between zero and one before passing to the rasterizer.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Fog Register | x | x | x | x | x | x

Position Register - oPos

The output position registers. The value is the position in homogeneous clipping space. This value must be written by the vertex shader.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Position Register | x | x | x | x | x | x

Point Size Register - oPts

The output point-size registers. Only the scalar x-component of the point size is used.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Point Size Register | x | x | x | x | x | x

Texture Coordinate Register - oT0 to oT7

The output texture coordinates registers. Specifically, these are an array of output data registers that are iterated and used as texture coordinates by the texture sampling stages routing data to the pixel shader.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Texture Coordinate Register | x | x | x | x | x | x

When writing to a texture coordinate register, it is recommended to pass only as many floating point values as the dimension of the corresponding texture map. Control the values passed with a modifier. For example, use .xy for a 2-D texture map.

When texture projection is enabled for a texture stage, all four floating point values must be written to the corresponding texture register.

Any of the D3DTTFF* texture transform flags should be zero when the programmable pipeline is being used.

Texture Coordinate Range

Object vertex data supplies input texture coordinates. Objects that do not used tiled textures commonly have texture coordinates in the range [0,1]. Objects that use tiled textures, such as terrain, typically have texture coordinates that range from [-?,+?] where ? can be a large floating point number.

Texture coordinate interpolation is performed on vertex data for rasterization. During rasterization, texture coordinates are interpolated between object vertices, modified by texture wrapping and scaled by the texture size (also taking into account texture address mode) to produce an integer index. The index is then used to perform a texture lookup. MaxTextureRepeat can be used to determine how many times a texture can be tiled.

If texture coordinates are read directly into a pixel shader (using texcoord or texcrd), the texture coordinate range depends on the instruction and the pixel shader version.


Point Size Register
Microsoft DirectX 9.0 SDK Update (October 2004)

Point Size Register

This vertex shader output register contains per-vertex point size data.

Syntax

Point Size Register

Remarks

Remarks
Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Point Size Register | x | x | x | x | x | x

A register consists of properties that determine how each register behaves.

Property | Description
Name | oPts
Count | 1 vector, of which of only 1 component can be used and must be specified by the component mask.
I/O permissions | Write-only.

Only the scalar x-component of the point size is used.


Position Register
Microsoft DirectX 9.0 SDK Update (October 2004)

Position Register

This vertex shader output register contains per-vertex position data.

Syntax

Position Register

Remarks

Remarks
Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Position Register | x | x | x | x | x | x

A register consists of properties that determine how each register behaves.

Property | Description
Name | oPos
Count | 1 vector
I/O permissions | Write-only.

The value is the position in homogeneous clipping space. This value must be written by the vertex shader.

Example

dcl_position v0

def c40, 0.0f,0.0f,0.0f,0.0f;
// transform into projection space
m4x4 r0,v0,c8
max r0.z,c40.z,r0.z //clamp to 0
max r0.w,c12.x,r0.w //clamp to near clip plane
mov oPos,r0


Predicate Register
Microsoft DirectX 9.0 SDK Update (October 2004)

Predicate Register

This vertex shader output register contains a per-channel Boolean value.

Syntax

Predicate Register

Remarks

A predicate register is supported by the following versions.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
predicate register | x | x | x

Here are the register properties.

Register type | Count | R/W | # Read ports | # Reads/inst | Dimension | RelAddr | Defaults | Requires DCL
Predicate(p) | 1 | R/W | 1 | 1 | 4 | N/A | None | N

The predicate register can be modified with setp_comp. There are no default values for this register, an application needs to set the register before it is used.


Sampler
Microsoft DirectX 9.0 SDK Update (October 2004)

Sampler

A sampler is a input pseudo-register for a vertex shader, which is used to identify the sampling stage. There are four vertex shader samplers: s0 to s3. Four texture surfaces can be read in a single shader pass.

Samplers are pseudo registers because you cannot directly read or write to them.

A sampling unit corresponds to the texture sampling stage, encapsulating the sampling-specific state provided by IDirect3DDevice9::SetSamplerState. Each sampler uniquely identifies a single texture surface, which is set to the corresponding sampler using the IDirect3DDevice9::SetTexture. However, the same texture surface can be set at multiple samplers.

At draw time, a texture cannot be simultaneously set as a render target and a texture at a stage.

Because there are four samplers, up to four texture surfaces can be read from in a single shader pass. A sampler might appear as the only argument in the texture load instruction: texldl.

In vs_3_0, if a sampler is used, it needs to be declared at the beginning of the shader program using the dcl_samplerType instruction.

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Sampler |  |  |  |  | x | x

Related Topics

  • Vertex Textures in vs_3_0


Temporary Register
Microsoft DirectX 9.0 SDK Update (October 2004)

Temporary Register

A vertex shader temporary register is used to hold intermediate results.

A temporary register must be initialized before it is used. Each temporary register has single-write and triple-read access. This means that a single shader instruction can use as many as three temporary registers as inputs.

Values in a temporary register that remain from preceeding invocations of the vertex shader cannot be used.

A register consists of properties that determine how each register behaves.

Property | Description
Name | r[n]. n is an optional register number. The default is 0, and is the value used if no value is specified.
Count | A maximum of 12 registers.
I/O permissions | Read/write. This register can be read or written by the application programming interface (API) or by the shader.
Read ports | The number of times a register can be read within a single instruction is 3. A temporary register is the only register that can be read and written more than once in a single instruction.

Each temporary register has single-write and triple-read access. Therefore, an instruction can have as many as three temporary registers in its set of input source operands.

No values in a temporary register that remain from preceding invocations of the vertex shader can be used. Vertex shaders that read a value from a temporary register before writing to it will fail the Microsoft Direct3D API call to create the vertex shader.

Example

Here is an example using a temporary register:

def c4, 0,0,0,1
...
// Decompress position
mov r0.x, v0.x
mov r0.y, c4.w       // 1
mov r0.z, v0.y
mov r0.w, c4.w       // 1

// Compute theta from distance and time
mov r4.xz, r0        // xz

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Temporary Register | x | x | x | x | x | x


Texture Coordinate Register
Microsoft DirectX 9.0 SDK Update (October 2004)

Texture Coordinate Register

This vertex shader output register contains per-vertex texture coordinates.

A register consists of properties that determine how each register behaves.

Property | Description
Name | oT0 - oT7
Count | Eight vectors
I/O permissions | Write-only

The output texture coordinates registers are an array of output data registers. The register data is iterated and used as texture coordinates by the texture sampling stages to supply data to the pixel shader.

When writing to a texture coordinate register, it is recommended that you pass only as many floating point values as the dimension of the corresponding texture map. Control the values that are passed with a modifier. For example, use .xy for a 2-D texture map.

The fixed function vertex pipeline flags, D3DTEXTURETRANSFORMFLAGS (D3DTTFF_COUNT1, D3DTTFF_COUNT2, D3DTTFF_COUNT3, D3DTTFF_COUNT4), should be set to zero if you are using a programmable vertex shader.

Object vertex data supplies input texture coordinates. Objects that do not use tiled textures commonly have texture coordinates in the range [0,1]. Objects that use tiled textures, such as terrain, typically have texture coordinates that range from [-n,+n] where n can be any floating point number.

Texture coordinate interpolation is performed on vertex data for rasterization. During rasterization, texture coordinates are interpolated between object vertices, modified by texture wrapping, and scaled by the texture size (also taking into account texture addressing modes) to produce an integer index. The index is then used to perform a texture lookup. Use the MaxTextureRepeat value in D3DCAPS9 to determine how many times a texture can be tiled.

Example

Declare the texture coordinate register.

dcl_texcoord v7

Copy the per-vertex texture coordinates to the output register.

mov oT0, v7

Vertex shader versions | 1_1 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Texture Coordinate Register | x | x | x | x | x | x


Pixel Shaders
Microsoft DirectX 9.0 SDK Update (October 2004)

Pixel Shaders

  • ps_1_1, ps_1_2, ps_1_3, ps_1_4
  • ps_2_0
  • ps_2_x
  • ps_3_0
  • Registers
  • Pixel Shader Instructions
  • Pixel Shader Differences


ps_1_1, ps_1_2, ps_1_3, ps_1_4
Microsoft DirectX 9.0 SDK Update (October 2004)

ps_1_1, ps_1_2, ps_1_3, ps_1_4

The pixel shader assembler is made up of a set of instructions that operate on pixel data contained in registers. Operations are expressed as instructions comprised of an operator and one or more operands. Instructions use registers to transfer data in and out of the pixel shader arithmetic logic unit (ALU). Registers can also be used by some instructions to hold temporary results.

Instructions

There are two main categories of pixel shader instructions: arithmetic instructions and texture addressing instructions. Arithmetic instructions modify color data. Texture addressing operations process texture coordinate data and in most cases, sample a texture. Pixel shader instructions are run on a per-pixel basis; that is, they have no knowledge of other pixels in the pipeline.

Texture addressing instructions each consume one slot, but arithmetic instructions can be paired to enable both color components (RGB) and an alpha component instruction in a single slot.

ps_1_1, ps_1_2, ps_1_3, ps_1_4 Instructions contains a list of the available instructions.

When multisampling is enabled, pixel shaders only get run once per pixel, not once for every subpixel. Multisampling only increases the resolution of polygon edges, as well as depth and stencil tests. For example, if 3x3 multisampling is enabled, and a triangle being rasterized is found to cover five of the nine subpixels for a particular pixel, the pixel shader gets run once and the same color result is applied to all five subpixels.

Registers

ps_1_X Registers lists the different registers used by the shader ALU.

Modifiers

Modifiers for ps_1_X can be used to change the functionality of an instruction, or the data read from or written to a register.

Microsoft DirectX 9.0 requires intermediate computations to maintain at least 8-bit precision for all surface formats. Both higher precision (12-bit) for in-stage math, and saturation to 8-bits between texture stages are recommended. No modifiable rounding modes or exceptions are supported. Multiplication should be supported with a round-to-nearest precision to keep precision loss to a minimum.

Sampler Count

The number of texture samplers available is:

  • For ps_1_0 - ps_1_3, the maximum is 4.
  • For ps_1_4, the maximum is 6.


ps_2_0
Microsoft DirectX 9.0 SDK Update (October 2004)

ps_2_0

A programmable pixel shader is made up of a set of instructions that operate on pixel data. Registers transfer data in and out of the arithmetic logic unit (ALU). Additional control can be applied to modify the instruction, the results, or what data gets written out.

  • ps_2_0 Instructions contains a list of the available instructions.
  • ps_2_0 Registers lists the different types of registers used by the vertex shader ALU.
  • Modifiers are used to modify the way an instruction works.
  • Destination Register Write Mask determines what components of the destination register get written.
  • Pixel Shader Source Register Modifiers alter the source register data before the instruction runs.
  • Source Register Swizzling gives additional control over which register components are read, copied, or written.

Instruction Count

Shaders have restrictions for maximum instuction counts. Total Instruction slots: 96 (64 arithmetic and 32 texture).

Sampler Count

The number of texture samplers available is 16.


ps_2_x
Microsoft DirectX 9.0 SDK Update (October 2004)

ps_2_x

A programmable pixel shader is made up of a set of instructions that operate on pixel data. Registers transfer data in and out of the arithmetic logic unit (ALU). Additional control can be applied to modify the instruction, the results, or what data gets written out.

  • ps_2_x Instructions contains a list of the available instructions.
  • ps_2_x Registers lists the different types of registers used by the vertex shader ALU.
  • Modifiers are used to modify the way an instruction works.
  • Destination Register Write Mask determines what components of the destination register get written.
  • Pixel Shader Source Register Modifiers alter the source register data before the instruction runs.
  • Source Register Swizzling gives additional control over which register components are read, copied, or written.

Dynamic Flow Control

StaticFlowControlDepth represents the nesting depth of dynamic flow control instructions: if, if_comp, if_pred, break, and break_comp. The value is equal to the nesting depth of the if_comp block. The range of values for this cap is 0 to 24. If this cap is zero, the device does not support dynamic flow control instructions.

Number of Temporary Registers

The number of temporary registers supported by the device. The range is from 12 to 32.

Static Flow Control Nesting Depth

StaticFlowControlDepth represents the nesting depth of two types of static flow control instructions: loop/rep and call/callnz. The range of values for this cap is 1 to 4. loop/rep instructions can be nested up to StaticFlowControlDepth deep. Independently, call/callnz instructions can be nested up to StaticFlowControlDepth deep.

Number of Instruction Slots

The number of instruction slots can range from 96 to a maximum of 512, and is specified by the MaxPixelShaderInstructionSlots. The total number of instructions that can run is defined by MaxPixelShaderInstructionsExecuted. This can be larger than the number of instruction slots due to looping and subroutine calls.

Arbitrary Swizzle

If D3DPS20CAPS_ARBITRARYSWIZZLE is set, arbitrary swizzle is supported. See Source Register Swizzling.

Gradient Instructions

If D3DPS20CAPS_GRADIENTINSTRUCTIONS is set, gradient instructions are supported. See dsx, dsy, and texldd.

Predication

If D3DPS20CAPS_PREDICATION is set, instruction predication is supported. See Predicate Register.

Dependent Read Limit

If D3DPS20CAPS_NODEPENDENTREADLIMIT is set, there are no dependent read limits.

Texture Instruction Limit

If D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT is set, there is no limit on texture instructions.

Sampler Count

The number of texture samplers available is 16.


ps_3_0
Microsoft DirectX 9.0 SDK Update (October 2004)

ps_3_0

A programmable pixel shader is made up of a set of instructions that operate on pixel data. Registers transfer data in and out of the arithmetic logic unit (ALU). Additional control can be applied to modify the instruction, the results, or what data gets written out.

  • ps_3_0 Instructions contains a list of the available instructions.
  • ps_3_0 Registers lists the different types of registers used by the vertex shader ALU.
  • Modifiers are used to modify the way an instruction works.
  • Destination Register Write Mask determines what components of the destination register get written.
  • Pixel Shader Source Register Modifiers alter the source register data before the instruction runs.
  • Source Register Swizzling gives additional control over which register components are read, copied, or written.

New Features

Add a face register. Add a position register. Color registers (v#) are now fully floating point and the texture coordinate registers (t#) have been consolidated. Input declarations take the usage names, and multiple usages are permitted for components of a given register.

Dynamic Flow Control

The device supports dynamic flow control (if bool, break, and break_comp). The depth of nesting ranges from 0 to 24.

Number of Temporary Registers

The number of temporary registers supported is 32.

Static Flow Control Nesting Depth

The call/callnz/call_pred can be nested to a maximum depth of 4. Independently, loop/rep instructions can be nested to a maximum depth of 4.

Arbitrary Swizzle

Arbitrary swizzle is supported. See Source Register Swizzling.

Gradient Instructions

Gradient instructions are supported. See dsx, dsy, and texldd.

Predication

Instruction predication is supported. See Predicate Register.

Dependent Read Limit

There are no dependent read limits.

Texture Instruction Limit

There is no limit on texture instructions.

Instruction Count

Each pixel shader is allowed anywhere from 512 up to the number of slots in MaxPixelShader30InstructionSlots (not more than 32768). The number of instructions run can be much higher because of the looping support. The in MaxPShaderInstructionsExecuted should be at least 2^16.

Sampler Count

The number of texture samplers available is 16.

Device Caps

If pixel s 3_0 is supported, the following caps are supported in hardware (at a minimum):

Cap | Capability
MaxTextureWidth, MaxTextureHeight | 4K each
MaxTextureRepeat | 8K
MaxAnisotropy | 16
PixelShaderVersion | 3_0
MaxPixelShader30InstructionSlots | 512
The following primitive caps are set:
  • D3DPMISCCAPS_MASKZ
  • All the cull modes: D3DPMISCCAPS_CULLNONE, D3DPMISCCAPS_CULLCW, D3DPMISCCAPS_MASKZ.
  • D3DPMISCCAPS_CULLCCW
  • D3DPMISCCAPS_CLIPPLANESCALEDPOINTS
  • D3DPMISCCAPS_CLIPTLVERTS
  • D3DPMISCCAPS_BLENDOP
  • D3DPMISCCAPS_FOGINFVF
The following raster caps are set:
  • RasterCaps
  • RasterCaps
  • RasterCaps
  • RasterCaps
Full support for depth bias including:
  • RasterCaps
  • RasterCaps
Full set of comparisons for depth and alpha test including:
  • ZCmpCaps
  • ZCmpCaps
  • ZCmpCaps
  • ZCmpCaps
  • ZCmpCaps
  • ZCmpCaps
  • ZCmpCaps
  • ZCmpCaps
Source blending modes | All blending modes are supported as a source (except SrcBlendCaps, SrcBlendCaps, and SrcBlendCaps).
The following texture caps are supported:
  • D3DPTEXTURECAPS_PERSPECTIVE
  • D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE
  • D3DPTEXTURECAPS_PROJECTED
  • D3DPTEXTURECAPS_CUBEMAP
  • D3DPTEXTURECAPS_VOLUMEMAP
  • D3DPTEXTURECAPS_MIPMAP
  • D3DPTEXTURECAPS_MIPVOLUMEMAP
  • D3DPTEXTURECAPS_MIPCUBEMAP
The following are supported on texture filter caps, volume texture filter caps and cube texture filter caps:
  • D3DPTFILTERCAPS_MINFPOINT
  • D3DPTFILTERCAPS_MINFLINEAR
  • D3DPTFILTERCAPS_MINFANISOTROPIC: This is not required for VolumeTextureFilterCaps and CubeTextureFilterCaps.
  • D3DPTFILTERCAPS_MIPFPOINT
  • D3DPTFILTERCAPS_MIPFLINEAR
  • D3DPTFILTERCAPS_MAGFPOINT
  • D3DPTFILTERCAPS_MAGFLINEAR
The following texture address modes are supported at vertex and pixel stages:
  • TextureAddressCaps
  • TextureAddressCaps
  • TextureAddressCaps
  • TextureAddressCaps
  • TextureAddressCaps
  • TextureAddressCaps
All the pixel shader caps are supported.
  • DynamicFlowControlDepth is 24
  • NumTemps is 32
  • StaticFlowControlDepth is 4
  • NumInstructionSlots is 512
  • Predication is supported.
  • Arbitrary swizzles are supported.
  • Gradient instructions.
  • No dependent read limit.
  • No limit on the mix of tex and math instructions.
All the stencil operations are supported.
  • D3DSTENCILOP_KEEP
  • D3DSTENCILOP_ZERO
  • D3DSTENCILOP_REPLACE
  • D3DSTENCILOP_INCRSAT
  • D3DSTENCILOP_DECRSAT
  • D3DSTENCILOP_INVERT
  • D3DSTENCILOP_INCR
  • D3DSTENCILOP_DECR
Two sided stencil is supported | D3DSTENCILCAPS_TWOSIDED
Device support point size per vertex | FVFCaps
Non-power of 2 texture support. | Either full support or conditional non-pow-2 support. Device should not have the square texture only limitation: TextureCaps.
If the device supports multiple rendertargets, the following caps are supported:
  • D3DPMISCCAPS_INDEPENDENTWRITEMASKS
  • D3DPMISCCAPS_MRTPOSTPIXELSHADERBLENDING
If vs_3_0 is supported | MaxUserClipPlanes is 6


Pixel Shader Differences
Microsoft DirectX 9.0 SDK Update (October 2004)

Pixel Shader Differences

Instruction Slots

Each version supports a different number of maximum instruction slots.

Version | Maximum number of instruction slots
ps_1_1 | 4 texture + 8 arithmetic
ps_1_2 | 4 texture + 8 arithmetic
ps_1_3 | 4 texture + 8 arithmetic
ps_1_4 | 6 texture + 8 arithmetic per phase
ps_2_0 | 32 texture + 64 arithmetic
ps_2_x | 96 minimum, and up to the number of slots in D3DCAPS9.PS20Caps.NumInstructionSlots. See PS20Caps.
ps_3_0 | 512 minimum, and up to the number of slots in D3DCAPS9.MaxPixelShader30InstructionSlots. See PS20Caps.

For information about the limitations of software shaders, see Software Shaders.

Flow Control Nesting Limits

  • See Flow Control Limitations.

ps_1_x Features

New instructions:

See ps_1_1, ps_1_2, ps_1_3, ps_1_4 Instructions.

New registers:

See ps_1_X Registers.

ps_2_0 Features

New features:

  • Three new swizzles - .yzxw, .zxyw, .wzyx
  • Number of Temporary Registers (r#) increased to 12
  • Number of Constant Float Registers (c#) increased to 32
  • Number of Texture Coordinate Registers (t#) increased to 8

New instructions:

  • Setup instructions - dcl, dcl_samplerType
  • Arithmetic instructions - abs, crs, dp2add, exp, frc, log, m3x2, m3x3, m3x4, m4x3, m4x4, max, min, nrm, pow, rcp, rsq, sincos
  • Texture instructions - texld (different syntax), texldb, texldp

New registers:

  • Sampler (s#)

ps_2_x Features

New features (See PS20Caps.):

  • Dynamic flow control
  • Static flow control
  • Nesting for dynamic and static flow control instructions
  • Number of Temporary Registers (r#) increased
  • Arbitrary source swizzle
  • Gradient instructions
  • Predication
  • No dependent texture read limit
  • No texture instruction limit

New instructions:

  • Static flow control instructions - if bool, call, callnz bool, else, endif, rep, endrep, label, ret
  • Dynamic flow control instructions - break, break_comp, breakp, callnz pred, if_comp, if pred, setp_comp - ps
  • Arithmetic instructions - dsx, dsy
  • Texture instruction - texldd

New registers:

  • Predicate Register (p0)

ps_3_0 Features

New features:

  • Consolidated 10 Input Registers (v#)
  • Indexable Constant Float Registers (c#) with the Loop Counter Register (aL)
  • Number of Temporary Registers (r#) increased to 32
  • Number of Constant Float Registers (c#) increased to 224

New instructions:

  • Setup instruction - dcl_usage
  • Static flow instructions - loop, endloop
  • Arithmetic instruction - sincos (new syntax)
  • Texture instruction - texldl

New registers:

  • Input Register (v#)
  • Position Register (vPos)
  • Face Register (vFace)


Pixel Shader Instructions
Microsoft DirectX 9.0 SDK Update (October 2004)

Pixel Shader Instructions

  • ps_1_1, ps_1_2, ps_1_3, ps_1_4 Instructions
  • ps_2_0 Instructions
  • ps_2_x Instructions
  • ps_3_0 Instructions
  • Modifiers for ps_1_X
  • Flow Control Limitations


ps_1_1, ps_1_2, ps_1_3, ps_1_4 Instructions
Microsoft DirectX 9.0 SDK Update (October 2004)

ps_1_1, ps_1_2, ps_1_3, ps_1_4 Instructions

This section contains reference information for the pixel shader version 1_X instructions.

There are several types of pixel shader instructions, as shown in the following table.

Instruction Set

Version |  | Instruction slots | 1_1 | 1_2 | 1_3 | 1_4
ps | Version number | 0 | x | x | x | x
Constant instructions |  |  | 1_1 | 1_2 | 1_3 | 1_4
def | Define constants | 0 | x | x | x | x
Phase instructions |  |  | 1_1 | 1_2 | 1_3 | 1_4
phase | Transition between phase 1 and phase 2 | 0 |  |  |  | x
Arithmetic instructions |  |  | 1_1 | 1_2 | 1_3 | 1_4
add | Add two vectors | 1 | x | x | x | x
bem | Apply a fake bump environment-map transform | 2 |  |  |  | x
cmp | Compare source to 0 | 11 |  | x | x | x
cnd | Compare source to 0.5 | 1 | x | x | x | x
dp3 | Three-component dot product | 1 | x | x | x | x
dp4 | Four-component dot product | 11 |  | x | x | x
lrp | Linear interpolate | 1 | x | x | x | x
mad | Multiply and add | 1 | x | x | x | x
mov | Move | 1 | x | x | x | x
mul | Multiply | 1 | x | x | x | x
nop | No operation | 0 | x | x | x | x
sub | Subtract | 1 | x | x | x | x
Texture instructions |  |  | 1_1 | 1_2 | 1_3 | 1_4
tex | Sample a texture | 1 | x | x | x |
texbem | Apply a fake bump environment-map transform | 1 | x | x | x |
texbeml | Apply a fake bump environment-map transform with luminance correction | 1+12 | x | x | x |
texcoord | Interpret texture coordinate data as color data | 1 | x | x | x |
texcrd | Copy texture coordinate data as color data | 1 |  |  |  | x
texdepth | Calculate depth values | 1 |  |  |  | x
texdp3 | Three-component dot product between texture data and the texture coordinates | 1 |  | x | x |
texdp3tex | Three-component dot product and 1-D texture lookup | 1 |  | x | x |
texkill | Cancels rendering of pixels based on a comparison | 1 | x | x | x | x
texld | Sample a texture | 1 |  |  |  | x
texm3x2depth | Calculate per-pixel depth values | 1 |  |  | x |
texm3x2pad | First row matrix multiply of a two-row matrix multiply | 1 | x | x | x |
texm3x2tex | Final row matrix multiply of a two-row matrix multiply | 1 | x | x | x |
texm3x3 | 3x3 matrix multiply | 1 |  | x | x |
texm3x3pad | First or second row multiply of a three-row matrix multiply | 1 | x | x | x |
texm3x3spec | Final row multiply of a three-row matrix multiply | 1 | x | x | x |
texm3x3tex | Texture look up using a 3x3 matrix multiply | 1 | x | x | x |
texm3x3vspec | Texture look up using a 3x3 matrix multiply, with non-constant eye-ray vector | 1 | x | x | x |
texreg2ar | Sample a texture using the alpha and red components | 1 | x | x | x |
texreg2gb | Sample a texture using the green and blue components | 1 | x | x | x |
texreg2rgb | Sample a texture using the red, green and blue components | 1 |  | x | x |
  1. 1 slot in ps_1_4; 2 slots in ps_1_2 and ps_1_3
  2. 1 + 1 = 1 arithmetic instruction + 1 texture instruction


ps_2_0 Instructions
Microsoft DirectX 9.0 SDK Update (October 2004)

ps_2_0 Instructions

This section contains reference information for the pixel shader version 2_0 instructions.

There are several types of pixel shader instructions, as shown in the table. Columns to the right mean the following:

  • Instruction slots - Number of instruction slots used by each instruction.
  • Setup - A pixel shader must have a version instruction and it must be the first instruction.
  • Arithmetic - These instructions provide the mathematical operations in a shader.
  • Texture - These instructions are used to load and sample texture data, and to modify texture coordinates.
  • New - These instructions are new to this version.

Instruction Set

Name | Description | Instruction slots | Setup | Arithmetic | Texture | New
abs | Absolute value | 1 |  | x |  | x
add | Add two vectors | 1 |  | x |  |
cmp | Compare source to 0 | 1 |  | x |  |
crs | Cross product | 2 |  | x |  | x
dcl_samplerType | Declare the texture dimension for a sampler | 0 | x |  |  | x
dcl | Declare the association between vertex shader output registers and pixel shader input registers. | 0 | x |  |  | x
def | Define constants | 0 | x |  |  |
dp2add | 2-D dot product and add | 2 |  | x |  | x
dp3 | 3-D dot product | 1 |  | x |  |
dp4 | 4-D dot product | 1 |  | x |  |
exp | Full precision 2x | 1 |  | x |  | x
frc | Fractional component | 1 |  | x |  | x
log | Full precision log2(x) | 1 |  | x |  | x
lrp | Linear interpolate | 2 |  | x |  |
m3x2 | 3x2 multiply | 2 |  | x |  | x
m3x3 | 3x3 multiply | 3 |  | x |  | x
m3x4 | 3x4 multiply | 4 |  | x |  | x
m4x3 | 4x3 multiply | 3 |  | x |  | x
m4x4 | 4x4 multiply | 4 |  | x |  | x
mad | Multiply and add | 1 |  | x |  |
max | Maximum | 1 |  | x |  | x
min | Minimum | 1 |  | x |  | x
mov | Move | 1 |  | x |  |
mul | Multiply | 1 |  | x |  |
nop | No operation | 1 |  | x |  |
nrm | Normalize | 3 |  | x |  | x
pow | xy | 3 |  | x |  | x
ps | Version | 0 | x |  |  |
rcp | Reciprocal | 1 |  | x |  | x
rsq | Reciprocal square root | 1 |  | x |  | x
sincos | Sine and cosine | 8 |  | x |  | x
sub | Subtract | 1 |  | x |  |
texkill | Kill pixel render | 1 |  |  | x |
texld | Sample a texture | 1 |  |  | x | x
texldb | Texture sampling with level of detail (LOD) bias from w-component | 1 |  |  | x | x
texldp | Texture sampling with projective divide by w-component | 1 |  |  | x | x


ps_2_x Instructions
Microsoft DirectX 9.0 SDK Update (October 2004)

ps_2_x Instructions

This section contains reference information for the pixel shader version 2_x instructions.

There are several types of pixel shader instructions, as shown in the table. Columns to the right mean the following:

  • Instruction slots - Number of instruction slots used by each instruction.
  • Setup - A pixel shader must have a version instruction and it must be the first instruction.
  • Arithmetic - These instructions provide the mathematical operations in a shader.
  • Texture - These instructions are used to load and sample texture data, and to modify texture coordinates.
  • Flow control - These instructions provide static and dynamic flow control to the execution of instructions.
  • New - These instructions are new to this version.

Instruction Set

Name | Description | Instruction slots | Setup | Arithmetic | Texture | Flow control | New
abs | Absolute value | 1 |  | x |  |  |
add | Add two vectors | 1 |  | x |  |  |
break | Break out of a rep...endrep block | 1 |  |  |  | x | x
break_comp | Conditionally break out of a rep...endrep block, with a comparison | 3 |  |  |  | x | x
breakp | Break out of a rep...endrep block, based on a predicate | 3 |  |  |  | x | x
call | Call a subroutine | 2 |  |  |  | x | x
callnz bool | Call a subroutine if a boolean register is not zero | 3 |  |  |  | x | x
callnz pred | Call a subroutine if a predicate register is not zero | 3 |  |  |  | x | x
cmp | Compare source to 0 | 1 |  | x |  |  |
crs | Cross product | 2 |  | x |  |  |
dcl_samplerType | Declare the texture dimension for a sampler | 0 | x |  |  |  |
dcl | Declare the association between vertex shader output registers and pixel shader input registers. | 0 | x |  |  |  |
def | Define constants | 0 | x |  |  |  |
defb | Define a Boolean constant | 0 | x |  |  |  | x
defi | Define an integer constant | 0 | x |  |  |  | x
dp2add | 2-D dot product and add | 2 |  | x |  |  |
dp3 | 3-D dot product | 1 |  | x |  |  |
dp4 | 4-D dot product | 1 |  | x |  |  |
dsx | Rate of change in the x-direction | 2 |  | x |  |  | x
dsy | Rate of change in the y direction | 2 |  | x |  |  | x
else | Begin an else block | 1 |  |  |  | x | x
endif | End an if...else block | 1 |  |  |  | x | x
endrep | End of a repeat block | 2 |  |  |  | x | x
exp | Full precision 2x | 1 |  | x |  |  |
frc | Fractional component | 1 |  | x |  |  |
if bool | Begin an if block | 3 |  |  |  | x | x
if_comp | Begin an if block with a comparison | 3 |  |  |  | x | x
if pred | Begin an if block with predication | 3 |  |  |  | x | x
label | Label | 0 |  |  |  | x | x
log | Full precision log2(x) | 1 |  | x |  |  |
lrp | Linear interpolate | 2 |  | x |  |  |
m3x2 | 3x2 multiply | 2 |  | x |  |  |
m3x3 | 3x3 multiply | 3 |  | x |  |  |
m3x4 | 3x4 multiply | 4 |  | x |  |  |
m4x3 | 4x3 multiply | 3 |  | x |  |  |
m4x4 | 4x4 multiply | 4 |  | x |  |  |
mad | Multiply and add | 1 |  | x |  |  |
max | Maximum | 1 |  | x |  |  |
min | Minimum | 1 |  | x |  |  |
mov | Move | 1 |  | x |  |  |
mul | Multiply | 1 |  | x |  |  |
nop | No operation | 1 |  | x |  |  |
nrm | Normalize | 3 |  | x |  |  |
pow | xy | 3 |  | x |  |  |
ps | Version | 0 | x |  |  |  |
rcp | Reciprocal | 1 |  | x |  |  |
rep | Repeat | 3 |  |  |  | x | x
ret | End of a subroutine | 1 |  |  |  | x | x
rsq | Reciprocal square root | 1 |  | x |  |  |
setp_comp | Set the predicate register | 1 |  |  |  | x | x
sincos | Sine and cosine | 8 |  | x |  |  |
sub | Subtract | 1 |  | x |  |  |
texkill | Kill pixel render | See note 1 |  |  | x |  |
texld | Sample a texture | See note 2 |  |  | x |  |
texldb | Texture sampling with level of detail (LOD) bias from w-component | See note 3 |  |  | x |  |
texldd | Texture sampling with user-provided gradients | 3 |  |  | x |  | x
texldp | Texture sampling with projective divide by w-component | See note 4 |  |  | x |  |

Notes:

  1. If D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT is set, slots = 2; otherwise slots = 1.
  2. If D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT is set and the texture is a cube map, slots = 4; otherwise slot = 1.
  3. If D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT is set, slots = 6; otherwise slots = 1.
  4. If D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT is not set, slots = 1; otherwise:
    • if D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT is set and the texture is a cube map, slots = 4.
    • if D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT is set and the texture is not a cube map, slots = 3.


ps_3_0 Instructions
Microsoft DirectX 9.0 SDK Update (October 2004)

ps_3_0 Instructions

This section contains reference information for the pixel shader version 3_0 instructions.

There are several types of pixel shader instructions, as shown in the table. Columns to the right mean the following:

  • Instruction slots - Number of instruction slots used by each instruction.
  • Setup - A pixel shader must have a version instruction and it must be the first instruction.
  • Arithmetic - These instructions provide the mathematical operations in a shader.
  • Texture - These instructions are used to load and sample texture data, and to modify texture coordinates.
  • Flow control - These instructions provide static and dynamic flow control to the execution of instructions.
  • New - These instructions are new to this version.

Instruction Set

Name | Description | Instruction slots | Setup | Arithmetic | Texture | Flow control | New
abs | Absolute value | 1 |  | x |  |  |
add | Add two vectors | 1 |  | x |  |  |
break | Break out of a loop...endloop or rep...endrep block | 1 |  |  |  | x |
break_comp | Conditionally break out of a loop...endloop or rep...endrep block, with a comparison | 3 |  |  |  | x |
breakp | Break out of a loop...endloop or rep...endrep block, based on a predicate | 3 |  |  |  | x |
call | Call a subroutine | 2 |  |  |  | x |
callnz bool | Call a subroutine if a boolean register is not zero | 3 |  |  |  | x |
callnz pred | Call a subroutine if a predicate register is not zero | 3 |  |  |  | x |
cmp | Compare source to 0 | 1 |  | x |  |  |
crs | Cross product | 2 |  | x |  |  |
dcl_samplerType | Declare the texture dimension for a sampler | 0 | x |  |  |  |
dcl_usage | Declare input and output registers | 0 | x |  |  |  | x
def | Define constants | 0 | x |  |  |  |
defb | Define a Boolean constant | 0 | x |  |  |  |
defi | Define an integer constant | 0 | x |  |  |  |
dp2add | 2-D dot product and add | 2 |  | x |  |  |
dp3 | 3-D dot product | 1 |  | x |  |  |
dp4 | 4-D dot product | 1 |  | x |  |  |
dsx | Rate of change in the x-direction | 2 |  | x |  |  |
dsy | Rate of change in the y direction | 2 |  | x |  |  |
else | Begin an else block | 1 |  |  |  | x |
endif | End an if...else block | 1 |  |  |  | x |
endloop | endloop | 2 |  |  |  | x | x
endrep | End of a repeat block | 2 |  |  |  | x |
exp | Full precision 2x | 1 |  | x |  |  |
frc | Fractional component | 1 |  | x |  |  |
if bool | Begin an if block | 3 |  |  |  | x |
if_comp | Begin an if block with a comparison | 3 |  |  |  | x |
if pred | Begin an if block with predication | 3 |  |  |  | x |
label | Label | 0 |  |  |  | x |
log | Full precision log2(x) | 1 |  | x |  |  |
loop | Loop | 3 |  |  |  | x | x
lrp | Linear interpolate | 2 |  | x |  |  |
m3x2 | 3x2 multiply | 2 |  | x |  |  |
m3x3 | 3x3 multiply | 3 |  | x |  |  |
m3x4 | 3x4 multiply | 4 |  | x |  |  |
m4x3 | 4x3 multiply | 3 |  | x |  |  |
m4x4 | 4x4 multiply | 4 |  | x |  |  |
mad | Multiply and add | 1 |  | x |  |  |
max | Maximum | 1 |  | x |  |  |
min | Minimum | 1 |  | x |  |  |
mov | Move | 1 |  | x |  |  |
mul | Multiply | 1 |  | x |  |  |
nop | No operation | 1 |  | x |  |  |
nrm | Normalize | 3 |  | x |  |  |
pow | xy | 3 |  | x |  |  |
ps | Version | 0 | x |  |  |  |
rcp | Reciprocal | 1 |  | x |  |  |
rep | Repeat | 3 |  |  |  | x |
ret | End of a subroutine | 1 |  |  |  | x |
rsq | Reciprocal square root | 1 |  | x |  |  |
setp_comp | Set the predicate register | 1 |  |  |  | x |
sincos | Sine and cosine | 8 |  | x |  |  |
sub | Subtract | 1 |  | x |  |  |
texkill | Kill pixel render | 2 |  |  | x |  |
texld | Sample a texture | See note 1 |  |  | x |  |
texldb | Texture sampling with level of detail (LOD) bias from w-component | 6 |  |  | x |  |
texldl | Texture sampling with LOD from w-component | See note 2 |  |  | x |  | x
texldd | Texture sampling with user-provided gradients | 3 |  |  | x |  |
texldp | Texture sampling with projective divide by w-component | See note 3 |  |  | x |  |

Notes:

  1. If the texture is a cube map, slots = 4; otherwise slots = 1.
  2. If the texture is a cube map, slots = 5; otherwise slots = 2.
  3. If the texture is a cube map, slots = 4; otherwise slots = 3.


Modifiers for ps_1_X
Microsoft DirectX 9.0 SDK Update (October 2004)

Modifiers for ps_1_X

Instruction modifiers affect the result of the instruction before it is written into the destination register. For instance, use them to multiply or divide the result by a factor of two, or to clamp the result between zero and one. Instruction modifiers are applied after the instruction runs but before writing the result to the destination register.

A list of the modifiers is shown below.

Modifier | Description | Syntax | Version
 |  |  | 1_1 | 1_2 | 1_3 | 1_4
_x2 | Multiply by 2 | register_x2 | X | X | X | X
_x4 | Multiply by 4 | register_x4 | X | X | X | X
_x8 | Multiply by 8 | register_x8 |  |  |  | X
_d2 | Divide by 2 | register_d2 | X | X | X | X
_d4 | Divide by 4 | register_d4 |  |  |  | X
_d8 | Divide by 8 | register_d8 |  |  |  | X
_sat | Saturate (clamp from 0 and 1) | register_sat | X | X | X | X
  • The multiply modifier multiplies the register data by a power of two after it is read. This is the same as a shift left.
  • The divide modifier divides the register data by a power of two after it is read. This is the same as a shift right.
  • The saturate modifier clamps the range of register values from zero to one.

Instruction modifiers can be used on arithmetic instructions. They may not be used on texture address instructions.

Multiply modifier

This example loads the destination register (dest) with the sum of the two colors in the source operands (src0 and src1) and multiplies the result by two.

add_x2 dest, src0, src1

This example combines two instruction modifiers. First, two colors in the source operands (src0 and src1) are added. The result is then multiplied by two, and clamped between 0.0 to 1.0 for each component. The result is saved in the destination register.

add_x2_sat dest, src0, src1

Divide modifier

This example loads the destination register (dest) with the sum of the two colors in the source operands (src0 and src1) and divides the result by two.

add_d2 dest, src0, src1

Saturate modifier

For arithmetic instructions, the saturation modifier clamps the result of this instruction into the range 0.0 to 1.0 for each component. The following example shows how to use this instruction modifier.

dp3_sat r0, t0_bx2, v0_bx2    ; t0 is bump, v0 is light direction

This operation occurs after any multiply or divide instruction modifier. _sat is most often used to clamp dot product results. However, it also enables consistent emulation of multipass methods where the frame buffer is always in the range 0 to 1, and of Microsoft DirectX 6.0 and 7.0 multitexture syntax, in which saturation is defined to occur at every stage.

This example loads the destination register (dest) with the sum of the two colors in the source operands (src0 and src1), and clamps the result into the range 0.0 to 1.0 for each component.

add_sat dest, src0, src1

This example combines two instruction modifiers. First, two colors in the source operands (src0 and src1) are added. The result is multiplied by two and clamped between 0.0 to 1.0 for each component. The result is saved in the destination register.

add_x2_sat dest, src0, src1


Modifiers for ps_2_0 and Above
Microsoft DirectX 9.0 SDK Update (October 2004)

Modifiers for ps_2_0 and Above

Instruction modifiers affect the result of the instruction before it is written into the destination register.

This section contains reference information for the instruction modifiers implemented by pixel shader version 2_0 and above.

Name | Syntax | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
Saturate | _sat | x | x | x | x | x
Partial Precision | _pp | x | x | x | x | x
Centroid | _centroid |  |  |  | x | x

Saturate

The saturate instruction modifier (_sat) saturates (or clamps) the instruction result to the range [0, 1] before writing to the destination register.

The _sat instruction modifier can be used with any instruction except frc, sincos, and any tex* instructions.

For ps_2_0, ps_2_x, and ps_2_sw, the _sat instruction modifier cannot be used with instructions writing to any output registers (Output Color Register or Output Depth Register). This restriction does not apply to ps_3_0 and above.

Example:

dp3_sat r0, v0, c1

Partial Precision

The partial precision instruction modifier (_pp) indicates areas where partial precision is acceptable, provided that the underlying implementation supports it. Implementations are always free to ignore the modifier and perform the affected operations in full precision.

The _pp modifier can occur in two contexts:

  • On a texture coordinate declaration to enable texture coordinates to be passed to the pixel shader in partial precision form. This allows, for example, the use of texture coordinates to relay color data to the pixel shader, which may be faster with partial precision than with full precision in some implementations. In the absence of this modifier, texture coordinates must be passed in full precision.
  • On any instruction including texture load instructions. This indicates that the implementation is allowed to execute the instruction with partial precision and store a partial precision result. In the absence of an explicit modifier, the instruction must be performed at full precision (regardless of the input precision).

Examples:

dcl_texcoord0_pp t1
cmp_pp r0, r1, r2, r3

Centroid

Centroid is an optional instruction modifier (ps_3_0 and above) that modifies the way that sampling locations are altered when multisampling. Centroid clamps the attribute interpolation to the range of the attribute across the primitive, when the multisample pixel center is not covered by the primitive. Gradients computed from such data are not guaranteed to be accurate. Take care when an attribute marked with _centroid is used for texture sampling. Normally the evaluation is performed at the pixel center. Any Input Color Register (v#) declared with a _color* usage will automatically have _centroid applied implicitly.

dcl_texcoord0_centroid v0


Flow Control Limitations
Microsoft DirectX 9.0 SDK Update (October 2004)

Flow Control Limitations

Pixel shader flow control instructions have limits affecting how many levels of nesting can be included in the instructions. In addition, there are some limitations for implementing per-pixel flow control with gradient instructions.

  • Pixel Shader Instruction Depth Counts
  • Interaction of Per-Pixel Flow Control With Screen Gradients

Pixel Shader Instruction Depth Counts

ps_2_0 does not support flow control. The limitations for the other pixel shader versions are listed below.

Instruction Depth Count for ps_2_x

Each instruction counts against one or more nesting depth limits. The following table lists the depth count that each instruction adds or subtracts from the existing depth.

Instruction | Static nesting | Dynamic nesting | loop/rep nesting | call nesting
if bool | 1 | 0 | 0 | 0
if_comp | 0 | 1 | 0 | 0
if pred | 0 | 1 | 0 | 0
else | 0 | 0 | 0 | 0
endif | -1(if bool) | -1(if pred or if_comp) | 0 | 0
rep | 0 | 0 | 1 | 0
endrep | 0 | 0 | -1 | 0
break | 0 | 0 | 0 | 0
break_comp | 0 | 1, -1 | 0 | 0
breakp | 0 | 0 | 0 | 0
call | 0 | 0 | 0 | 1
callnz bool | 0 | 0 | 0 | 1
callnz pred | 0 | 1 | 0 | 1
ret | 0 | -1(callnz pred) | 0 | -1
setp_comp - ps | 0 | 0 | 0 | 0

Nesting Depth

Nesting depth defines the number of instructions can be called from inside of each other. Each type of instruction has one or more nesting limits as indicated in the following table.

Instruction Type | Maximum
Static nesting | 24 if (D3DCAPS9.PS20Caps.StaticFlowControlDepth > 0); 0 otherwise
Dynamic nesting | 0 to 24, see D3DCAPS9.PS20Caps.DynamicFlowControlDepth
rep nesting | 0 to 4, see D3DCAPS9.PS20Caps.StaticFlowControlDepth
call nesting | 0 to 4, see D3DCAPS9.PS20Caps.StaticFlowControlDepth (independent of rep limit)

Instruction Depth Count for ps_2_sw

Each instruction counts against one or more nesting depth limits. This table shows the depth count that each instruction adds or subtracts from the existing depth.

Instruction | Static nesting | Dynamic nesting | loop/rep nesting | call nesting
if bool | 1 | 0 | 0 | 0
if pred | 0 | 1 | 0 | 0
if_comp | 0 | 1 | 0 | 0
else | 0 | 0 | 0 | 0
endif | -1(if bool) | -1(if pred or if_comp) | 0 | 0
rep | 0 | 0 | 1 | 0
endrep | 0 | 0 | -1 | 0
loop | n/a | n/a | n/a | n/a
endloop | n/a | n/a | n/a | n/a
break | 0 | 0 | 0 | 0
break_comp | 0 | 1, -1 | 0 | 0
breakp | 0 | 0 | 0 | 0
call | 0 | 0 | 0 | 1
callnz bool | 0 | 0 | 0 | 1
callnz pred | 0 | 1 | 0 | 1
ret | 0 | -1(callnz pred) | 0 | -1
setp_comp - ps | 0 | 0 | 0 | 0

Nesting Depth

Nesting depth defines the number of instructions that can be called from inside of each other. Each type of instruction has one or more nesting limits as indicated in the following table.

Instruction Type | Maximum
Static nesting | 24
Dynamic nesting | 24
rep nesting | 4
call nesting | 4

Instruction Depth Count for ps_3_0

Each instruction counts against one or more nesting depth limits. This table shows the depth count that each instruction adds or subtracts from the existing depth.

Instruction | Static nesting | Dynamic nesting | loop/rep nesting | call nesting
if bool | 1 | 0 | 0 | 0
if pred | 0 | 1 | 0 | 0
if_comp | 0 | 1 | 0 | 0
else | 0 | 0 | 0 | 0
endif | -1(if bool) | -1(if pred or if_comp) | 0 | 0
rep | 0 | 0 | 1 | 0
endrep | 0 | 0 | -1 | 0
loop | 0 | 0 | 1 | 0
endloop | 0 | 0 | -1 | 0
break | 0 | 0 | 0 | 0
break_comp | 0 | 1, -1 | 0 | 0
breakp | 0 | 0 | 0 | 0
call | 0 | 0 | 0 | 1
callnz bool | 0 | 0 | 0 | 1
callnz pred | 0 | 1 | 0 | 1
ret | 0 | -1(callnz pred) | 0 | -1
setp_comp - ps | 0 | 0 | 0 | 0

Nesting Depth

Nesting depth defines the number of instructions that can be called from inside of each other. Each type of instruction has one or more nesting limits as indicated in the following table.

Instruction Type | Maximum
Static nesting | 24
Dynamic nesting | 24
loop/rep nesting | 4
call nesting | 4

Instruction Depth Count for ps_3_sw

Each instruction counts against one or more nesting depth limits. This table shows the depth count that each instruction adds or subtracts from the existing depth.

Instruction | Static nesting | Dynamic nesting | loop/rep nesting | call nesting
if bool | 1 | 0 | 0 | 0
if pred | 0 | 1 | 0 | 0
if_comp | 0 | 1 | 0 | 0
else | 0 | 0 | 0 | 0
endif | -1(if bool) | -1(if pred or if_comp) | 0 | 0
rep | 0 | 0 | 1 | 0
endrep | 0 | 0 | -1 | 0
loop | 0 | 0 | 1 | 0
endloop | 0 | 0 | -1 | 0
break | 0 | 0 | 0 | 0
break_comp | 0 | 1, -1 | 0 | 0
breakp | 0 | 0 | 0 | 0
call | 0 | 0 | 0 | 1
callnz bool | 0 | 0 | 0 | 1
callnz pred | 0 | 1 | 0 | 1
ret | 0 | -1(callnz pred) | 0 | -1
setp_comp - ps | 0 | 0 | 0 | 0

Nesting Depth

Nesting depth defines the number of instructions that can be called from inside of each other. Each type of instruction has one or more nesting limits as indicated in the following table.

Instruction Type | Maximum
Static nesting | 24
Dynamic nesting | 24
loop/rep nesting | 4
call nesting | 4

Interaction of Per-Pixel Flow Control With Screen Gradients

The pixel shader instruction set includes several instructions that produce or use gradients of quantities with respect to screen space x and y. The most common use for gradients is to compute level of detail (LOD) calculations for texture sampling, and in the case of anisotropic filtering, selecting samples along the axis of anisotropy. Typically, hardware implementations run the pixel shader on multiple pixels simultaneously (such as a 2x2 grid), so that gradients of quantities computed in the shader can be reasonably approximated as deltas of the values at the same point of execution in adjacent pixels.

When flow control is present in a shader, the result of a gradient calculation requested inside a given branch path is ambiguous when adjacent pixels may execute separate flow control paths. Therefore, it is deemed illegal to use any pixel shader operation that requests a gradient calculation to occur at a location that is inside a flow control construct which could vary across pixels for a given primitive being rasterized.

All pixel shader instructions are partitioned into those operations that are permitted and into those that are not permitted inside of flow control:

  • Scenario A: Operations that are permitted inside flow control that could vary across the pixels in a primitive. These include the operations listed in the following table.

    Instruction | Is Permitted in Flow Control when:
    texld, texldb and texldp | A temporary register is used for the texture coordinate.
    dsx and dsy | A temporary register is used for the operand.

  • Scenario B: Operations that are permitted anywhere. These include the operations listed in the following table.

    Instruction | Is Permitted Anywhere when:
    texld, texldb and texldp | A read-only quantity is used for the texture coordinate (may vary per-pixel, such as interpolated texture coordinates).
    dsx and dsy | A read-only quantity is used for the input operand (may vary per-pixel, such as interpolated texture coordinates).
    texldl | The user provides LOD as an argument, so there are no gradients, and thus no issue with flow control.
    texldd | The user provides gradients as input arguments, so there is no issue with flow control.

These restrictions are strictly enforced in shader validation. Scenarios having a branch condition that looks like it would branch consistently across a primitive, even though an operand in the condition expression is a pixel-shader-computed quantity, nevertheless still fall into scenario A and are not permitted. Similarly, scenarios where gradients are requested on some shader-computed quantity x from inside dynamic flow control, yet where it appears that x is not modified across any of the branches, nevertheless still fall into scenario A and are not permitted.

Predication is included in these restrictions on flow control, so that implementations remain free to trivially interchange the implementation of branch instructions with predicated instructions.

The user can use instructions from scenarios A and B together. For example, suppose the user needs an anisotropic texture sample given a shader computed texture coordinate; however, the texture load is only needed for pixels satisfying some per-pixel condition. To meet these requirements, the user can compute the texture coordinate for all pixels, outside per-pixel varying flow control, immediately computing gradients using dsx and dsy instructions. Then, within a per-pixel if bool/endif block, the user can use texldd (texture load with user provided gradients), passing the precalculated gradients. Another way to describe this usage pattern is that, while all pixels in the primitive had to compute the texture coordinates and be involved with gradient calculation, only the pixels that needed to sample a texture actually did so.

Regardless of these rules, the burden is still on the user to ensure that before computing any gradient (or performing a texture sample that implicitly computes a gradient), the register containing the source data must have been initialized for all execution paths beforehand. Initialization of temporary registers is not validated or enforced in general.


abs - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

abs - ps

Computes absolute value.

Syntax

abs dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
abs |  |  |  |  | x | x | x | x | x

This instruction works as shown here.

dest.x = abs(src.x)
dest.y = abs(src.y)
dest.z = abs(src.z)
dest.w = abs(src.w)

Instruction Information

Minimum operating system Windows 98


add - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

add - ps

Adds two vectors.

Syntax

add dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
add | x | x | x | x | x | x | x | x | x

The following code snippet shows the operations performed.

dest.x = src0.x + src1.x;
dest.y = src0.y + src1.y;
dest.z = src0.z + src1.z;
dest.w = src0.w + src1.w;

Instruction Information

Minimum operating system Windows 98


bem - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

bem - ps

Apply a fake bump environment-map transform.

Syntax

bem dst.rg, src0, src1

where

  • dst.rg dst is the destination register. The red and green component write mask must be used.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
bem |  |  |  | x |  |  |  |  |

This instruction performs the following calculation.

(Given n == dest register #)
dest.r = src0.r + D3DTSS_BUMPENVMAT00(stage n) * src1.r
                + D3DTSS_BUMPENVMAT10(stage n) * src1.g

dest.g = src0.g + D3DTSS_BUMPENVMAT01(stage n) * src1.r
                + D3DTSS_BUMPENVMAT11(stage n) * src1.g

Rules for using bem:

  1. bem must appear in the first phase of a shader (that is, before a phase marker).
  2. bem consumes two arithmetic instruction slots.
  3. Only one use of this instruction is allowed per shader.
  4. Destination writemask must be .rg /.xy.
  5. This instruction cannot be co-issued.
  6. Aside from the restriction that destination write mask be .rg, modifiers on source src0, src1, and instruction modifiers are unconstrained.

Instruction Information

Minimum operating system Windows 98


break - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

break - ps

Break out of the current loop at the nearest endloop or endrep.

Syntax

break

Remarks

This instruction is supported in the following versions.

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
break |  |  |  |  |  | x | x | x | x

Minimum operating system Windows 98


break_comp - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

break_comp - ps

Break out of the current loop at the nearest endloop or endrep, based on a per-component comparison.

Syntax

break_comp src0, src1

Where:

  • _comp is a scalar (or single) comparison between the two source registers. It can be one of the following:
    Syntax | Comparison
    _gt | Greater than
    _lt | Less than
    _ge | Greater than or equal
    _le | Less than or equal
    _eq | Equal to
    _ne | Not equal to
  • src0 is a source register. Replicate swizzle is required if selecting a single component.
  • src1 is a source register. Replicate swizzle is required if selecting a single component.

Remarks

This instruction is supported in the following versions.

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
break_comp |  |  |  |  |  | x | x | x | x

When the comparison is true, it breaks out of the current loop, as shown.

if (!(src0 comparison src1))
   jump to the corresponding endloop or endrep instruction;


breakp - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

breakp - ps

Conditionally break out of the current loop at the nearest endloop or endrep. Use one of the components of the predicate register as a condition to determine whether or not to perform the instruction.

Syntax

breakp [!]p0.{x|y|z|w}

Where:

  • [!] is an optional negate modifier.
  • p0 is the Predicate Register.
  • {x|y|z|w} is the required replicate swizzle on p0.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
breakp |  |  |  |  |  | x | x | x | x


call - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

call - ps

Performs a function call to the instruction marked with the provided label.

Syntax

call l#

Where:

  • l# is a label marking the beginning of the subroutine to be called.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
call |  |  |  |  |  | x | x | x | x

This instruction does the following:

  1. Push address of the next instruction to the return address stack.
  2. Continue execution from the instruction marked by the label.


callnz bool - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

callnz bool - ps

Call if not zero. Performs a conditional call to the instruction marked by the label index.

Syntax

callnz l#, [!]b#

Where:

  • l# is a label marking the beginning of the subroutine to be called.
  • [!] is an optional negate modifier.
  • b# identifies a Constant Boolean Register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
callnz bool |  |  |  |  |  | x | x | x | x

This instruction does the following:

if (specified Boolean register is not zero)
{
    Push address of the next instruction to the return address stack
    Continue execution from the instruction marked by the label
}


callnz pred - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

callnz pred - ps

Call with a predicate, if not zero. Performs a conditional call to the instruction marked by the label index. Predication uses a Boolean value to determine whether of not to perform the instruction.

Syntax

callnz l#, [!]p0.{x|y|z|w}

Where:

  • where l# is a label marking the beginning of the subroutine to be called.
  • [!] is an optional negate modifier.
  • p0 is the predicate register. See Predicate Register.
  • {x|y|z|w} is the required replicate swizzle on p0.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
callnz pred |  |  |  |  |  | x | x | x | x

This instruction does the following:

if (specified register component is not zero)
{
    Push address of the next instruction to the return address stack
    Continue execution from the instruction marked by the label
}


cmp - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

cmp - ps

Choose src1 if src0 >= 0. Otherwise, choose src2. The comparison is done per channel.

Syntax

cmp dst, src0, src1, src2

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.
  • src2 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
cmp |  | x | x | x | x | x | x | x | x

There are a few additional limitations for versions 1_2 and 1_3:

  • Each shader can use up to a maximum of three cmp instructions.
  • The destination register cannot be the same as any of the source registers.

This example does a four-channel comparison.

ps_1_4
def c0, -0.6, 0.6, 0, 0.6
def c1  0,0,0,0
def c2  1,1,1,1

mov r1, c1
mov r2, c2

cmp r0, c0, r1, r2   // r0 is assigned 1,0,0,0 based on the following:

// r0.x = c2.x because c0.x <  0
// r0.y = c1.y because c0.y >= 0
// r0.z = c1.z because c0.z >= 0
// r0.w = c1.w because c0.w >= 0


cnd - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

cnd - ps

Conditionally chooses between src1 and src2, based on the comparison src0 > 0.5.

Syntax

cnd dst, src0, src1, src2

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.
  • src2 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
cnd | x | x | x | x |  |  |  |  |

For versions 1_1 to 1_3, src0 must be r0.a.

// Version 1_1 to 1_3
if (r0.a > 0.5)
  dest = src1
else
  dest = src2

Version 1_4 compares each channel separately.

for each component in src0
{
   if (src0.component > 0.5)
     dest.component = src1.component
   else
     dest.component = src2.component
}

These examples show a four-channel comparison done in a version 1_4 shader, as well as a single-channel comparison possible in a version 1_1 shader.

ps_1_4
def c0, -0.5, 0.5, 0, 0.6
def c1,  0,0,0,0
def c2,  1,1,1,1

cnd r1, c0, c1, c2   // r0 contains 1,1,1,0 because
// r1.x = c2.x because c0.x <= 0.5
// r1.y = c2.y because c0.y <= 0.5
// r1.z = c2.z because c0.z <= 0.5
// r1.w = c1.w because c0.w >  0.5

Version 1_1 to 1_3 compares against the replicated alpha channel of r0 only.

ps_1_1
def c0, -0.5, 0.5, 0, 0.6
def c1,  0,0,0,0
def c2,  1,1,1,1
mov r0, c0
cnd r1, r0.a, c1, c2   // r1 gets assigned 0,0,0,0 because
                       // r0.a > 0.5, therefore r1.xyzw = c1.xyzw

This example compares two values, A and B. The example assumes A is loaded into v0 and B is loaded into v1. Both A and B must be in the range of -1 to +1, and since the color registers (vn) are defined to be between 0 and 1, the restriction happens to be satisfied in this example.

ps_1_1                // Version instruction
sub r0, v0, v1_bias   // r0 = A - (B - 0.5)
cnd r0, r0.a, c0, c1  // r0 = ( A > B ? c0 : c1 )

// r0 = c0 if A > B, otherwise, r0 = c1


crs - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

crs - ps

Computes a cross product using the right-hand rule.

Syntax

crs dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
crs |  |  |  |  | x | x | x | x | x

This instruction works as shown here.

dest.x = src0.y * src1.z - src0.z * src1.y;
dest.y = src0.z * src1.x - src0.x * src1.z;
dest.z = src0.x * src1.y - src0.y * src1.x;

Some restrictions on use:

  • src0 cannot be the same register as dest.
  • src1 cannot be the same register as dest.
  • src0 cannot have any swizzle other than the default swizzle (.xyzw).
  • src1 cannot have any swizzle other than the default swizzle (.xyzw).
  • dest has to have exactly one of the following seven masks: .x | .y | .z | .xy | .xz | .yz | .xyz.
  • dest must be a temporary register.
  • dest must not be the same register as src0 or src1


dcl - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

dcl - ps

Declare a pixel shader input register.

Syntax

dcl[_pp] dest[.mask]

Where:

  • [_pp] is optional partial precision. See Partial Precision.
  • dest is a destination register. It must be either a Input Color Register (vn), or an Texture Coordinate Register (tn).
  • [.mask] is an optional write mask that controls which components of the destination register that can be written to. See Destination Register Write Mask.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dcl |  |  |  |  | x | x | x | x | x

All dcl instructions must appear before the first executable instruction.


dcl_samplerType - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

dcl_samplerType - ps

Declare a pixel shader sampler.

Syntax

dcl_samplerType s#

where:

  • _samplerType defines the sampler data type. This determines how many coordinates are required by each texture coordinate when sampling. The following texture coordinate dimensions are defined.
    • _2d
    • _cube
    • _volume
  • s# identifies a sampler where s is an abbreviation for the sampler, and # is the sampler number. Samplers are pseudo registers because you cannot directly read or write to them.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dcl_samplerType |  |  |  |  | x | x | x | x | x

All dcl_samplerType instructions must appear before the first executable instruction.

Example

dcl_cube t0.rgb;  // Define a 3-D texture map.

add r0, r0, t0;   // Perturb texture coordinates.
texld r0, s0, r0; // Load r0 with a color sampled from stage0
                  //   at perturbed texture coordinates r0.
                  // This is a dependent texture read.


dcl_usage - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

dcl_usage - ps

Declare the association between a vertex shader outputs and pixel shader inputs.

Syntax

dcl_semantics [_centroid] dest[.write_mask]

Where:

  • _semantics: The same set of semantics as for the input declaration can be used. Semantic names come are paired with an index. See D3DDECLUSAGE .
  • [_Centroid] is an optional instruction modifier. It is is supported on dcl_usage instructions that declare the input registers and on texture lookup instructions. The centroid is appended with no space.
  • dest: destination register. See ps_3_0 Registers.
  • write_mask: The same output register may be declared multiple times each time with a unique write mask(so different semantics can be applied to individual components). However, the same semantic cannot be used multiple times in a declaration. This means that vectors must be four components or less, and cannot go across four-component register boundaries (individual output registers). When the _psize semantic is used, it should have a full write mask because it is considered a scalar. When the _position semantic is used, it should have full write mask because all four components have to be written.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dcl_usage |  |  |  |  |  |  |  | x | x

All dcl_usage instructions must appear before the first executable instruction.

Declaration Examples

ps_3_0

; Declaring inputs
dcl_normal      v0.xyz
dcl_blendweight v0.w ; Must be same reg# as normal, matching vshader packing
dcl_texcoord1   v1.y ; Mask can be any subset of mask from vshader semantic
dcl_texcoord0   v1.zw; Has to be same reg# as texcoord1, to match vshader

; Declaring samplers
dcl_2d s0
dcl_2d s1

def c0, 0, 0, 0, 0

mov r0.x, v1.y ; texcoord1
mov r0.y, c0
texld r0, r0, s0

texld r1, v1.zw, s1
...
(output regs in ps_3_0 are same as ps_2_0: oC0-oC3, oDepth)


def - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

def - ps

Defines pixel shader floating-point constants.

Syntax

def dest, fVvalue1, fValue2, fValue3, fValue4

Where:

  • dst is the destination register.
  • fValue1 to fValue4 are floating-point values..

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
def | x | x | x | x | x | x | x | x | x

There are two ways to set a floating-point constant in a pixel shader.

  1. Use def to define the constant directly inside a shader.
  2. Use the API to set a constant with IDirect3DDevice9::SetPixelShaderConstantF.

The def instruction defines a shader constant whose value is loaded any time a shader is set to a device. These are called "immediate constants." Immediate constants take precedence over constants set by the application programming interface (API) method.

  • Must appear before the first arithmetic or addressing instruction in shader.
  • Can be intermixed with dcl instructions (which are the other type of instruction that resides at the beginning of a shader).
  • dst register must be a constant register (cn).
  • Write mask must be full (default).
  • If a constant register is defined multiple times in a shader, the last one persists.


defb - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

defb - ps

Defines a boolean constant value, which should be loaded any time a shader is set to a device.

Syntax

defb dest, booleanValue

where

  • dst is the destination register.
  • booleanValue is a single boolean value, either true or false.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
defb |  |  |  |  |  | x | x | x | x

The defb instruction defines a boolean shader constant whose value is loaded anytime a shader is set to a device. These are called immediate constants. Immediate constants take precedence over constants set by the application programming interface (API) method SetPixelShaderConstantB.

There are two ways to set a booleanconstant in a shader.

  1. Use defb to define the constant directly inside a shader.
  2. Use the API methods to set a constant.
    • Use IDirect3DDevice9::SetPixelShaderConstantB to set a Boolean constant.

Related Topics

  • def
  • defi


defi - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

defi - ps

Defines an integer constant value, which should be loaded any time a shader is set to a device.

Syntax

defi dst, integerValue
  • dst is the destination register.
  • integerValue is a constant integer value.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
defi |  |  |  |  |  | x | x | x | x

The defi instruction defines a shader constant whose value is loaded anytime a shader is set to a device. These are called immediate constants. Immediate constants take precedence over constants set by the application programming interface (API) method SetPixelShaderConstantB.

There are two ways to set a constant in a shader.

  1. Use defi to define the constant directly inside a shader.
  2. Use the API methods to set a constant.
    • Use IDirect3DDevice9::SetPixelShaderConstantB to set a Boolean constant.
    • Use IDirect3DDevice9::SetPixelShaderConstantF to set a floating-point constant.
    • Use IDirect3DDevice9::SetPixelShaderConstantI to set an integer constant.


dp2add - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

dp2add - ps

Performs a 2-D dot product and a scalar addition.

Syntax

dp2add dst, src0, src1, src2.{x|y|z|w}

Where:

  • dst is a destination register.
  • src0, src1, and src2 are three source registers.
  • {x|y|z|w} is the required replicate swizzle on src2.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dp2add |  |  |  |  | x | x | x | x | x

The scalar value for add is chosen by the replicate swizzle on src2.

The following code snippet shows the operations performed.

dest = src0.r * src1.r + src0.g * src1.g + src2.replicate_swizzle
// The scalar result is replicated to the write mask components


dp3 - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

dp3 - ps

Computes the three-component dot product of the source registers.

Syntax

dp3 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dp3 | x | x | x | x | x | x | x | x | x

The following code snippet shows the operations performed:

dest.x = dest.y = dest.z = dest.w =
  (src0.x * src1.x) + (src0.y * src1.y) + (src0.z * src1.z);

This instruction runs in the vector pipeline, always writing out to the color channels. For version 1_4, this instruction still uses the vector pipeline but may write to any channel.

An instruction with a destination register .rgb (.xyz) write mask may be co-issued with dp3 as shown below.

dp3 r0.rgb, t0, v0            // Copy scalar result to color components
+mov r2.a, t0                 // Copy alpha component from t0 in parallel

The dp3 instruction can be modified using the Source Register Signed Scaling input argument modifier (_bx2) applied to its input arguments if they are not already expanded to signed dynamic range. For a lighting shader, the saturate instruction modifier (_sat) is often used to clamp the negative values to black, as shown in the following example.

dp3_sat r0, t0_bx2, v0_bx2    // t0 is a bump map, v0 contains the light direction


dp4 - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

dp4 - ps

Computes the four-component dot product of the source registers.

Syntax

dp4 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dp4 |  | x | x | x | x | x | x | x | x

The following code snippet shows the operations performed:

dest.x = dest.y = dest.z = dest.w =
    (src0.x * src1.x) + (src0.y * src1.y) +
    (src0.z * src1.z) + (src0.w * src1.w);

Limitations for ps_1_2 and ps_1_3:

  • Each shader can use up to a maximum of four dp4 instructions.
  • Each dp4 instruction counts as two arithmetic instructions.

Limitations for 1_X versions:

  • This instruction cannot be co-issued because dp4 runs in both the vector and alpha pipeline.


dsx - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

dsx - ps

Compute the rate of change in the render target's x-direction.

Syntax

dsx dst, src

Where:

  • dst is a destination register.
  • src is an input source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dsx |  |  |  |  |  | x | x | x | x

The rate of change computed from the source register is an approximation on the contents of the same register in adjacent pixel(s) running the pixel shader in lock-step with the current pixel. This is designed to work even if adjacent pixels follow different paths due to flow control, because the hardware is required to run a group of lock-step pixel shaders, disabling writes as necessary when flow control goes down a path that a particular pixel does not take.

The dsx and dsy instructions compute their result by looking at the current contents of the source register (per component) for the various pixels in the local area executing in the lock-step. The exact formula used to compute the gradient varies depending on the hardware but should be consistent with the way the hardware does the same operations as part of the level of detail (LOD) calculation process for texture sampling.

Related Topics

  • texldd


dsy - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

dsy - ps

Compute the rate of change in the render target's y-direction.

Syntax

dsy dst, src

Where:

  • dst is a destination register.
  • src is an input source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
dsy |  |  |  |  |  | x | x | x | x

The rate of change computed from the source register is an approximation on the contents of the same register in adjacent pixel(s) running the pixel shader in lock-step with the current pixel. This is designed to work even if adjacent pixels follow different paths due to flow control, because the hardware is required to run a group of lock-step pixel shaders, disabling writes as necessary when flow control goes down a path that a particular pixel does not take.

The dsx and dsy instructions compute their result by looking at the current contents of the source register (per component) for the various pixels in the local area executing in the lock-step. The exact formula used to compute the gradient varies depending on the hardware but should be consistent with the way the hardware does the same operations as part of the level of detail (LOD) calculation process for texture sampling.

Related Topics

  • texldd


else - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

else - ps

Start of an else block.

Syntax

else

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
else |  |  |  |  |  | x | x | x | x

If the condition in the corresponding if statement is true, the code enclosed by the if statement and the matching else is run.

Related Topics

  • if bool
  • endif


endif - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

endif - ps

Marks the end of an if...else block.

Syntax

endif

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
endif |  |  |  |  |  | x | x | x | x

Related Topics

  • if bool
  • else


endloop - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

endloop - ps

End of a loop...endloop block.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
endloop |  |  |  |  |  |  |  | x | x

endloop must follow the last instruction of a loop block.

Example

loop aL, i3
    add r1, r0, c2[ aL ]
endloop


endrep - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

endrep - ps

End a rep...endrep block.

Syntax

endrep

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
endrep |  |  |  |  |  | x | x | x | x

Example

rep i2
    add r0, r0, c0
endrep


exp - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

exp - ps

Provides full precision exponential 2x.

Syntax

exp dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle; that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified. See Source Register Swizzling.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
exp |  |  |  |  | x | x | x | x | x

The following code snippet shows the operations performed:

dest.x = dest.y = dest.z = dest.w = (float)pow(2, src.replicateSwizzleComponent);


frc - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

frc - ps

Returns the fractional portion of each input component.

Syntax

frc dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
frc |  |  |  |  | x | x | x | x | x

The following code snippet shows conceptually how the instruction operates.

dest.x = src.x - (float)floor(src.x);
dest.y = src.y - (float)floor(src.y);
dest.z = src.z - (float)floor(src.z);
dest.w = src.w - (float)floor(src.w);

The floor function converts the argument passed in to the greatest integer that is less than (or equal to) the argument. This is converted to a float and then subtracted fom the original value. The resulting fractional value ranges from 0.0 through 1.0.


if bool - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

if bool - ps

Start of an if block.

Syntax

if bool

Where:

  • bool is a bool (Boolean) register number. See Constant Boolean Register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
if bool |  |  |  |  |  | x | x | x | x

If the source Boolean register in the if statement is true, the code enclosed by the if statement and the matching endif or else is executed. Otherwise, the code enclosed by the else...endif statements is executed. This instruction consumes one instruction slot.

An if block can be nested.

An if block cannot straddle a loop block.

An if block can be followed by a statement block, and/or an else instruction, and/or an endif instruction.

Example

This instruction provides conditional static flow control.

defb b3, true

if b3
// Instructions to run if b3 is nonzero
else
// Instructions to run otherwise
endif

Related Topics

  • else
  • endif


if_comp - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

if_comp - ps

Start an if bool...else...endif block, with a condition based on values that could be computed in a shader. This instruction is used to skip a block of code, based on a condition.

Syntax

if_comp src0, src1

Where:

  • _comp is a comparison between the two source registers. It can be one of the following:
    Syntax | Comparison
    _gt | Greater than
    _lt | Less than
    _ge | Greater than or equal
    _le | Less than or equal
    _eq | Equal to
    _ne | Not equal to
  • src0 is a source register. Replicate swizzle is required to select a component.
  • src1 is a source register. Replicate swizzle is required to select a component.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
if_comp |  |  |  |  |  | x | x | x | x

This instruction is used to skip a block of code, based on a condition.

if (src0 comparison src1)
   jump to the corresponding else or endif instruction;

Be careful using the equals and not equals comparison modes on floating point numbers. Because rounding occurs during during floating point calculations, the comparison can be done against an epsilon value (small nonzero number) to avoid errors.

Restrictions include:

  • if_comp...else...endif blocks (along with the predicated if blocks) can be nested up to 24 layers deep.
  • src0 and src1 registers require a replicate swizzle.
  • if_comp blocks must end with an else or endif instruction.
  • if_comp...else...endif blocks cannot straddle a loop block. The if_comp block must be completely inside or outside the loop block.

Example

This instruction provides conditional dynamic flow control.

if_lt r3.x, r4.y
// Instructions to run if r3.x < r4.y

else
// Instructions to run otherwise

endif


if pred - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

if pred - ps

Start of an if bool...else...endif block, with the condition taken from the content of the predicate register.

Syntax

if [!]pred.replicateSwizzle

Where:

  • [!] is an optional NOT modifier. This modifies the value in the predicate register.
  • pred is the Predicate Register.
  • replicateSwizzle is a single component that is copied (or replicated) to all four components (swizzled). Valid components are: [x, y, z, w] or [r, g, b, a].

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
if_pred |  |  |  |  |  | x | x | x | x

This instruction is used to skip a block of code, based on a channel of the predicate register. Each if_pred block must end with an else or endif instruction.

Restrictions include:

if_pred blocks can be nested. This counts to the total dynamic nesting depth along with if_comp blocks.

An if_pred block cannot straddle a loop block; it should either be completely inside it or surround it.


label - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

label - ps

Mark the next instruction as having a label index.

Syntax

label l#

where # identifies the label number.

For ps_2_x, the label number must be between between 0 and 15.

For ps_2_sw, ps_3_0, and ps_3_sw, the label number must be between between 0 and 2047.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
label |  |  |  |  |  | x | x | x | x

This instruction defines a label located at the next shader instruction. The label instruction can only be present directly after a ret instruction (which defines the end of the previous subroutine or main program).


loop - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

loop - ps

Starts a loop...endloop block.

Syntax

loop aL, i#

Where:

  • aL is the Loop Counter Register holding the current loop count.
  • i# is a Constant Integer Register. See remarks.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
loop |  |  |  |  |  |  |  | x | x
  • The Loop Counter Register holds the current loop count and can be used for relative addressing into Input Color Register (v#) inside the loop block.
  • i#.x specifies the iteration count. The legal range is [0, 255].
  • i#.y specifies the initial value of the Loop Counter Register register. The legal range is [0, 255].
  • i#.z specifies the step/stride size. The legal range is [-128, 127].
  • i#.w is not used by the loop block and has to be 0.
  • Loop blocks may be nested. See Flow Control Limitations.
  • When nested, the value of the Loop Counter Register refers to the immediate enclosing loop block.
  • Loop blocks are allowed to be either completely inside an if* block or completely surrounding it. No straddling is allowed.

Example

loop aL, i3
    add r1, r0, v2[ aL ]
endloop


log - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

log - ps

Full precision log2(x).

Syntax

log dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle; that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
log |  |  |  |  | x | x | x | x | x

The following code snippet shows the operations performed.

float v = abs(src);
if (v != 0)
{
    dest.x = dest.y = dest.z = dest.w =
        (float)(log(v)/log(2));
}
else
{
    dest.x = dest.y = dest.z = dest.w = -FLT_MAX;
}

This instruction accepts a scalar source whose sign bit is ignored. The result is replicated to all four channels.


lrp - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

lrp - ps

Interpolates linearly between the second and third source registers by a proportion specified in the first source register.

Syntax

lrp dst, src0, src1, src2

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.
  • src2 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
lrp | x | x | x | x | x | x | x | x | x

This instruction performs the linear interpolation based on the following formula.

dest = src0 * src1 + (1-src0) * src2
// which is the same as
dest = src2 + src0 * (src1 - src2)


m3x2 - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

m3x2 - ps

Computes the product of a 3-component vector and a 2x3 matrix.

Syntax

m3x2 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register, which corresponds to the first of two consecutive constant registers.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m3x2 |  |  |  |  | x | x | x | x | x

The xy mask is required for the destination register. Negate and swizzle modifiers are allowed for src0 but not for src1.

The following equations show how the instruction operates:

dest.x = (src0.x*src1.x) + (src0.y*src1.y) + (src0.z*src1.z);
dest.y = (src0.x*src2.x) + (src0.y*src2.y) + (src0.z*src2.z);

The input vector is in register src0. The input 3x2 matrix is in register src1 and the next higher register in the same register file, as shown in the following expansion. A 2-D result is produced, leaving the other elements of the destination register (dest.z and dest.w) unaffected.

This operation is commonly used for 2-D transforms. This instruction is implemented as a pair of dot products as shown here.

m3x2   r0.xy, r1, c0   which will be expanded to:

dp3   r0.x, r1, c0
dp3   r0.y, r1, c1

Swizzle and negate modifiers are invalid for the src1 register. The dest and src0 register, or any of src1+i registers, cannot be the same.


m3x3 - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

m3x3 - ps

Computes the product of a 3-component vector and a 3x3 matrix.

Syntax

m3x3 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register, which corresponds to the first of three consecutive constant registers.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m3x3 |  |  |  |  | x | x | x | x | x

The xyz mask is required for the destination register. Negate and swizzle modifiers are allowed for src0 but not for src1.

The following code snippet shows the operations performed.

dest.x = (src0.x * src1.x) + (src0.y * src1.y) + (src0.z * src1.z);
dest.y = (src0.x * src2.x) + (src0.y * src2.y) + (src0.z * src2.z);
dest.z = (src0.x * src3.x) + (src0.y * src3.y) + (src0.z * src3.z);

The input vector is in register src0. The input 3x3 matrix is in register src1, and the next two higher registers, as shown in the expansion below. A 3-D result is produced, leaving the other element of the destination register (dest.w) unaffected.

This operation is commonly used for transforming normal vectors during lighting computations. This instruction is implemented as a set of dot products as shown below.

m3x3 r0.xyz, r1, c0  which will be expanded to:

dp3   r0.x, r1, c0
dp3   r0.y, r1, c1
dp3   r0.z, r1, c2


m3x4 - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

m3x4 - ps

Computes the product of a 3-component vector and a 3x4 matrix.

Syntax

m3x4 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register, which corresponds to the first of four consecutive constant registers.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m3x4 |  |  |  |  | x | x | x | x | x

The xyzw (default) mask is required for the destination register. Negate and swizzle modifiers are allowed for src0 but not for src1.

The following code snippet shows the operations performed.

dest.x = (src0.x*src1.x) + (src0.y*src1.y) + (src0.z*src1.z);
dest.y = (src0.x*src2.x) + (src0.y*src2.y) + (src0.z*src2.z);
dest.z = (src0.x*src3.x) + (src0.y*src3.y) + (src0.z*src3.z);
dest.w = (src0.x*src4.x) + (src0.y*src4.y) + (src0.z*src4.z);

The input vector is in register src0. The input 3x4 matrix is in register src1, and the next two higher registers, as shown in the expansion below.

This operation is commonly used for transforming a position vector by a matrix that has a projective effect but applies no translation. This instruction is implemented as a pair of dot products as shown here.

m3x4   r0.xyzw, r1, c0   will be expanded to:

dp3 r0.x, r1, c0
dp3 r0.y, r1, c1
dp3 r0.z, r1, c2
dp3 r0.w, r1, c3


m4x3 - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

m4x3 - ps

Computes the product of a 4-component vector and a 4x3 matrix.

Syntax

m4x3 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register, which corresponds to the first of three consecutive constant registers.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m4x3 |  |  |  |  | x | x | x | x | x

The xyz mask is required for the destination register. Negate and swizzle modifiers are allowed for src0, but not for src1.

The following code snippet shows the operations performed.

dest.x = (src0.x*src1.x) + (src0.y*src1.y) + (src0.z*src1.z) + (src0.w*src1.w);
dest.y = (src0.x*src2.x) + (src0.y*src2.y) + (src0.z*src2.z) + (src0.w*src2.w);
dest.z = (src0.x*src3.x) + (src0.y*src3.y) + (src0.z*src3.z) + (src0.w*src3.w);

The input vector is in register src0. The input 4x3 matrix is in register src1, and the next two higher registers, as shown in the expansion below. A 3-D result is produced, leaving the other element of the destination register (dest.w) unaffected.

This operation is commonly used for transforming a position vector by a matrix that has no projective effect, such as occurs in model-space transformations. This instruction is implemented as a set of dot products as shown below.

m4x3   r0.xyz, r1, c0    will be expanded to:

dp4   r0.x, r1, c0
dp4   r0.y, r1, c1
dp4   r0.z, r1, c2

Swizzle and negate modifiers are invalid for the src1 register. The dst and src0 register cannot be the same.


m4x4 - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

m4x4 - ps

Computes the product of a 4-component vector and a 4x4 matrix.

Syntax

m4x4 dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register, which corresponds to the first of four consecutive constant registers.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
m4x4 |  |  |  |  | x | x | x | x | x

The xyzw (default) mask is required for the destination register. Negate and swizzle modifiers are allowed for src0, but not for src1.

Swizzle and negate modifiers are invalid for the src0 register. The dst and src0 registers cannot be the same.

The following code snippet shows the operations performed.

dest.x = (src0.x*src1.x) + (src0.y*src1.y) + (src0.z*src1.z) + (src0.w*src1.w);
dest.y = (src0.x*src2.x) + (src0.y*src2.y) + (src0.z*src2.z) + (src0.w*src2.w);
dest.z = (src0.x*src3.x) + (src0.y*src3.y) + (src0.z*src3.z) + (src0.w*src3.w);
dest.w = (src0.x*src4.x) + (src0.y*src4.y) + (src0.z*src4.z) + (src0.w*src4.w);

The input vector is in register src0. The input 4x4 matrix is in register src1, and the next three higher registers, as shown in the expansion below.

This operation is commonly used for transforming a position by a projection matrix. This instruction is implemented as a set of dot products as shown here.

m4x4   r0.xyzw, r1, c0    will be expanded to:

dp4   r0.x, r1, c0
dp4   r0.y, r1, c1
dp4   r0.z, r1, c2
dp4   r0.w, r1, c3


mad - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

mad - ps

Multiply and add instruction. Sets the destination register to (src0 * src1) + src2.

Syntax

mad dst, src0, src1, src2

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.
  • src2 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
mad | x | x | x | x | x | x | x | x | x

The following code snippet shows the operations performed.

dest.x = src0.x * src1.x + src2.x;
dest.y = src0.y * src1.y + src2.y;
dest.z = src0.z * src1.z + src2.z;
dest.w = src0.w * src1.w + src2.w;


mov - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

mov - ps

Move data between registers.

Syntax

mov dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
mov | x | x | x | x | x | x | x | x | x


mul - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

mul - ps

Multiplies sources into the destination.

Syntax

mul dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
mul | x | x | x | x | x | x | x | x | x

The following code snippet shows the operations performed.

dest.x = src0.x * src1.x;
dest.y = src0.y * src1.y;
dest.z = src0.z * src1.z;
dest.w = src0.w * src1.w;


max - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

max - ps

Calculates the maximum of the sources.

Syntax

max dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
max |  |  |  |  | x | x | x | x | x

The following code snippet shows the operations performed.

dest.x=(src0.x >= src1.x) ? src0.x : src1.x;
dest.y=(src0.y >= src1.y) ? src0.y : src1.y;
dest.z=(src0.z >= src1.z) ? src0.z : src1.z;
dest.w=(src0.w >= src1.w) ? src0.w : src1.w;


min - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

min - ps

Calculates the minimum of the sources.

Syntax

min dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
min |  |  |  |  | x | x | x | x | x

The following code snippet shows the operations performed.

dest.x=(src0.x < src1.x) ? src0.x : src1.x;
dest.y=(src0.y < src1.y) ? src0.y : src1.y;
dest.z=(src0.z < src1.z) ? src0.z : src1.z;
dest.w=(src0.w < src1.w) ? src0.w : src1.w;


nrm - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

nrm - ps

Normalize a 3-D vector.

Syntax

nrm dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
nrm |  |  |  |  | x | x | x | x | x

This instruction works conceptually as shown here.

squareRootOfTheSum = (src0.x*src0.x + src0.y*src0.y + src0.z*src0.z)1/2;
dest.x = src0.x * (1 / squareRootOfTheSum);
dest.y = src0.y * (1 / squareRootOfTheSum);
dest.z = src0.z * (1 / squareRootOfTheSum);
dest.w = src0.w * (1 / squareRootOfTheSum);

The dest and src registers cannot be the same. The dest register must be a temporary register.

This instruction performs the linear interpolation based on the following formula.

float f = src0.x*src0.x + src0.y*src0.y + src0.z*src0.z;
if (f != 0)
    f = (float)(1/sqrt(f));
else
    f = FLT_MAX;

dest.x = src0.x*f;
dest.y = src0.y*f;
dest.z = src0.z*f;
dest.w = src0.w*f;


nop - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

nop - ps

No operation is performed.

Syntax

nop

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
nop | x | x | x | x | x | x | x | x | x

This instruction performs a no-op, or no operation. The syntax for calling it is as follows:

nop


phase - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

phase - ps

The phase instruction marks the transition between phase 1 and phase 2. If no phase instruction is present, the entire shader runs as if it is a phase 2 shader.

This instruction applies to version 1_4 only.

Syntax

phase

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
phase |  |  |  | x |  |  |  |  |

Shader instructions that occur before the phase instruction are phase 1 instructions. All other instructions are phase 2 instructions. By having two phases for instructions, the maximum number of instructions per shader is increased.

The unfortunate side-effect of the phase transition is that the alpha component of temporary registers do not persist across the transition. In other words, the alpha component must be reinitialized after the phase instruction.

Example

This example shows how to group instructions as phase 1 or phase 2 instructions within a shader.

The phase instruction is also commonly called the phase marker because it marks the transition between phase 1 and 2 instructions. In a version 1_4 pixel shader, if the phase marker is not present, the shader is run as if it is running in phase 2. This is important because there are differences between phase 1 and 2 instructions and register availability. The differences are noted throughout the reference section.

ps_1_4
  // Add phase 1 instructions here

phase
  // Add phase 2 instructions here


pow - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

pow - ps

Full precision abs(src0)src1.

Syntax

pow dst, src0, src1

where

  • dst is the destination register.
  • src0 is an input source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.
  • src1 is an input source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
pow |  |  |  |  | x | x | x | x | x

This instruction works as follows:

dest.x = dest.y = dest.z = dest.w = [abs(src0)]src1;

This is a scalar instruction, therefore the source registers should have replicate swizzles to indicate which channels are used.

The input power (src1) must be a scalar.

The scalar result is replicated to all four output channels.

This instruction could be expanded as exp(src1 * log(src0)).

The dst register should be a temporary register, and should not be the same register as src1.


ps
Microsoft DirectX 9.0 SDK Update (October 2004)

ps

This instruction specifies the shader version number and works on all shader versions.

Syntax

ps_mainVer_subVer

Input Arguments

Input arguments contain a single main version number with a single sub version number. The allowable combinations are listed in the table below.

Main versions | Sub versions
1 | 1, 2, 3, 4
2 | 0, x (extended), sw (software)
3 | 0, sw (software)

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
ps | x | x | x | x | x | x | x | x | x

This instruction must be the first non-comment instruction in a pixel shader.

Hardware accelerated versions of the software (versions without _sw in the version number), can process vertices with hardware accelearation or use software vertex processing. Software versions (versions with _sw in the version number) process vertices only with software.

Examples

This partial example declares a version 1_1 pixel shader.

ps_1_1

This partial example declares a version 1_4 pixel shader.

ps_1_4


rcp - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

rcp - ps

Computes the reciprocal of the source scalar.

Syntax

rcp dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
rcp |  |  |  |  | x | x | x | x | x

The output must be exactly 1.0 if the input is exactly 1.0. A source of 0.0 yields infinity.

The scalar result is replicated to all channels in the destination write mask.

Precision should be at least 1.0/(222) absolute error over the range (1.0, 2.0) because common implementations will separate mantissa and exponent.


rep - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

rep - ps

Start a rep...endrep block.

Syntax

rep i#

where i# is an integer register that specifies the repeat count in the .x component. See Constant Integer Register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
rep |  |  |  |  |  | x | x | x | x
  • i#.x specifies the iteration count. The legal range is [0, 255].
  • i#.yzw are not used by the repeat block.
  • Repeat blocks may be nested. See Flow Control Limitations.
  • Repeat blocks are allowed to be either completely inside an if* block or completely surrounding it. No straddling is allowed.

Example

rep i2
    add r0, r0, c0
endrep


ret - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

ret - ps

Takes the address of an instruction from the return address stack and continues execution from it. In the case of the main function, this instruction stops shader execution.

Syntax

ret

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
ret |  |  |  |  |  | x | x | x | x

This instruction takes the address of an instruction from the return address stack and continues execution from it. In the case of the main function, this instruction stops shader execution.

The ret instruction consumes one vertex shader instruction slot.

If a shader contains no subroutines, using ret at the end of the main program is optional.

Multiple return statements are not permitted in the main program or in any subroutine, the first return statement is treated as the end of the main program or subroutine.


rsq - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

rsq - ps

Computes the reciprocal square root (positive only) of the source scalar.

Syntax

rsq dst, src

where

  • dst is the destination register.
  • src is a source register. Source register requires explicit use of replicate swizzle, that is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
rsq |  |  |  |  | x | x | x | x | x

The absolute value is taken before processing.

Precision should be at least 1.0/(222) absolute error over the range (1.0, 4.0) because common implementations will separate mantissa and exponent.

The output must be exactly 1.0 if the input is exactly 1.0. A source of 0.0 yields infinity.


setp_comp - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

setp_comp - ps

Set the predicate register.

Syntax

setp_comp dst, src0, src1

Where:

  • _comp is a per-channel comparison between the two source registers. It can be one of the following:
    Syntax | Comparison
    _gt | Greater than
    _lt | Less than
    _ge | Greater than or equal
    _le | Less than or equal
    _eq | Equal to
    _ne | Not equal to
  • dst is the Predicate Register register, p0.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
setp_comp |  |  |  |  |  | x | x | x | x

This instruction operates as:

per channel in destination write mask
{
  dst.channel = src0.channel cmp src1.channel
}

For each channel that can be written according to the destination write mask, save the boolean result of the comparison operation between the corresponding channels of src0 and src1 (after the source modifier swizzles have been resolved).

Source registers allow arbitrary component swizzles to be specified.

The destination register allows arbitrary write masks.

The dest register must be the predicate register.

Applying the Predicate Register

Once the predicate register has been initialized with setp_comp, it can be used to control an instruction per component. Here's the syntax:

([!]p0[.swizzle]) instruction dest, srcReg, ...

Where:

  • [!] is an optional boolean NOT
  • p0 is the predicate register
  • [.swizzle] is an optional swizzle to apply to the contents of the predicate register before using it to mask the instruction. The available swizzles are: .xyzw (default when none specified), or any replicate swizzle: .x/.r, .y/.g, .z/.b or .a/.w.
  • instruction is any aritmetic, or texture instruction. This cannot be a static or dynamic flow control instruction.
  • dest, srcReg, ... are the registers required by the instruction

Assuming the predicate register has been set up with (true, true, false, false) component values, it can be applied to this instruction:

(p0) add r1, r2, r3

to perform a 2 component add.

r1.x = r2.x + r3.x
r1.y = r2.y + r3.y

The x and y components of r1 will not be written since the predicate register contained false in components z and w.

Applying the predicate register to an arithmetic or texture instruction increases its instruction slot count by 1.

The predicate register can also be applied to if pred, callnz pred and breakp instructions. These flow control instructions do not have any increase in the instruction slot count when using the predicate register.

Minimum operating system Windows 98


sincos - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

sincos - ps

Computes sine and cosine, in radians.

Syntax

ps_2_0 and ps_2_x

sincos dst.{x|y|xy}, src0.{x|y|z|w}, src1, src2

Where:

  • dst is the destination register and has to be a Temporary Register (r#). The destination register must have exactly one of the following three masks: .x | .y | .xy.
  • src0 is a source register that provides the input angle, which must be within [-pi, +pi]. {x|y|z|w} is the required replicate swizzle.
  • src1 and src2 are source registers and must be two different Constant Float Registers (c#). The values of src1 and src2 must be that of the macros D3DSINCOSCONST1 and D3DSINCOSCONST2 respectively.

ps_3_0

sincos dst.{x|y|xy}, src0.{x|y|z|w}

Where:

  • dst is a destination register and has to be a Temporary Register (r#). The destination register must have exactly one of the following three masks: .x | .y | .xy.
  • src0 is a source register that provides the input angle, which must be within [-pi, +pi]. {x|y|z|w} is the required replicate swizzle.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
sincos |  |  |  |  | x | x | x | x | x

ps_2_0 and ps_2_x

For ps_2_0 and ps_2_x, sincos can be used with predication, but with one restriction to the swizzle of the Predicate Register (p0): only replicate swizzle (.x | .y | .z | .w) is allowed.

For ps_2_0 and ps_2_x, the instruction operates as follows (V = the scalar value from src0 with a replicate swizzle):

  • If the write mask is .x:
    dest.x = cos(V)
dest.y is undefined when the instruction completes
dest.z is undefined when the instruction completes
dest.w is not touched by the instruction
  • If the write mask is .y:
    dest.x is undefined when the instruction completes
dest.y = sin(V)
dest.z is undefined when the instruction completes
dest.w is not touched by the instruction
  • If the write mask is .xy:
    dest.x = cos(V)
dest.y = sin(V)
dest.z is undefined when the instruction completes
dest.w is not touched by the instruction

ps_3_0

For ps_3_0, sincos can be used with predication without any restriction. See Predicate Register.

For ps_3_0, the instruction operates as follows (V = the scalar value from src0 with a replicate swizzle):

  • If the write mask is .x:
    dest.x = cos(V)
dest.y is not touched by the instruction
dest.z is not touched by the instruction
dest.w is not touched by the instruction
  • If the write mask is .y:
    dest.x is not touched by the instruction
dest.y = sin(V)
dest.z is not touched by the instruction
dest.w is not touched by the instruction
  • If the write mask is .xy:
    dest.x = cos(V)
dest.y = sin(V)
dest.z is not touched by the instruction
dest.w is not touched by the instruction

The application can map an arbitrary angle (in radians) to the range [-pi, +pi] using the following shader pseudocode:

def c0, pi, 0.5, 2*pi, 1/(2*pi)
mad r0.x, input_angle, c0.w, c0.y
frc r0.x, r0.x
mad r0.x, r0.x, c0.z, -c0.x


sub - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

sub - ps

Subtracts sources.

Syntax

sub dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register.
  • src1 is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
sub | x | x | x | x | x | x | x | x | x

This instruction performs the subtraction shown in this formula.

dest = src0 - src1


tex - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

tex - ps

Loads the destination register with color data (RGBA) sampled from a texture. The texture must be bound to a particular texture stage (n) using IDirect3DDevice9::SetTexture. Texture sampling is controlled by IDirect3DDevice9::SetSamplerState.

Syntax

tex dst

where

  • dst is the destination register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
tex | x | x | x |  |  |  |  |  |

The destination register number specifies the texture stage number.

Texture sampling uses texture coordinates to look up, or sample, a color value at the specified (u,v,w,q) coordinates while taking into account the texture stage state attributes.

The texture coordinate data is interpolated from the vertex texture coordinate data and is associated with a specific texture stage. The default association is a one-to-one mapping between texture stage number and texture coordinate declaration order. This means that the first set of texture coordinates defined in the vertex format are by default associated with texture stage 0.

Texture coordinates may be associated with any stage using two techniques. When using a fixed function vertex shader or the fixed function pipeline, the texture stage state flag TSS_TEXCOORDINDEX can be used in IDirect3DDevice9::SetTextureStageState to associate coordinates to a stage. Otherwise, the texture coordinates are output by the vertex shader oTn registers when using a programmable vertex shader.


texbem - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

texbem - ps

Apply a fake bump environment-map transform. This is accomplished by modifying the texture address data of the destination register, using address perturbation data (du,dv), and a 2-D bump environment matrix.

Syntax

texbem dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texbem | x | x | x |  |  |  |  |  |

The red and green color data in the src register is interpreted as the perturbation data (du,dv).

This instruction transforms red and green components in the source register using the 2-D bump environment-mapping matrix. The result is added to the texture coordinate set corresponding to the destination register number, and is used to sample the current texture stage.

This operation always interprets du and dv as signed quantities. For versions 1_0 and 1_1, the Source Register Signed Scaling input modifier (_bx2) is not permitted on the input argument.

This instruction produces defined results when input textures contain signed format data. Mixed format data works only if the first two channels contain signed data. For more information about surface formats, see D3DFORMAT.

This can be used for a variety of techniques based on address perturbation, including fake per-pixel environment mapping and diffuse lighting (bump mapping).

When using this instruction, texture registers must follow the following sequence.

// The texture assigned to stage t(n) contains the (du,dv) data
// The texture assigned to stage t(m) is sampled
tex     t(n)
texbem  t(m),  t(n)      where m > n

The calculations done within the instruction are shown below.

// 1. New values for texture addresses (u',v') are calculated
// 2. Sample the texture using (u',v')

u' = TextureCoordinates(stage m)u +
      D3DTSS_BUMPENVMAT00(stage m)*t(n)R +
      D3DTSS_BUMPENVMAT10(stage m)*t(n)G

v' = TextureCoordinates(stage m)v +
      D3DTSS_BUMPENVMAT01(stage m)*t(n)R +
      D3DTSS_BUMPENVMAT11(stage m)*t(n)G

t(m)RGBA = TextureSample(stage m)
// using (u',v') as coordinates

Register data that has been read by a texbem - ps or texbeml instruction cannot be read later, except by another texbem - ps or texbeml.

// This example demonstrates the validation error caused by t0 being reread:
ps_1_1
tex t0
texbem t1, t0
add r0, t1, t0

(Instruction Error) (Statement 4) Register data that has been read by
texbem or texbeml instruction cannot be read by other instructions

Examples

Here is an example shader with the texture maps identified and the texture stages identified.

ps_1_1
tex t0              ; Define t0 to get a 2-tuple DuDv
texbem t1, t0       ; Compute (u',v')
                    ; Sample t1 using (u',v')
mov r0, t1          ; Output result

texbem requires the following textures in the following texture stages.

  • Stage 0 is assigned a bump map with (du, dv) perturbation data.
  • Stage 1 uses a texture map with color data.
  • This instruction sets the matrix data on the texture stage that is sampled.
  • This is different from the functionality of the fixed function pipeline where the perturbation data and the matrices occupy the same texture stage.


texbeml - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

texbeml - ps

Apply a fake bump environment-map transform with luminance correction. This is accomplished by modifying the texture address data of the destination register, using address perturbation data (du,dv), a 2-D bump environment matrix, and luminance.

Syntax

texbeml dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texbeml | x | x | x |  |  |  |  |  |

The red and green color data in the src register is interpreted as the perturbation data (du,dv). The blue color data in the src register is interpreted as the luminance data.

This instruction transforms the red and green components in the source register using the 2-D bump environment mapping matrix. The result is added to the texture coordinate set corresponding to the destination register number. A luminance correction is applied using the luminance value and the bias texture stage values. The result is used to sample the current texture stage.

This can be used for a variety of techniques based on address perturbation such as fake per-pixel environment mapping.

This operation always interprets du and dv as signed quantities. For versions 1_0 and 1_1, the Source Register Signed Scaling input modifier (_bx2) is not permitted on the input argument.

This instruction produces defined results when input textures contain mixed format data. For more information about surface formats, see D3DFORMAT.

// When using this instruction, texture registers must follow
//   the following sequence:
// The texture assigned to stage tn contains the (du,dv) data
// The texture assigned to stage t(m) is sampled
tex     t(n)
texbeml t(m),  t(n)      where m > n

This example shows the calculations done within the instruction.

// 1. New values for texture addresses (u',v') are calculated
// 2. Sample the texture using (u',v')
// 3. Luminance correction is applied

u' = TextureCoordinates(stage m)u +
    D3DTSS_BUMPENVMAT00(stage m)*t(n)R +
    D3DTSS_BUMPENVMAT10(stage m)*t(n)G

v' = TextureCoordinates(stage m)v +
    D3DTSS_BUMPENVMAT01(stage m)*t(n)R +
    D3DTSS_BUMPENVMAT11(stage m)*t(n)G

t(m)RGBA = TextureSample(stage m) using (u',v') as coordinates

t(m)RGBA = t(m)RGBA*
    [(t(n)B * D3DTSS_BUMPENVLSCALE(stage m)) +
        D3DTSS_BUMPENVLOFFSET(stage m)]

Register data that has been read by a texbem or texbeml instruction cannot be read later, except by another texbem or texbeml.

// This example demonstrates the validation error caused by
//   t0 being reread
ps_1_1
tex t0
texbem t1, t0
add r0, t1, t0

(Instruction Error) (Statement 4) Register data that has been read by
texbem or texbeml instruction cannot be read by other instructions

Examples

Here is an example shader with the texture maps identified and the texture stages identified.

ps_1_1
tex t0              ; Define t0 to get a 2-tuple DuDv
texbeml t1, t0      ; Compute (u',v')
                    ; Apply luminance correction
                    ; Sample t1 using (u',v')
mov r0, t1          ; Output result

This example requires the following textures in the following texture stages.

  • Stage 0 is assigned a bump map with (du, dv) perturbation data.
  • Stage 1 is assigned a texture map with color data.
  • texbeml sets the matrix data on the texture stage that is sampled. This is different from the functionality of the fixed function pipeline where the perturbation data and the matrices occupy the same texture stage.


texcoord - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

texcoord - ps

Interprets texture coordinate data (UVW1) as color data (RGBA).

Syntax

texcoord dst

where

  • dst is the destination register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texcoord | x | x | x |  |  |  |  |  |

This instruction interprets the texture coordinate set (UVW1) corresponding to the destination register number as color data (RGBA). If the texture coordinate set contains fewer than three components, the missing components are set to 0. The fourth component is always set to 1. All values are clamped between 0 and 1.

The advantage of texcoord is that it provides a way to pass vertex data interpolated at high precision directly into the pixel shader. However, when the data is written into the destination register, some precision will be lost, depending on the number of bits used by the hardware for registers.

No texture is sampled by this instruction. Only texture coordinates set on this texture stage are relevant.

Any texture data (such as position, normal, and light source direction) can be mapped by a vertex shader into a texture coordinate. This is done by associating a texture with a texture register using ID3DXBaseEffect::SetTexture and by specifying how the texture sampling is done using IDirect3DDevice9::SetTextureStageState. If the fixed function pipeline is used, be sure to supply the TSS_TEXCOORDINDEX flag.

This instruction is used as follows:

texcoord tn

An Texture Coordinate Register (tn) contains four color values (RGBA). The data can also be thought of as vector data (xyzw). texcoord will retrieve three of these values (xyz) from texture coordinate set x, and the fourth component (w) is set to 1. The texture address is copied from the texture coordinate set n. The result is clamped between 0 and 1.

This example is for illustration only. The C code accompanying the shader has not been optimized for performance.

Here is an example shader using texcoord.

ps_1_1        ; version instruction
texcoord t0   ; declare t0 hold texture coordinates,
              ; which represent rgba values in this example
mov r0, t0    ; move the color in t0 to output register r0

The rendered output from the pixel shader is shown below. The (u,v,w,1) coordinate values map to the (rgb) channels. The alpha channel is set to 1. At the corners of the image, coordinate (0,0,0,1) is interpreted as black; (1,0,0,1) is red; (0,1,0,1) is green; and (1,1,0,1) contains green and red, producing yellow.

Texture coordinate data

Additional code is required to use this shader and an example scenario is shown below.

// This code creates the shader from a file. The contents of
//   the shader file can also be supplied as a text string.
TCHAR               strPShaderPath[512];
LPD3DXBUFFER        pCode;
DXUtil_FindMediaFile(strPShaderPath, _T("shaderFile.txt"));

// Assemble the vertex shader from the file
D3DXAssembleShaderFromFile(strPShaderPath, 0, NULL, &pCode, NULL);
m_pd3dDevice->CreatePixelShader((DWORD*)pCode->GetBufferPointer(),
                   &m_hPixelShader);
pCode->Release();

// This code defines the object vertex data
struct CUSTOMVERTEX
{
    FLOAT x, y, z;
    FLOAT tu1, tv1;
};

#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_TEX1|TEXCOORD2(0))

static CUSTOMVERTEX g_Vertices[]=
{
    //  x      y     z     u1    v1
    { -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, },
    { +1.0f, -1.0f, 0.0f, 1.0f, 0.0f, },
    { +1.0f, +1.0f, 0.0f, 1.0f, 1.0f, },
    { -1.0f, +1.0f, 0.0f, 0.0f, 1.0f, },
};


texcrd - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

texcrd - ps

Copies texture coordinate data from the source texture coordinate iterator register as color data in the destination register.

Syntax

texcrd dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texcrd |  |  |  | x |  |  |  |  |

This instruction interprets coordinate data as color data (RGBA).

No texture is sampled by this instruction. Only texture coordinates set on this texture stage are relevant.

When using texcrd, keep in mind the following detail about how data is copied from the source register to the destination register. The source texture coordinate register (t#) holds data in the range [-D3DCAPS9.MaxTextureRepeat, D3DCAPS9.MaxTextureRepeat], while the destination register (r#) can hold data only in the (likely smaller) range [-D3DCAPS9.PixelShader1xMaxValue, D3DCAPS9.PixelShader1xMaxValue]. Note that for pixel shader version 1_4, D3DCAPS9.PixelShader1xMaxValue must be a minimum of eight. The texcrd instruction, in the process of clamping source data that is out of range of the destination register, is likely to behave differently on different hardware. The first pixel shader version 1_4 hardware on the market will perform a special clamp for values outside of range. This clamp is designed to produce a number that can fit into the destination register, but also to preserve texture addressing behavior for out-of-range data (see D3DTEXTUREADDRESS) if the data were to be subsequently used for texture sampling. However, new hardware from different manufacturers might not exhibit this behavior and might just chop data to fit the destination register range. Therefore, the safest course of action when using pixel shader version 1_4 texcrd is to supply texture coordinate data only into the pixel shader that is already within the range [-8,8] so that you do not rely on the way hardware clamps.

Unlike texcoord, texcrd does not clamp values between 0 and 1.

Rules for using texcrd:

  1. The same .xyz or .xyw modifier must be applied to every read of an individual t(n) register within a texcrd or texld instruction.
  2. The fourth channel result of texcrd is unset/undefined in all cases.
  3. The third channel is unset/undefined for the xyw_dw case.

Examples

The complete set of allowed syntax for texcrd, taking into account all valid source modifier/selector and destination write mask combinations, is shown below. Note that the .rgba and .xyzw notation can be used interchangeably.

Copies first three channels of texture coordinate iterator register, t(n), into r(m). The fourth channel of r(m) is uninitialized.

texcrd  r(m).rgb, t(n).xyz

// Produces the same result as the previous instruction
texcrd  r(m).rgb, t(n)

Puts first, second, and fourth components of t(n) into first three channels of r(m). The fourth channel of r(m) is uninitialized.

texcrd  r(m).rgb, t(n).xyw

Here is a projective divide example using the _dw modifier.

This example copies x/w and y/w from t(n) into the first two channels of r(m). The third and fourth channels of r(m) are uninitialized. Any data previously written to the third channel of r(m) will be lost. Data in the fourth channel of r(m) is lost due to the phase marker. For version 1_4, the D3DTTFF_PROJECTED flag is ignored.

texcrd  r(m).rg,  t(n)_dw.xyw


texdepth - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

texdepth - ps

Calculate depth values to be used in the depth buffer comparison test for this pixel.

Syntax

texdepth dst

where

  • dst is the destination register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texdepth |  |  |  | x |  |  |  |  |

This instruction uses r5.r / r5.g in the depth buffer comparison test for this pixel. The data in the blue and alpha channels is ignored. If r5.g = 0, the result of r5.r / r5.g = 1.0.

Temporary register r5 is the only register that this instruction can use.

After executing this instruction, temporary register r5 is unavailable for additional use in the shader.

When multisampling, using this instruction eliminates most of the benefit of the higher resolution depth buffer. Because the pixel shader runs once per pixel, the single depth value output by texm3x2depth or texdepth will be used for each of the subpixel depth comparison tests.

Examples

Here is an example using texdepth.

ps_1_4
texld  r0, t0        // Sample texture from texture stage 0 (dest
                     //   register number) into r0
                     // Use texture coordinate data from t0
texcrd r1.rgb, t1    // Load a second set of texture coordinate data into r1
add    r5.rg, r0, r1 // Add the two sets of texture coordinate data
phase                // Phase marker, required when using texdepth instruction
texdepth  r5         // Calculate pixel depth as r5.r / r5.g
                     // Do other color calculations with shader output r0


texdp3 - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

texdp3 - ps

Performs a three-component dot product between data in the texture register number and the texture coordinate set corresponding to the destination register number.

Syntax

texdp3 dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texdp3 |  | x | x |  |  |  |  |  |

Texture registers must use the following sequence.

tex    t(n)        // Define tn as a standard 3-vector (tn must be
                   //   defined in some way before texdp3 uses it)
texdp3 t(m), t(n)  // where m > n
                   // Perform a three-component dot product between tn and
                   //   the texture coordinate set m. The scalar result is
                   //   replicated to all components of t(m)

Here is more detail about how the dot product is accomplished.

The texdp3 instruction performs a three-component dot product and replicates it to all four color channels.

t(m)RGBA = TextureCoordinates(stage m)UVW • t(n)RGB


texdp3tex - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

texdp3tex - ps

Performs a three-component dot product and uses the result to do a 1-D texture lookup.

Syntax

texdp3tex dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texdp3tex |  | x | x |  |  |  |  |  |

Texture registers must use the following sequence.

tex       t(n)        // Define tn as a standard 3-vector (tn must be
                      // defined in some way before texdp3tex uses it)
texdp3tex t(m), t(n)  // where m > n
                      // Perform a three-component dot product between t(n) and
                      // the texture coordinate set m. Use the scalar result to
                      // do a 1-D texture lookup at texturestage m and place
                      // the result in t(m)

Here is more detail about how the dot product and texture lookup are done.

The texdp3tex instruction performs a three-component dot product.

u' = TextureCoordinates(stage m)UVW • t(n)RGB

The result is used to sample the texture at texture stage m by performing a 1-D lookup.

t(m)RGBA = TextureSample(stage m)RGBA using (u',0,0) as coordinates


texkill - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

texkill - ps

Cancels rendering of the current pixel if any of the first three components (UVW) of the texture coordinates is less than zero.

Syntax

texkill src

where

  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texkill | x | x | x | x | x | x | x | x | x

texkill does not sample any texture. It operates on the first three components of the texture coordinates given by the source register number. For ps_1_4, texkill operates on the data in the first three components of the source register.

You can use this instruction to implement arbitrary clip planes in the rasterizer.

When using vertex shaders, the application is responsible for applying the perspective transform. This can cause problems for the arbitrary clipping planes because if it contains anisomorphic scale factors, the clip planes need to be transformed as well. Therefore, it is best to provide an unprojected vertex position to use in the arbitrary clipper, which is the texture coordinate set identified by the texkill operator.

This instruction is used as follows:

texkill tn

// The pixel masking is accomplished as follows:
if ( the x,y,z components of TextureCoordinates(stage n)UVWQ < 0 )
  cancel pixel render

For pixel shader 1_1, 1_2, and 1_3, texkill operates on the texture coordinate set given by the source register number. In version 1_4, however, texkill operates on the data contained in the Texture Coordinate Register (tn) or in the temporary register (rn) that has been specified as the source.

When multisampling is enabled, any antialiasing effect achieved on polygon edges due to multisampling will not be achieved along any edge that has been generated by texkill. The pixel shader runs once per pixel.

This example is for illustration only.

This example masks out pixels that have negative texture coordinates. The pixel colors are interpolated from vertex colors provided in the vertex data.

ps_1_1       // Version instruction
texkill t0   // Mask out pixel using texture coordinates from stage 0
mov r0, v0   // Move the diffuse color in v0 to r0

// The rendered output from the pixel shader is shown below

The texture coordinates range from -0.5 to 0.5 in u, and 0.0 to 1.0 in v. This instruction causes the negative u values get masked out. The first image shows the vertex color applied to the quad without the texkill instruction applied. The second image shows the result of the texkill instruction. The pixel colors from the texture coordinates below 0 (where x goes from -0.5 to 0.0) are masked out. The background color (white) is used where the pixel color is masked.

Vertex color applied to the quad without the texkill instruction Output with the texkill instruction applied

The texture coordinate data is declared in the vertex data declaration in this example.

struct CUSTOMVERTEX
{
    FLOAT x, y, z;
    DWORD color;
    FLOAT tu1, tv1;
};

#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1|D3DTEXCOORD2(0))

static CUSTOMVERTEX g_Vertices[]=
{
    //  x      y     z    color         u1,    v1
    { -1.0f, -1.0f, 0.0f, 0xffff0000, -0.5f,  1.0f, },
    {  1.0f, -1.0f, 0.0f, 0xff00ff00,  0.5f,  1.0f, },
    {  1.0f,  1.0f, 0.0f, 0xff0000ff,  0.5f,  0.0f, },
    { -1.0f,  1.0f, 0.0f, 0xffffffff, -0.5f,  0.0f, },

};


texld - ps_1_4
Microsoft DirectX 9.0 SDK Update (October 2004)

texld - ps_1_4

Loads the destination register with color data (RGBA) sampled using the contents of the source register as texture coordinates. The sampled texture is the texture associated with the destination register number.

texld dst, src

Registers

Argument | Description | Registers |  |  |  | Version
 |  | vn | cn | tn | rn
dst | Destination register |  |  |  | x | 1_4
src | Source register |  |  | x |  | 1_4 phase 1
 |  |  |  | x | x | 1_4 phase

When using r(n) as a source register, the first three components (XYZ) must have been initialized in the previous phase of the shader.

To learn more about registers, see ps_1_X Registers.

Remarks

This instruction samples the texture in the texture stage associated with the destination register number. The texture is sampled using texture coordinate data from the source register.

The syntax for the texld and texcrd instructions expose support for a projective divide with a Texture Register Modifier. For pixel shader version 1.4, the D3DTTFF_PROJECTED texture transform flag is always ignored.

Rules for using texld:

  1. The same .xyz or .xyw modifier must be applied to every read of an individual t(n) register within both texcrd or texld instructions. If .xyw is being used on t(n) register reads, this can be mixed with other reads of the same t(n) register using .xyw_dw.
  2. The _dz source modifier is only valid on texld with r(n) source register (thus phase 2 only).
  3. The _dz source modifier may be used no more than two times per shader.
Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texld |  |  |  | x |  |  |  |  |

Examples

The texld instruction offers some control over which components of the source texture coordinate data are used. The complete set of allowed syntax for texld follows, and includes all valid source register modifiers, selectors, and write mask combinations.

texld  r(m), t(n).xyz
// Uses xyz from t(n) to sample 1-D, 2-D, or 3-D texture

texld  r(m), t(n)
// Same as previous

texld  r(m), t(n).xyw
// Uses xyw (skipping z) from t(n) to sample 1-D, 2-D or 3-D texture

texld  r(m), t(n)_dw.xyw
// Samples 1-D or 2-D texture at x/w, y/w from t(n). The result
// is undefined for a cube-map lookup.

texld  r(m), r(n).xyz
// Samples 1-D, 2-D, or 3-D texture at xyz from r(m)
// This is possible in the second phase of the shader

texld  r(m), r(n)
// Same as previous

texld  r(m), r(n)_dz.xyz
// Samples 1-D or 2-D texture at x/z, y/z from r(m)
// Possible only in second phase
// The result is undefined for a cube-map lookup

texld  r(n), r(n)_dz
// Same as previous


texld - ps_2_0 and up
Microsoft DirectX 9.0 SDK Update (October 2004)

texld - ps_2_0 and up

Sample a texture at a particular sampler, using provided texture coordinates. This instruction is different from the texld instruction used in pixel shader version 1_4.

Syntax

texld dst, src0, src1

Where:

  • dst is a destination register.
  • src0 is a source register that provides the texture coordinates for the texture sample.
  • src1 identifies the Sampler (s#), where # specifies which texture sampler number to sample. The sampler has associated with it a texture and a sampler state defined by D3DSAMPLERSTATETYPE.

ps_2_0 and ps_2_x

dst must be a Temporary Register (r#) and only .xyzw mask (default mask) is allowed.

src0 must be either a Texture Coordinate Register (t#) or a Temporary Register (r#), with no modifier or swizzle.

src1 must be a Sampler (s#), with no modifier or swizzle.

If the D3DPS20CAPS_NODEPENDENTREADLIMIT cap bit is not set (in D3DPSHADERCAPS2_0), a given texture instruction (texld, texldp, texldb, texldd) may be dependent upon, at most, third order. A first-order dependent texture instruction is a texture instruction in which either:

  • src0 is a Temporary Register (r#).
  • dst was previously written, now being written again.

A second-order dependent texture instruction is defined as a texture instruction that reads or writes to a Temporary Register (r#) whose contents, before executing the texture instruction, depend (perhaps indirectly) on the outcome of a first-order dependent texture instruction. An (n)th-order dependent texture instruction derives from an (n - 1)th-order texture instruction.

ps_3_0

src1 must be a Sampler (s#), with no modifier. Swizzle is allowed on src1, and when applied, the texture lookup results are pre-swizzled before written to dst.

Remarks

This instruction is supported in the following versions:

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texld |  |  |  |  | x | x | x | x | x

The number of coordinates required for src0 to perform the texture sample depends on how src1 was declared, plus the .w component. Sampler types are declared with dcl_samplerType. If src1 is declared as a 2-D sampler, then src0 must contain .xy coordinates; if src1 is declared as either a cube sampler or a volume sampler, then src0 must contain .xyz coordinates. Sampling a texture with fewer dimensions than are present in the texture coordinate is allowed since the extra texture coordinate component(s) are ignored.

If the source texture contains fewer than four components, defaults are placed in the missing components. Defaults depend on the texture format as shown in the following table:

Texture Format | Default Values
D3DFMT_R5G6B5, D3DFMT_R8G8B8, D3DFMT_L8, D3DFMT_L16, D3DFMT_R3G3B2, D3DFMT_CxV8U8, D3DFMT_L6V5U5 | A = 1.0
D3DFMT_V8U8, D3DFMT_V16U16, D3DFMT_G16R16, D3DFMT_G16R16F, D3DFMT_G32R32F | B = A = 1.0
D3DFMT_A8 | R = G = B = 0.0
D3DFMT_R16F, D3DFMT_R32F | G = B = A = 1.0
All depth/stencil formats | R = B = 0.0, A = 1.0


texldb - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

texldb - ps

Biased texture load instruction. This instruction uses the fourth element (.a or .w) to bias the texture-sampling level of detail (LOD) just before sampling.

Syntax

texldb dst, src0, src1

Where:

  • dst is the destination register.
  • src0 is a source register that provides the texture coordinates for the texture sample. See Texture Coordinate Register.
  • src1 identifies the Sampler (s#), where # specifies which texture sampler number to sample. The sampler has associated with it a texture and a sampler state defined by D3DSAMPLERSTATETYPE.

For the restrictions when using texldb, see the texld instruction.

ps_2_0 and ps_2_x

dst must be a Temporary Register (r#) and only .xyzw mask (default mask) is allowed.

src0 must be either a Texture Coordinate Register (t#) or a Temporary Register (r#), with no modifier or swizzle.

src1 must be a Sampler (s#), with no modifier or swizzle.

If the D3DPS20CAPS_NODEPENDENTREADLIMIT cap bit is not set (in D3DPSHADERCAPS2_0), a given texture instruction (texld, texldp, texldb, texldd) may be dependent upon, at most, third order. A first-order dependent texture instruction is a texture instruction in which either:

  • src0 is a Temporary Register (r#).
  • dst was previously written, now being written again.

A second-order dependent texture instruction is defined as a texture instruction that reads or writes to a Temporary Register (r#) whose contents, before executing the texture instruction, depend (perhaps indirectly) on the outcome of a first-order dependent texture instruction. An (n)th-order dependent texture instruction derives from an (n - 1)th-order texture instruction.

ps_3_0

src1 must be a Sampler (s#), with no modifier. Swizzle is allowed on src1, and when applied, the texture lookup results are pre-swizzled before written to dst.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texldb |  |  |  |  | x | x | x | x | x

texldb biases the mipmap LOD, computed normally as part of the sample process by the (signed) value in src0.w. Positive bias values will result in smaller mipmaps being selected and vice versa. For ps_2_0 and ps_2_x, bias values can be within the range [-3.0, +3.0]. For ps_3_0, bias values can be within the range [-16.0, +15.0]. Bias values outside these ranges produce undefined results. The sampler state D3DSAMP_MIPMAPLODBIAS is still honored, and the texldb bias is added to this, but on a per-pixel basis. After the biased LOD is computed, D3DSAMP_MAXMIPLEVEL is still honored and the texture sample occurs. After texldb, the contents of src0 are unaffected (unless dst is the same register).

The number of coordinates required for src0 to perform the texture sample depends on how src1 was declared, plus the .w component. Sampler types are declared with dcl_samplerType. If src1 is declared as a 2-D sampler, then src0 must contain .xyw coordinates; if src1 is declared as either a cube sampler or a volume sampler, then src0 must contain .xyzw coordinates. Sampling a 2-D texture with .xyzw coordinates is allowed (the .z coordinate is ignored).

If the source texture contains fewer than four components, defaults are placed in the missing components. Defaults depend on the texture format as shown in the following table:

Texture Format | Default Values
D3DFMT_R5G6B5, D3DFMT_R8G8B8, D3DFMT_L8, D3DFMT_L16, D3DFMT_R3G3B2, D3DFMT_CxV8U8, D3DFMT_L6V5U5 | A = 1.0
D3DFMT_V8U8, D3DFMT_V16U16, D3DFMT_G16R16, D3DFMT_G16R16F, D3DFMT_G32R32F | B = A = 1.0
D3DFMT_A8 | R = G = B = 0.0
D3DFMT_R16F, D3DFMT_R32F | G = B = A = 1.0
All depth/stencil formats | R = B = 0.0, A = 1.0


texldd - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

texldd - ps

Samples a texture with additional gradient inputs.

Syntax

texldd, dst, src0, src1, src2, src3

Where:

  • dst is a destination register.
  • src0 is a source register that provides the texture coordinates for the texture sample. See Texture Coordinate Register.
  • src1 identifies the source sampler register (s#), where # specifies which texture sampler number to sample. The sampler has associated with it a texture and a control state defined by the D3DSAMPLERSTATETYPE enumeration (ex. D3DSAMP_MINFILTER).
  • src2 is an input source register that specifies the x gradient.
  • src3 is an input source register that specifies the y gradient.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texldd |  |  |  |  |  | x * | x | x | x

* This instruction is only supported by ps_2_a. It is not supported by ps_2_b. For more information about profiles, see D3DXGetPixelShaderProfile.

This instruction samples a texture using the texture coordinates at src0, the sampler specified by src1, and the gradients DSX and DSY coming from src2 and src3. The x and y gradient values are used to select the appropriate mipmap level of the texture for sampling.

All sources support arbitrary swizzles.

All write masks are valid on the destination.


texldl - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

texldl - ps

Sample a texture with a particular sampler. The particular mipmap level of detail (LOD) being sampled has to be specified as the fourth component of the texture coordinate.

Syntax

texldl dst, src0, src1

Where:

  • dst is a destination register.
  • src0 is a source register that provides the texture coordinates for the texture sample. See Texture Coordinate Register.
  • src1 identifies the source sampler register (s#), where # specifies which texture sampler number to sample. The sampler has associated with it a texture and a control state defined by the D3DSAMPLERSTATETYPE enumeration (for example, D3DSAMP_MINFILTER).

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texldl |  |  |  |  |  |  |  | x | x

texldl looks up the texture set at the sampler stage referenced by src1. The LOD is selected from src0.w. This value can be negative in which case the LOD selected is the zeroth one (biggest map) with the MAGFILTER. Since src0.w is a floating point value, the fractional value is used to interpolate (if MIPFILTER is LINEAR) between two mip levels. Sampler states MIPMAPLODBIAS and MAXMIPLEVEL are honored. For more information about sampler states, see D3DSAMPLERSTATETYPE.

If a shader program samples from a sampler that does not have a texture set, then 0001 is obtained in the destination register.

The following is a rough algorithm that the reference device follows:

LOD = src0.w + LODBIAS;
if (LOD <= 0 )
{
   LOD = 0;
   Filter = MagFilter;
   tex = Lookup( MAX(MAXMIPLEVEL, LOD), Filter );
}
else
{
   Filter = MinFilter;
   LOD = MAX( MAXMIPLEVEL, LOD );
   tex = Lookup( Floor(LOD), Filter );
   if( MipFilter == LINEAR )
   {
      tex1 = Lookup( Ceil(LOD), Filter );
      tex = (1 - frac(src0.w))*tex + frac(src0.w)*tex1;
   }
}

Restrictions:

  • The texture coordinates should not be scaled by texture size.
  • dst must be a Temporary Register (r#).
  • dst can accept a writemask. See Destination Register Write Mask.
  • Defaults for missing components are either 0 or 1, and depend on the texture format.
  • src1 must be a Sampler (s#). src1 may not use a negate modifier (see Pixel Shader Source Register Modifiers). src1 may use swizzle (see Source Register Swizzling), which is applied after sampling, but before the write mask (see Destination Register Write Mask) is honored. The sampler must have been declared (using dcl_samplerType) at the beginning of the shader.
  • The number of coordinates required to perform the texture sample depends on how the sampler was declared. If it was declared as a cube, a three-component texture coordinate is required (.rgb). Validation enforces that coordinates provided to tex_ldl are sufficient for the texture dimension declared for the sampler. However, it is not guaranteed that the application actually sets a texture (through the application programming interface (API)) with dimensions equal to the dimension declared for the sampler. In such a case, the runtime will attempt to detect mismatches (possibly in debug only). Sampling a texture with fewer dimensions than are present in the texture coordinate will be allowed and assumed to ignore the extra texture coordinate components. Conversely, sampling a texture with more dimensions than are present in the texture coordinate is illegal.
  • If the src0 (texture coordinate) is Temporary Register, the components required for the lookup (described above) must have been previously written.
  • Sampling unsigned RGB textures will result in float values between 0.0 and 1.0.
  • Sampling signed textures will result in float values between -1.0 to 1.0.
  • When sampling floating-point textures, Float16 means that the data will range within MAX_FLOAT16. Float32 means the maximum range of the pipeline will be used. Sampling outside of either range is undefined.
  • There is no dependent read limit.


texldp - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

texldp - ps

Projected texture load instruction. This instruction divides the input texture coordinate by the fourth element (.a or .w) just before sampling.

Syntax

texldp dst, src0, src1

where

  • dst is the destination register.
  • src0 is a source register that provides the texture coordinates for the texture sample. See Texture Coordinate Register.
  • src1 identifies the Sampler (s#), where # specifies which texture sampler number to sample. The sampler has associated with it a texture and a sampler state defined by D3DSAMPLERSTATETYPE.

For the set of restrictions when using texldp, see texld.

Remarks

texldp performs projection on the coordinates read from src0 before performing the sample. Each texture coordinate is divided by src0.w, then the texture is sampled. When texldp completes, the contents of src0 are unaffected (unless dst is the same register). An alternative to using texldp is to manually perform the projection division in the shader. However, performing the division in shader code is usually slower than when performed by the texldp instruction, so avoid such additional math when possible.

The number of coordinates required for src0 to perform the texture sample depends on how src1 was declared, plus the .w component. Sampler types are declared with dcl_samplerType. If src1 is declared as a 2-D sampler, then src0 must contain .xyw coordinates; if src1 is declared as either a cube sampler or a volume sampler, then src0 must contain .xyzw coordinates. Sampling a 2-D texture with .xyzw coordinates is allowed (the .z coordinate is ignored).

If the source texture contains fewer than four components, defaults are placed in the missing components. Defaults depend on the texture format as shown in the following table.

Texture Format | Default Values for missing components
D3DFMT_R5G6B5, D3DFMT_R8G8B8, D3DFMT_L8, D3DFMT_L16, D3DFMT_R3G3B2, D3DFMT_CxV8U8, D3DFMT_L6V5U5 | A = 1.0
D3DFMT_V8U8, D3DFMT_V16U16, D3DFMT_G16R16, D3DFMT_G16R16F, D3DFMT_G32R32F | B = A = 1.0
D3DFMT_A8 | R = G = B = 0.0
D3DFMT_R16F, D3DFMT_R32F | G = B = A = 1.0
All depth/stencil formats | R = B = 0.0, A = 1.0

This instruction is supported in the following versions:

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texldp |  |  |  |  | x | x | x | x | x

ps_2_0 and ps_2_x

dst must be a Temporary Register (r#) and only .xyzw mask (default mask) is allowed.

src0 must be either a Texture Coordinate Register (t#) or a Temporary Register (r#), with no modifier or swizzle.

src1 must be a Sampler (s#), with no modifier or swizzle.

If the D3DPS20CAPS_NODEPENDENTREADLIMIT cap bit is not set (in D3DPSHADERCAPS2_0), a given texture instruction (texld, texldp, texldb, texldd) may be dependent upon, at most, third order. A first-order dependent texture instruction is a texture instruction in which either:

  • src0 is a Temporary Register (r#)
  • dst was previously written, now being written again.

A second-order dependent texture instruction is defined as a texture instruction that reads or writes to a Temporary Register (r#) whose contents, before executing the texture instruction, depend (perhaps indirectly) on the outcome of a first-order dependent texture instruction. An (n)th-order dependent texture instruction derives from an (n - 1)th-order texture instruction.

ps_3_0

For ps_3_0, src1 must be a Sampler (s#), with no modifier. Swizzle is allowed on src1, and when applied, the texture lookup results are pre-swizzled before written to dst.


texm3x2depth - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

texm3x2depth - ps

Calculate the depth value to be used in depth testing for this pixel.

Syntax

texm3x2depth dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texm3x2depth |  |  | x |  |  |  |  |  |

This instruction must be used with the texm3x2pad instruction.

When using these two instructions, texture registers must use the following sequence.

tex t(n)                     // Define tn as a standard 3-vector.(tn must be
                             // defined in some way before it is used
texm3x2pad   t(m),   t(n)    // Where m > n
                             // Calculate z value
texm3x2depth t(m+1), t(n)    // Calculate w value; use both z and w to
                             // find depth

The depth calculation is done after using a dot product operation to find z and w. Here is more detail about how the depth calculation is accomplished.

The texm3x2pad instruction calculates z.

z = TextureCoordinates(stage m)UVW • t(n)RGB

The texm3x2depth instruction calculates w.

w = TextureCoordinates(stage m+1)UVW • t(n)RGB

Calculate depth and store the result in t(m+1).

if (w == 0)
  t(m+1) = 1.0
else
  t(m+1) = z/w

The calculated depth is tagged to be used in the depth test for the pixel, replacing the existing depth test value for the pixel.

Be sure to clamp z/w to be in the range of (0-1). If z/w is outside this range, the result stored in the depth buffer will be undefined.

After running tex3x2depth, register t(m+1) is no longer available for use in the shader.

When multisampling, using this instruction eliminates most of the benefit of the higher resolution depth buffer. Because the pixel shader runs once per pixel, the single depth value output by texm3x2depth or texdepth will be used for each of the subpixel depth comparison tests.


texm3x2pad - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

texm3x2pad - ps

Performs the first row multiplication of a two-row matrix multiply. This instruction must be combined with either texm3x2tex or texm3x2depth. Refer to either of these instructions for details on using texmpad.

Syntax

tex3x2pad dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texm3x2pad | x | x | x |  |  |  |  |  |

This instruction cannot be used by itself.


texm3x2tex - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

texm3x2tex - ps

Performs the final row of a 3x2 matrix multiply and uses the result to do a texture lookup. texm3x2tex must be used in conjunction with the texm3x2pad instruction.

Syntax

texm3x2tex dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texm3x2tex | x | x | x |  |  |  |  |  |

The instruction is used as one of two instructions representing a 3x2 matrix multiply operation. This instruction must be used with the texm3x2pad instruction.

When using these two instructions, texture registers must use the following sequence.

tex t(n)                      // Define tn as a standard 3-vector (tn must
                              // be defined in some way before it is used)
texm3x2pad  t(m),   t(n)      // where m > n
                              // Perform first row of matrix multiply
texm3x2tex  t(m+1), t(n)      // Perform second row of matrix multiply
                              // to get (u,v) to sample texture
                              // associated with stage m+1

Here is more detail about how the 3x2 multiply is accomplished.

The texm3x2pad instruction performs the first row of the multiply to find u'.

u' = t(n)RGB * TextureCoordinates(stage m)UVW

The texm3x2tex instruction performs the second row of the multiply to find v'.

v' = t(n)RGB * TextureCoordinates(stage m+1)UVW

The texm3x2tex instruction samples the texture on stage (m+1) with (u',v') and stores the result in t(m+1).

t(m+1)RGB = TextureSample(stage m+1)RGB using (u', v') as coordinates

Examples

Here is an example shader with the texture maps and the texture stages identified.

ps_1_1
tex t0                // Bind texture in stage 0 to register t0
texm3x2pad  t1,  t0   // First row of matrix multiply
texm3x2tex  t2,  t0   // Second row of matrix multiply to get (u,v)
                      // with which to sample texture in stage 2
mov r0, t2            // Output result

This example requires the following textures in the following texture stages.

  • Stage 0 takes a map with (x,y,z) perturbation data.
  • Stage 1 holds texture coordinates. No texture is required in the texture stage.
  • Stage 2 holds both texture coordinates as well as a 2-D texture set at that texture stage.


texm3x3 - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

texm3x3 - ps

Performs a 3x3 matrix multiply when used in conjunction with two texm3x3pad instructions.

Syntax

texm3x3 dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texm3x3 |  | x | x |  |  |  |  |  |

This instruction is the same as the texm3x3tex instruction, without the texture lookup.

This instruction is used as the final of three instructions representing a 3x3 matrix multiply operation. The 3x3 matrix is comprised of the texture coordinates of the third texture stage, and by the two preceding texture stages. Any texture assigned to any of the three texture stages is ignored.

This instruction must be used with two texm3x3pad instructions. Texture registers must follow the following sequence.

tex t(n)                 // Define tn as a standard 3-vector (tn must
                         // be defined in some way before it is used)
texm3x3pad t(m),   t(n)  // where m > n
                         // Perform first row of matrix multiply
texm3x3pad t(m+1), t(n)  // Perform second row of matrix multiply
texm3x3    t(m+2), t(n)  // Perform third row of matrix multiply to get a
                         // 3-vector result

Here is more detail about how the 3x3 multiply is accomplished.

The first texm3x3pad instruction performs the first row of the multiply to find u'.

u' = TextureCoordinates(stage m)UVW * t(n)RGB

The second texm3x3pad instruction performs the second row of the multiply to find v'.

v' = TextureCoordinates(stage m+1)UVW * t(n)RGB

The texm3x3tex instruction performs the third row of the multiply to find w'.

w' = TextureCoordinates(stage m+2)UVW * t(n)RGB

Place the result of the matrix multiply in the destination register.

t(m+2)RGBA = (u', v', w', 1)


texm3x3pad - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

texm3x3pad - ps

Performs the first or second row multiply of a three-row matrix multiply. This instruction must be used in combination with texm3x3, texm3x3spec, texm3x3vspec, or texm3x3tex.

Syntax

texm3x3pad dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texm3x3pad | x | x | x |  |  |  |  |  |

This instruction cannot be used by itself.


texm3x3spec - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

texm3x3spec - ps

Performs a 3x3 matrix multiply and uses the result to perform a texture lookup. This can be used for specular reflection and environment mapping. texm3x3spec must be used in conjunction with two texm3x3pad instructions.

Syntax

texm3x3spec dst, src0, src1

where

  • dst is the destination register.
  • src0 and src1 are source registers.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texm3x3spec | x | x | x |  |  |  |  |  |

This instruction performs the final row of a 3x3 matrix multiply, uses the resulting vector as a normal vector to reflect an eye-ray vector, and then uses the reflected vector to perform a texture lookup. The shader reads the eye-ray vector from a constant register. The 3x3 matrix multiply is typically useful for orienting a normal vector to the correct tangent space for the surface being rendered.

The 3x3 matrix is comprised of the texture coordinates of the third texture stage and the two preceding texture stages. The resulting post reflection vector (u,v,w) is used to sample the texture on the final texture stage. Any texture assigned to the preceding two texture stages is ignored.

This instruction must be used with two texm3x3pad instructions. Texture registers must use the following sequence.

tex t(n)                      // Define tn as a standard 3-vector (tn must
                              //   be defined in some way before it is used)
texm3x3pad t(m),   t(n)       //   where m > n
                              // Perform first row of matrix multiply
texm3x3pad  t(m+1), t(n)      // Perform second row of matrix multiply
texm3x3spec t(m+2), t(n), c0  // Perform third row of matrix multiply
                              // Then do a texture lookup on the texture
                              //   associated with texture stage m+2

The first texm3x3pad instruction performs the first row of the multiply to find u'.

u' = TextureCoordinates(stage m)UVW * t(n)RGB

The second texm3x3pad instruction performs the second row of the multiply to find v'.

v' = TextureCoordinates(stage m+1)UVW * t(n)RGB

The texm3x3spec instruction performs the third row of the multiply to find w'.

w' = TextureCoordinates(stage m+2)UVW * t(n)RGB

The texm3x3spec instruction then does a reflection calculation.

(u'', v'', w'') = 2*[(N*E)/(N*N)]*N - E
// where the normal N is given by
//   N = (u', v', w')
//   and the eye-ray vector E is given by the constant register
//   E = c# (Any constant register--c0, c1, c2, etc.--can be used)

Lastly, the texm3x3spec instruction samples t(m+2) with (u'',v'',w'') and stores the result in t(m+2).

t(m+2)RGBA = TextureSample(stage m+2)RGBA using (u'', v'', w'') as coordinates

Examples

Here is an example shader with the texture maps and the texture stages identified.

ps_1_1
tex t0                    // Bind texture in stage 0 to register t0 (tn must
                          //   be defined in some way before it is used)
texm3x3pad  t1,  t0       // First row of matrix multiply
texm3x3pad  t2,  t0       // Second row of matrix multiply
texm3x3spec t3,  t0,  c#  // Third row of matrix multiply to get a 3-vector
                          // Reflect 3-vector by the eye-ray vector in c#
                          // Use reflected vector to lookup texture in
                          //   stage 3
mov r0, t3                // Output the result

This example requires the following texture stage setup.

  • Stage 0 is assigned a texture map with normal data. This is often referred to as a bump map. The data is (XYZ) normals for each texel. Texture coordinates at stage n defines where to sample this normal map.
  • Texture coordinate set m is assigned to row 1 of the 3x3 matrix. Any texture assigned to stage m is ignored.
  • Texture coordinate set m+1 is assigned to row 2 of the 3x3 matrix. Any texture assigned to stage m+1 is ignored.
  • Texture coordinate set m+2 is assigned to row 3 of the 3x3 matrix. Stage m+2 is assigned a volume or cube texture map. The texture provides color data (RGBA).
  • The eye-ray vector E is given by a constant register E = c#.


texm3x3tex - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

texm3x3tex - ps

Performs a 3x3 matrix multiply and uses the result to do a texture lookup. texm3x3tex must be used with two texm3x3pad instructions.

Syntax

texm3x3tex dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texm3x3tex | x | x | x |  |  |  |  |  |

This instruction is used as the final of three instructions representing a 3x3 matrix multiply operation, followed by a texture lookup. The 3x3 matrix is comprised of the texture coordinates of the third texture stage and the two preceding texture stages. The resulting three-component vector (u,v,w) is used to sample the texture in stage 3. Any texture assigned to the preceding two texture stages is ignored. The 3x3 matrix multiply is typically useful for orienting a normal vector to the correct tangent space for the surface being rendered.

This instruction must be used with the texm3x3pad instruction. Texture registers must use the following sequence.

tex t(n)                 // Define tn as a standard 3-vector (tn must
                         //   be defined in some way before it is used)
texm3x3pad t(m),   t(n)  //   where m > n
                         // Perform first row of matrix multiply
texm3x3pad t(m+1), t(n)  // Perform second row of matrix multiply
texm3x3tex t(m+2), t(n)  // Perform third row of matrix multiply to get a
                         //   3-vector with which to sample texture
                         //   associated with texture stage m+2

Here is more detail about how the 3x3 multiply is accomplished.

The first texm3x3pad instruction performs the first row of the multiply to find u'.

u' = TextureCoordinates(stage m)UVW * t(n)RGB

The second texm3x3pad instruction performs the second row of the multiply to find v'.

v' = TextureCoordinates(stage m+1)UVW * t(n)RGB

The texm3x3spec instruction performs the third row of the multiply to find w'.

w' = TextureCoordinates(stage m+2)UVW * t(n)RGB

Lastly, the texm3x3tex instruction samples t(m+2) with (u',v',w') and stores the result in t(m+2).

t(m+2)RGBA = TextureSample(stage m+2)RGBA using (u', v', w') as coordinates.

Examples

Here is an example shader with the texture maps identified and the texture stages identified.

ps_1_1
tex t0                // Bind texture in stage 0 to register t0
texm3x3pad  t1,  t0   // First row of matrix multiply
texm3x3pad  t2,  t0   // Second row of matrix multiply
texm3x3tex  t3,  t0   // Third row of matrix multiply to get a
                      // 3-vector with which to sample texture at
mov r0, t3            // stage 3 output result

This example requires the following texture stage setup.

  • Stage 0 is assigned a texture map with normal data. This is often referred to as a bump map. The data is (XYZ) normals for each texel. Texture coordinate set 0 defines how to sample this normal map.
  • Texture coordinate set 1 is assigned to row 1 of the 3x3 matrix. Any texture assigned to stage 1 is ignored.
  • Texture coordinate set 2 is assigned to row 2 of the 3x3 matrix. Any texture assigned to stage 2 is ignored.
  • Texture coordinate set 3 is assigned to row 3 of the 3x3 matrix. A volume or cube texture should be set to stage 3 for lookup by the transformed 3-D vector.


texm3x3vspec - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

texm3x3vspec - ps

Performs a 3x3 matrix multiply and uses the result to perform a texture lookup. This can be used for specular reflection and environment mapping where the eye-ray vector is not constant. texm3x3vspec must be used in conjunction with two texm3x3pad instructions. If the eye-ray vector is constant, the texm3x3spec instruction will perform the same matrix multiply and texture lookup.

Syntax

texm3x3vspec dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texm3x3vspec | x | x | x |  |  |  |  |  |

This instruction performs the final row of a 3x3 matrix multiply operation, interprets the resulting vector as a normal vector to reflect an eye-ray vector, and then uses the reflected vector as a texture address for a texture lookup. It works just like texm3x3spec, except that the eye-ray vector is taken from the fourth component of the texture coordinates. The 3x3 matrix multiply is typically useful for orienting a normal vector to the correct tangent space for the surface being rendered.

The 3x3 matrix is comprised of the texture coordinates of the third texture stage and the two preceding texture stages. The resulting post-reflection vector (UVW) is used to sample the texture in stage 3. Any texture assigned to the preceding two texture stages is ignored.

This instruction must be used with the texm3x3pad instruction. Texture registers must use the following sequence.

tex t(n)                    // Define tn as a standard 3-vector (tn must
                            //   be defined in some way before it is used)
texm3x3pad   t(m),   t(n)   // where m > n
                            // Perform first row of matrix multiply
texm3x3pad   t(m+1), t(n)   // Perform second row of matrix multiply
texm3x3vspec t(m+2), t(n)   // Perform third row of matrix multiply
                            // Then do a texture lookup on the texture
                            // associated with texture stage m+2

The first texm3x3pad instruction performs the first row of the multiply to find u'.

u' = TextureCoordinates(stage m)UVW * t(n)RGB

The second texm3x3pad instruction performs the second row of the multiply to find v'.

v' = TextureCoordinates(stage m+1)UVW * t(n)RGB

The texm3x3spec instruction performs the third row of the multiply to find w'.

w' = TextureCoordinates(stage m+2)UVW * t(n)RGB

The texm3x3vspec instruction also does a reflection calculation.

(u'', v'', w'') = 2*[(N*E)/(N*N)]*N - E
// where the normal N is given by
// N = (u', v', w')
// and the eye-ray vector E is given by
// E = (TextureCoordinates(stage m)Q,
//      TextureCoordinates(stage m+1)Q,
//      TextureCoordinates(stage m+2)Q)

Lastly, the texm3x3vspec instruction samples t(m+2) with (u'',v'',w'')and stores the result in t(m+2).

t(m+2)RGBA = TextureSample(stage m+2)RGBA
  using (u'', v'', w'') as coordinates

Examples

Here is an example shader with the texture maps identified and the texture stages identified.

ps_1_1
tex t0                // Bind texture in stage 0 to register t0
texm3x3pad   t1,  t0  // First row of matrix multiply
texm3x3pad   t2,  t0  // Second row of matrix multiply
texm3x3vspec t3,  t0  // Third row of matrix multiply to get a 3-vector
                      // Reflect 3-vector by the eye-ray vector
                      // Use reflected vector to do a texture lookup
                      //   at stage 3
mov r0, t3            // Output the result

This example requires the following texture stage setup.

  • Stage 0 is assigned a texture map with normal data. This is often referred to as a bump map. The data is (XYZ) normals for each texel. Texture coordinates at stage n defines how to sample this normal map.
  • Texture coordinate set m is assigned to row 1 of the 3x3 matrix. Any texture assigned to stage m is ignored.
  • Texture coordinate set m+1 is assigned to row 2 of the 3x3 matrix. Any texture assigned to stage m+1 is ignored.
  • Texture coordinate set m+2 is assigned to row 3 of the 3x3 matrix. Stage m+2 is assigned a volume or cube texture map. The texture provides color data (RGBA).
  • The eye-ray vector E is passed into the instruction in the fourth component (q) of the texture coordinate data at stages m, m+1, and m+2.


texreg2ar - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

texreg2ar - ps

Interprets the alpha and red color components of the source register as texture address data (u,v) to sample the texture at the stage corresponding to the destination register number. The result is stored in the destination register.

Syntax

texreg2ar dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texreg2ar | x | x | x |  |  |  |  |  |

This instruction is useful for color-space remapping operations.

Here is an example of the sequence the instruction follows.

tex t(n)
texreg2ar t(m), t(n)     where m > n

// The first instruction loads the texture color (RGBA)
// into register tn
tex tn
// The second instruction remaps the color
t(m)RGBA = TextureSample(stage m)RGBA using t(n)AR as coordinates

_bx2 cannot be used on the src register for texreg2ar or texreg2gb instructions.

For this instruction, the source register must use unsigned data. Use of signed or mixed data in the source register will produce undefined results. For more information, see D3DFORMAT.


texreg2gb - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

texreg2gb - ps

Interprets the green and blue color components of the source register as texture address data to sample the texture at the stage corresponding to the destination register number.

Syntax

texreg2gb dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texreg2gb |  | x | x |  |  |  |  |  |

This instruction is useful for color-space remapping operations.

Here is an example of the sequence the instruction follows.

// Here is an example of the sequence the instruction follows
tex t(n)
texreg2gb t(m), t(n)     where m > n

// The first instruction loads the texture color (RGBA)
// into register tn
tex tn
// The second instruction remaps the color
t(m)RGBA = TextureSample(stage m)RGBA using t(n)GB as coordinates

_bx2 cannot be used on the src register for texreg2ar or texreg2gb instructions.

For this instruction, the source register must use unsigned data. Use of signed or mixed data in the source register will produce undefined results. For more information, see D3DFORMAT.


texreg2rgb - ps
Microsoft DirectX 9.0 SDK Update (October 2004)

texreg2rgb - ps

Interprets the red, green, and blue (RGB) color components of the source register as texture address data in order to sample the texture at the stage corresponding to the destination register number. The result is stored in the destination register.

Syntax

texreg2rgb dst, src

where

  • dst is the destination register.
  • src is a source register.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
texreg2rgb |  | x | x |  |  |  |  |  |

This instruction is useful for color-space remapping operations. It supports two-dimensional (2-D) and three-dimensional (3-D) coordinates. It can be used just like the texreg2ar or texreg2gb to remap 2-D data. However, this instruction also supports 3-D data so it can be used with cube maps and 3-D volume textures.

Here is an example of the sequence the instruction follows.

tex t(n)
texreg2rgb t(m), t(n)     where m > n

Here is more detail about how the remapping is accomplished.

// The first instruction loads the texture color (RGBA) into register tn
tex tn

// The second instruction remaps the color
t(m)RGB = TextureSample(stage m)RGB using t(n)RGB as coordinates.


Registers
Microsoft DirectX 9.0 SDK Update (October 2004)

Registers

  • ps_1_X Registers
  • ps_2_0 Registers
  • ps_2_x Registers
  • ps_3_0 Registers


Pixel Shader Register Modifiers
Microsoft DirectX 9.0 SDK Update (October 2004)

Pixel Shader Register Modifiers

Source Register Modifiers:

  • Source Register Bias
  • Source Register Invert
  • Source Register Negate
  • Source Register Swizzling
  • Source Register Scale x 2
  • Source Register Signed Scaling
  • Pixel Shader Source Register Modifiers
  • ps_1_4 Source Register Modifiers for texld and texcrd

Destination Register Modifiers:

  • Destination Register Write Mask


Pixel Shader Source Register Modifiers
Microsoft DirectX 9.0 SDK Update (October 2004)

Pixel Shader Source Register Modifiers

Use source register modifiers to change the value read from a register before an instruction runs. The contents of a source register are left unchanged. Modifiers are useful for adjusting the range of register data in preparation for the instruction. A set of modifiers called selectors copies or replicates the data from a single channel (r,g,b,a) into the other channels.

ps_1_1 - ps_1_4

This table identifies the versions that support each modifier:

Source register modifiers | Syntax | Version
 |  | 1_1 | 1_2 | 1_3 | 1_4
bias | register_bias | X | X | X | X
invert | 1 - register | X | X | X | X
negate | - register | X | X | X | X
scale by 2 | register_x2 |  |  |  | X
signed scaling | register_bx2 | X | X | X | X
texld and texcrd modifiers | register_d* | X | X | X | X
source register swizzling | register.xyzw | X | X | X | X

Source register modifiers can be used only on arithmetic instructions. They cannot be used on texture address instructions. The exception to this is the scale by 2 modifier. For version 1_1, signed scale can be used on the source argument of any texm* instruction. For version 1_2 or 1_3, signed scale can be used on the source argument of any texture address instruction.

Some modifier specific restrictions:

  • Negate can be combined with either the bias, signed scaling, or scalex2 modifier. When combined, negate is run last.
  • Invert cannot be combined with any other modifier.
  • Invert, negate, bias, signed scaling, and scalex2 can be combined with any of the selectors.
  • Source register modifiers should not be used on constant registers because they will cause undefined results. For version 1_4, modifiers on constants are not allowed and will fail validation.

ps_2_0 and Above

For version ps_2_0 and up, the number of modifiers has been simplified.

Negate

Negate the contents of the source register.

Component modifier | Description
- r | Source negation

The negate modifier cannot be used on second source register of these instructions: m3x2, m3x3, m3x4, m4x3, and m4x4.

Pixel shader versions | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
- | x | x | x | x | x

Absolute Value

Take the absolute value of the register.

Pixel shader versions | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
abs |  |  |  | x | x

If any version 3 shader reads from one or more constant float registers (c#), one of the following must be true.

  • All of the constant floating-point registers must use the abs modifier.
  • None of the constant floating-point registers can use the abs modifier.


Source Register Bias
Microsoft DirectX 9.0 SDK Update (October 2004)

Source Register Bias

Subtract 0.5 from all components.

Registers

Source register. For more about register types, see ps_1_X Registers.

Remarks

The contents of the register are not changed. The modifier is applied only to the data read from the register. The bias is applied to all four color channels (RGBA) as follows:

output = (input - 0.5)

The effect is to modify data that was in the range 0 to 1 to be in the range -0.5 to 0.5. Applying bias to data outside this range may produce undefined results.

Note This modifier is mutually exclusive with Source Register Invert, so it cannot be applied to the same register.

This modifier is for use with the arithmetic instructions.

Example

This example performs the same operation as D3DTOP_ADDSIGNED in Microsoft DirectX 6.0 and 7.0 multiple texture syntax.

add r0, r0, t0_bias; Shift down by 0.5.


Source Register Invert
Microsoft DirectX 9.0 SDK Update (October 2004)

Source Register Invert

Performs a (1 - value) calculation for each channel of the specified register.

Syntax

1 - register

Registers

Source Register. For more about register types, see ps_1_X Registers.

Remarks

The contents of the register are not changed. The modifier is applied only to the data read from the register. The invert operation is applied to all four color channels (RGBA).

This modifier can be used only with arithmetic instructions. In addition, this modifier cannot be combined with the other Pixel Shader Source Register Modifiers.

Example

This example uses inversion to generate the complement of register r1.

mul r0, r0, 1-r1;


Source Register Negate
Microsoft DirectX 9.0 SDK Update (October 2004)

Source Register Negate

Performs a negate (y = -x), on all register components.

Syntax

- register

Registers

Source Register. For more about register types, see ps_1_X Registers.

Remarks

The contents of the register are not changed. The modifier is applied only to the data read from the register. The negate operation is applied to all four color channels (RGBA).

This operation is performed after any other modifiers present on the same argument.

This modifier is mutually exclusive with Source Register Invert so it cannot be applied to the same register.

This modifier is for use only with arithmetic instructions.

Example

The following example shows how to use this modifier.

mul r0, r0, -v1;


Source Register Scale x 2
Microsoft DirectX 9.0 SDK Update (October 2004)

Source Register Scale x 2

Multiply the value by two before using it in the instruction.

Syntax

register_x2

Register

Source register. For more about register types, see ps_1_X Registers.

Remarks

The contents of the register are not changed. The modifier is applied only to the data read from the register.

This modifier is mutually exclusive with Source Register Invert, so it cannot be applied to the same register.

This modifier is only available to arithmetic instructions in version 1_4.

Example

This example samples a texture, converts data to the range of -1 to +1, and calculates a dot product.

mul r0, r0, r1_x2;


Source Register Signed Scaling
Microsoft DirectX 9.0 SDK Update (October 2004)

Source Register Signed Scaling

Subtracts 0.5 from each channel and scales the result by 2.0. The name "bx2" comes from bias and times two, which is the operation it performs.

Syntax

source register_bx2

Register

Source Register. For more about register types, see ps_1_X Registers.

Remarks

The contents of the register are not changed. The modifier is applied only to the data read from the register.

The signed scaling operation is applied to the data read from the register before the next instruction is run. The operation is applied to all four color channels (RGBA) as follows:

y = 2(x - 0.5)

This operation is commonly used to expand data from [0.0 to 1.0] to [-1.0 to 1.0]. Using _bx2 on data outside the range 0 to 1 may produce undefined results.

This modifier is designed for use with the arithmetic instructions. This modifier is commonly used on inputs to the dot product instruction (dp3).

This modifier is mutually exclusive with Source Register Invert so it cannot be applied to the same register.

For shader version 1_1, input arguments to any of the texture address instructions of the form texm3x2* and texm3x3* can use the _bx2 modifier.

For shader versions 1_2 and 1_3, the source register to any tex* instruction can use the _bx2 modifier. For version 1_0 and 1_1, _bx2 cannot be used on the source register for texreg2ar or texreg2gb.

Example

This example samples a texture, converts data to the range of -1 to +1, and calculates a dot product.

tex t0                        ; Read a texture color.
dp3_sat r0, t0_bx2, v0_bx2    ; Calculate a dot product.


ps_1_4 Source Register Modifiers for texld and texcrd
Microsoft DirectX 9.0 SDK Update (October 2004)

ps_1_4 Source Register Modifiers for texld and texcrd

Two pixel shader version 1_4 texture address instructions, texld and texcrd, have custom syntax. These instructions support their own set of source register modifiers, source register selectors, and destination-register write masks, as shown here.

Source Register Modifiers for texld and texcrd

These modifiers provide projective divide functionality by dividing the x and y values by either the z or w values.

Source register modifiers | Description | Syntax
_dz | Divide x,y components by z | register_dz
_db |  | register_db
_dw | Divide x,y components by w | register_dw
_da |  | register_da

Remarks

The _dz or _db modifier does the following:

x' = x/z ( x' = 1.0 if z == 0)
y' = y/z ( y' = 1.0 if z == 0)
z' is undefined
w' is undefined

The _dw or _da modifier does the following:

x' = x/w ( x' = 1.0 if w == 0)
y' = y/w ( y' = 1.0 if w == 0)
z' is undefined
w' is undefined


Source Register Swizzling
Microsoft DirectX 9.0 SDK Update (October 2004)

Source Register Swizzling

Swizzling refers to the ability to copy any source register component to any temporary register component. Swizzling does not affect the source register data. Before an instruction runs, the data in a source register is copied to a temporary register.

Source Swizzling

Source swizzle allows individual component of a source register to take on the value of any of the four components of the same source register before the register is read for computation.

For example, the .zxxy swizzle means:

  • .x component will take on the value of .z component
  • .y component will take on the value of .x component
  • .z component will take on the value of .x component
  • .w component will take on the value of .y component

The components can appear in any order. If fewer than four components are specified, the last component is repeated. For example:

.xy  = .xyyy
.wzx = .wzxx
.z   = .zzzz

If no component is specified, no swizzling is applied.

Some instructions have restrictions for source swizzle. They are listed in the respected instruction reference pages.

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
.x |  |  |  | x | x | x | x | x | x
.y |  |  |  | x | x | x | x | x | x
.z | x* | x* | x* | x | x | x | x | x | x
.w | x | x | x | x | x | x | x | x | x
.xyzw (default) | x | x | x | x | x | x | x | x | x
.yzxw |  |  |  |  | x | x | x | x | x
.zxyw |  |  |  |  | x | x | x | x | x
.wzyx |  |  |  |  | x | x | x | x | x
arbitrary swizzle |  |  |  |  |  | x | x | x | x

* Only available if destination write mask is .w (.a).

Arbitrary Swizzle

Swizzles can be applied to source registers in an arbitrary order; that is, any source register can take any component mask, in any order.

Replicate Swizzle

Replicate swizzle copies one component to another. This is, exactly one of the .x, .y, .z, .w swizzle components (or the .r, .g, .b, .a equivalents) must be specified.


Destination Register Write Mask
Microsoft DirectX 9.0 SDK Update (October 2004)

Destination Register Write Mask

A write mask controls which components of a destination register are written after an instruction is completed. An output write mask is allowed as long as the components are in the order of .rgba or .xyzw. That is, .rba and .xw are valid masks. Texture registers have one set of rules and non-texture registers have another set of rules.

Syntax

dst.writemask

where

  • dst is a destination register.
  • writemask is a sequence of masks from either set: (x,y,z,w) or (red, green, blue, alpha).

Remarks

The following destination write masks are available.

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_x | 2_sw | 3_0 | 3_sw
.xyzw (default) | x | x | x | x | x | x | x | x | x
.xyz | x | x | x | x | x | x | x | x | x
.w | x | x | x | x | x | x | x | x | x
arbitrary mask |  |  |  | x | x | x | x | x | x

The arbitrary mask allows any set of channels to be combined to produce a mask. The channels must be listed in the order r, g, b, a—for example, register.rba, which updates the red, blue, and alpha channels of the destination. The arbitrary mask is available only in version 1_4.

If no destination write mask is specified, the destination write mask defaults to the rgba case. In other words, all channels in the destination register are updated.

For versions 1_0 to 1_3, the dp3 dp3 arithmetic instruction can use only the .rgb or .rgba output write masks.

Destination register write masks are supported for arithmetic operations only. They cannot be used on texture addressing instructions, with the exception of the version 1_4 instructions, texcrd and texld.

The default is to write all four color channels.

// All four color channels can be written by explicitly listing them.
mul r0.rgba, t0, v0

// Or, the default mask can be used to write all four channels.
mul r0, t0, v0

The alpha write mask is also referred to as the scalar write mask, because it uses the scalar pipeline.

add r0.a, t1, v1

So this instruction effectively puts the sum of the alpha component of t1 and the alpha component of v1 into r0.a.

The color write mask is used to control writing to the color channels.

// The color write mask is also referred to as the vector write mask,
//   because it uses the vector pipeline.
mul r0.rgb, t0, v0

For version 1_4, destination write masks can be used in any combination as long as the masks are ordered r,g,b,a.

// This example updates the red, blue, and alpha channels.
mov r0.rba, r1

A co-issued instruction allows two potentially different instructions to be issued simultaneously. This is accomplished by executing the instructions in the alpha pipeline and the RGB pipeline.

  mul r0.rgb, t0, v0
+ add r1.a,   t1, c1

The advantage of pairing instructions this way is that it allows different operations to be performed in the vector and scalar pipeline in parallel.

These vertex shader output registers are restricted to the following write masks:

Register Type | Required Write Mask
oFog | no explicit write mask is allowed on this scalar register
oPts | no explicit write mask is allowed on this scalar register
oPos | .xyzw(which is the default)
oT# | combined mask: .x | .xy | .xyz | .xyzw (which is the default)


ps_1_X Registers
Microsoft DirectX 9.0 SDK Update (October 2004)

ps_1_X Registers

Pixel shaders depend on registers to get vertex data, to output pixel data, to hold temporary results during calculations and to identify texture sampling stages. There are several types of registers, each with a unique functionality. This section contains reference information for the input and output registers implemented by pixel shader version 1_X.

Registers hold data for use by the pixel shader. Registers are fully described in the following sections.

  • Register Types describes the four types of registers available and their purposes.
  • Read Port Limit details the restrictions on using multiple registers in a single instruction.
  • Read-only, Read/Write describes which registers can be used for reading, writing, or both.
  • Range details the range of the component data.

Register Types

 |  | Versions
Name | Type | 1_1 | 1_2 | 1_3 | 1_4
c# | Constant register | 8 | 8 | 8 | 8
r# | Temporary register | 2 | 2 | 2 | 6
t# | Texture register | 4 | 4 | 4 | 6
v# | Color register | 2 | 2 | 2 | 2 in phase 2
  • Constant registers contain constant data. Data can be loaded into a constant register using IDirect3DDevice9::SetPixelShaderConstantF or it can be defined using def. Constant registers are not usable by texture address instructions. The only exception is the texm3x3spec instruction, which uses a constant register to supply an eye-ray vector.
  • Temporary registers are used to store intermediate results. r0 additionally serves as the pixel shader output. The value in r0 at the end of the shader is the pixel color for the shader.

    Shader validation will fail IDirect3DDevice9::CreatePixelShader on any shader that attempts to read from a temporary register that has not been written by a previous instruction. D3DXAssembleShader will fail similarly, assuming validation is enabled (do not use D3DXSHADER_SKIPVALIDATION).

  • Texture registers

    For pixel shader version 1_1 to 1_3, texture registers contain texture data or texture coordinates. Texture data is loaded into a texture register when a texture is sampled. Texture sampling uses texture coordinates to look up, or sample, a color value at the specified (u,v,w,q) coordinates while taking into account the texture stage state attributes. The texture coordinate data is interpolated from the vertex texture coordinate data and is associated with a specific texture stage. There is a default one-to-one association between texture stage number and texture coordinate declaration order. By default, the first set of texture coordinates defined in the vertex format is associated with texture stage 0.

    For these pixel shader versions, texture registers behave just like temporary registers when used by arithmetic instructions.

    For pixel shader version 1_4, texture registers (t#) contain read-only texture coordinate data. This means that the texture coordinate set and the texture stage number are independent from each other. The texture stage number (from which to sample a texture) is determined by the destination register number (r0 to r5). For the texld instruction, the texture coordinate set is determined by the source register (t0 to t5), so the texture coordinate set can be mapped to any texture stage. In addition, the source register (specifying texture coordinates) for texld can also be a temporary register (r#), in which case the contents of the temporary register are used as texture coordinates.

  • Color registers contain per-pixel color values. The values are obtained by per-pixel iteration of the diffuse and specular color values in the vertex data. For pixel shader version 1_4 shaders, color registers are available only during the second phase.

    If the shade mode is set to D3DSHADE_FLAT, the iteration of both vertex colors (diffuse and specular) is disabled. Regardless of the shade mode, fog will still be iterated by the pipeline if pixel fog is enabled. Keep in mind that fog is applied later in the pipeline than the pixelshader.

    It is common to load the v0 register with the vertex diffuse color data. It is also common to load the v1 register with the vertex specular color data.

    Input color data values are clamped (saturated) to the range 0 through 1 because this is the valid input range for color registers in the pixel shader.

    Pixel shaders have read only access to color registers. The contents of these registers are iterated values, but iteration may be performed at much lower precision than texture coordinates.

Read Port Limit

The read port limit specifies the number of different registers of each register type that can be used as a source register in a single instruction.

 |  | Versions
Name | Type | 1_1 | 1_2 | 1_3 | 1_4
c# | Constant register | 2 | 2 | 2 | 2
r# | Temporary register | 2 | 2 | 2 | 3
t# | Texture register | 2 | 3 | 3 | 1
v# | Color register | 2 | 2 | 2 | 2 in phase 2

For example, the color registers for almost all versions have a read port limit of two. This means that a single instruction can use a maximum of two different color registers (v0 and v1 for instance) as source registers. This example shows two color registers being used in the same instruction:

mad r0, v1, c2, v0

Read-only, Read/Write

The register types are identified according to read-only (RO) capability or read/write (RW) capability in the following table. Read-only registers can be used only as source registers in an instruction; they can never be used as a destination register.

 |  | Versions
Name | Type | 1_1 | 1_2 | 1_3 | 1_4
c# | Constant register | RO | RO | RO | RO
r# | Temporary register | RW | RW | RW | RW
t# | Texture register | RW | RW | RW | See following note
v# | Color register | RO | RO | RO | RO

Registers that are RW capable can be used to store intermediate results. This includes the temporary registers and texture registers for some of the shader versions.

Note
  • For pixel shader version 1_4, texture registers are RO for texture addressing instructions, and texture registers can be neither read from nor written to by arithmetic instructions. Also, because texture registers have become texture coordinate registers, having RO access is not a regression of previous functionality.

Range

The range is the maximum and minimum register data value. The ranges vary based on the type of register. The ranges for some of the registers can be queried from the device caps using IDirect3D9::GetDeviceCaps.

Name | Type | Range | Versions
c# | Constant register | -1 to +1 | All versions
r# | Temporary register | - PixelShader1xMaxValue to + PixelShader1xMaxValue | All versions
t# | Texture register | - MaxTextureRepeat to + MaxTextureRepeat | All versions
v# | Color register | 0 to 1 | All versions

Early pixel shader hardware represents data in registers using a fixed-point number. This limits precision to a maximum of approximately eight bits for the fractional part of a number. Keep this in mind when designing a shader.

For pixel shader version 1_1 to 1_3, MaxTextureRepeat must be a minimum of one. For 1_4, MaxTextureRepeat must be a minimum of eight.

See D3DCAPS9 for more information about PixelShader1xMaxValue.


ps_2_0 Registers
Microsoft DirectX 9.0 SDK Update (October 2004)

ps_2_0 Registers

Pixel shaders depend on registers to get vertex data, to output pixel data, to hold temporary results during calculations, and to identify texture sampling stages. There are several types of registers, each with a unique functionality. This section contains reference information for the input and output registers implemented by pixel shader version 2_x.

Input Register Types

Register | Name | Count | R/W | # Read ports | # Reads/inst | Dimension | RelAddr | Defaults | Requires DCL
v# | Input Color Register | 2 | R | 1 | Unlimited | 4 | N | Partial(0001). See note 4 | Y
r# | Temporary Register | See note 1 | R/W | 3 | Unlimited | 4 | N | None | N
c# | Constant Float Register | 32 | R | 1 | 2 | 4 | N | 0000 | N
i# | Constant Integer Register | 16 | See note 2 | 1 | 1 | 4 | N | 0000 | N
b# | Constant Boolean Register | 16 | See note 2 | 1 | 1 | 1 | N | FALSE | N
p0 | Predicate Register | 1 | See note 2 | 1 | 1 | 1 | N | None | Y
s# | Sampler | 16 | See note 3 | 1 | 1 | 4 | N | See note 5 | Y
t# | Texture Coordinate Register | 8 | R | 1 | 1 | 1 | N | None | Y

Notes:

  1. 12 min/32 max: The number of r# registers is determined by PS20Caps.NumTemps (which ranges from 12 to 32).
  2. Only usable by a flow control instruction.
  3. Only usable by a texture sampling instruction.
  4. partial(x, y, z, w) - If only a subset of channels are updated in the register, the remaining channels will default to specified values (x, y, z, w).
  5. Defaults for sampler lookups exist, but values depend on texture format.

The number of readports is the number of different registers (for each register type) that can be read in a single instruction.

Output Register Types

Register | Name | Count | R/W | Dimension | RelAddr | Defaults | Requires DCL
oC# | Output Color Register | See Multielement Textures | W | 4 | N | None | N
oDepth | Output Depth Register | 1 | W | 1 | N | None | N


ps_2_x Registers
Microsoft DirectX 9.0 SDK Update (October 2004)

ps_2_x Registers

Pixel shaders depend on registers to get vertex data, to output pixel data, to hold temporary results during calculations, and to identify texture sampling stages. There are several types of registers, each with a unique functionality. This section contains reference information for the input and output registers implemented by pixel shader version 2_x.

Input Register Types

Register | Name | Count | R/W | # Read ports | # Reads/inst | Dimension | RelAddr | Defaults | Requires DCL
v# | Input Color Register | 2 | R | 1 | Unlimited | 4 | N | Partial(0001). See note 4 | Y
r# | Temporary Register | See note 1 | R/W | 3 | Unlimited | 4 | N | None | N
c# | Constant Float Register | 32 | R | 1 | 2 | 4 | N | 0000 | N
i# | Constant Integer Register | 16 | See note 2 | 1 | 1 | 4 | N | 0000 | N
b# | Constant Boolean Register | 16 | See note 2 | 1 | 1 | 1 | N | FALSE | N
p0 | Predicate Register | 1 | See note 2 | 1 | 1 | 1 | N | None | Y
s# | Sampler | 16 | See note 3 | 1 | 1 | 4 | N | See note 5 | Y
t# | Texture Coordinate Register | 8 | R | 1 | 1 | 1 | N | None | Y

Notes:

  1. 12 min/32 max: The number of r# registers is determined by PS20Caps.NumTemps (which ranges from 12 to 32).
  2. Only usable by a flow control instruction.
  3. Only usable by a texture sampling instruction.
  4. partial(x, y, z, w) - If only a subset of channels are updated in the register, the remaining channels will default to specified values (x, y, z, w).
  5. Defaults for sampler lookups exist, but values depend on texture format.

The number of readports is the number of different registers (for each register type) that can be read in a single instruction.

Output Register Types

Register | Name | Count | R/W | Dimension | RelAddr | Defaults | Requires DCL
oC# | Output Color Register | See Multielement Textures | W | 4 | N | None | N
oDepth | Output Depth Register | 1 | W | 1 | N | None | N


ps_3_0 Registers
Microsoft DirectX 9.0 SDK Update (October 2004)

ps_3_0 Registers

Pixel shaders depend on registers to get vertex data, to output pixel data, to hold temporary results during calculations, and to identify texture sampling stages. There are several types of registers, each with a unique functionality. This section contains reference information for the input and output registers implemented by pixel shader version 3_0.

New Registers

Input Register

The Input Registers (v#) are now fully floating point and the Texture Coordinate Registers (t#) have been consolidated into it. The dcl_usage at the top of the shader is used to describe what is containted in a particular Input Register. A semantic for the pixel types is introduced (analogous to the vertex side) for this model. No clamping is performed when the input registers are defined as colors (like texture coordinates). The evaluation of the registers defined as color differs from the texture coordinates when multisampling.

Face Register

The face register (vFace) is new for this model. This is a floating point scalar register that will eventually contain the primitive area. In ps_3_0, however, only the sign of this register is valid. Hence, if the value is less than zero (the sign bit is set negative) the primitive is the back face (the area is negative, counterclockwise). Therefore, in ps_3_0 it only makes sense to compare this register against 0 (> 0 or < 0). Inside the pixel shader, the application can make a decision as to which lighting technique to use. Two-sided lighting can be achieved this way. This register requires a declaration, so undeclared usage will be flagged as an error. For lines and point primitives, this register is undefined. The face register can only be used as condition with the following instructions: setp_comp - ps, if_comp, or break_comp.

Loop Counter Register

The Loop Counter Register (aL) is new for this model. It automatically gets incremented in each execution of the loop/endloop block. It can be used in the block for relative addressing if needed. It is invalid to use Loop Counter Register outside the loop.

Position Register

The Position Register (vPos) is new for this model. It contains the current pixels (x, y) in the corresponding channels. The (z, w) channels are undefined. This register requires a declaration, so undeclared usage will be flagged as an error. When declared, this register must have exactly one of the following masks: .x, .y, .xy.

Input Register Types

Register | Name | Count | R/W | # Read ports | # Reads/inst | Dimension | RelAddr | Defaults | Requires DCL
v# | Input Color Register | 10 | R | 1 | Unlimited | 4 | aL | None | Yes
r# | Temporary Register | 32 | R/W | 3 | Unlimited | 4 | No | None | No
c# | Constant Float Register | 224 | R | 1 | Unlimited | 4 | No | 0000 | No
i# | Constant Integer Register | 16 | R | 1 | 1 | 4 | No | 0000 | No
b# | Constant Boolean Register | 16 | R | 1 | 1 | 1 | No | FALSE | No
p0 | Predicate Register | 1 | R | 1 | 1 | 1 | No | None | No
s# | Sampler | 16 | R | 1 | 1 | 4 | No | See note 1 | Yes
vFace | Face Register | 1 | R | 1 | Unlimited | 1 | No | None | Yes
vPos | Position Register | 1 | R | 1 | Unlimited | 4 | No | None | Yes
aL | Loop Counter Register | 1 | R | 1 | Unlimited | 1 | n/a | None | No

Notes:

  1. Defaults for sampler lookups exist, but values depend on texture format.

The number of readports is the number of different registers (for each register type) that can be read in a single instruction.

Output Register Types

Register | Name | Count | R/W | Dimension | RelAddr | Defaults | Requires DCL
oC# | Output Color Register | See Multielement Textures | W | 4 | No | None | No
oDepth | Output Depth Register | 1 | W | 1 | No | None | No


Relative Addressing
Microsoft DirectX 9.0 SDK Update (October 2004)

Relative Addressing

The [ ] syntax can be used only in register types that can be relatively addressed in certain shader models. The supported forms of [ ] syntax are listed as follows:

Where:

  • "R" denotes any register type that can be relatively addressed.
  • "A" denotes any register that can be used as an index to relatively address other registers.
  • n0 - ni, m0 - mj, and k are integers >= 0.
[ ] syntax | Effective index | Examples
R[ A + m0 + ... + mj ] | A + m0 + ... + mj | c[ aL + 3 + 7 ]
R[ k ] ( = Rk ) | k | c[ 10 ] ( = c10 )
R[ A ] | A | c[ aL ]
Rk[ n0 + ... + ni + A + m0 + ... + mj ] | A + k + n0 + ... + ni + m0 + ... + mj | c8[ 3 + 2 + aL + 5 + 6 + 1 ]
R[ n0 + ... + ni + A + m0 + ... + mj ] | A + n0 + ... + ni + m0 + ... + mj | c[ 2 + 1 + aL + 3 + 4 + 5 ]
Rk[ A ] | A + k | c12[ aL ], c0[ aL ]
Rk[ A + m0 + ... + mj ] | A + k + m0 + ... + mj | c[ aL + 4 + 8 ]
R[ n0 + ... + ni + A ] | A + n0 + ... + ni | c[ 3 + 1 + aL ]
Rk[ n0 + ... + ni + A ] | A + k + n0 + ... + ni | c[ 2 + 1 + 3 + aL ]

The registers are available in the following versions:


Input Color Register
Microsoft DirectX 9.0 SDK Update (October 2004)

Input Color Register

Pixel shader input register containing vertex color.

Syntax

dcl v#.writeMask

where:

  • dcl is a register declaration instruction.
  • v is an input register and # is the register number. The number of registers allowed is determined by the shader version.
  • writeMask determines which components (up to four) are written. Valid components are: (x,y,z,w) or (r,g,b,a).

Remarks

Color registers are read-only registers. Each register contains four-component RGBA values iterated from input vertices. They have lower precision than most registers, guaranteed to have 8 bits of unsigned data in the range (0, +1). You cannot use more than one in a single instruction.

Related Topics

  • ps_1_X Registers
  • ps_2_0 Registers
  • ps_2_x Registers
  • ps_3_0 Registers


Constant Boolean Register
Microsoft DirectX 9.0 SDK Update (October 2004)

Constant Boolean Register

This register is a collection of bits used in static flow control instructions (for example, if bool - else - endif). There are 16 of them, therefore, a shader can have 16 independent branch conditions. They can be set using defi or IDirect3DDevice9::SetPixelShaderConstantI.

The behavior of shader constants has changed between Microsoft DirectX 8.0 and DirectX 9.0.

  • For DirectX 9.0, constants set with defx assign values to the shader constant space. The lifetime of a constant declared with defx is confined to the execution of that shader only. Conversely, constants set using the application programming interfaces (APIs)SetXXXShaderConstantX initialize constants in global space. Constants in global space are not copied to local space (visible to the shader) until SetxxxShaderConstants is called.
  • For DirectX 8.0, constants set with defx or the APIs both assign values to the shader constant space. Each time the shader is executed, the constants are used by the current shader regardless of the technique used to set them.
Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Constant Boolean Register |  |  |  |  |  |  | x | x | x


Constant Float Register
Microsoft DirectX 9.0 SDK Update (October 2004)

Constant Float Register

Pixel shader input register for a 4-D floating-point constant.

They can be set using def or IDirect3DDevice9::SetPixelShaderConstantF.

The behavior of shader constants has changed between Microsoft DirectX 8.0 and DirectX 9.0.

  • For DirectX 9.0, constants set with defx assign values to the shader constant space. The lifetime of a constant declared with defx is confined to the execution of that shader only. Conversely, constants set using the application programming interfaces (APIs)SetXXXShaderConstantX initialize constants in global space. Constants in global space are not copied to local space (visible to the shader) until SetxxxShaderConstants is called.
  • For DirectX 8.0, constants set with defx or the APIs both assign values to the shader constant space. Each time the shader is executed, the constants are used by the current shader regardless of the technique used to set them.

Examples

Here is an example declaring two floating-point constants within a shader.

def c40, 0.0f,0.0f,0.0f,0.0f;

These constants are loaded every time IDirect3DDevice9::SetPixelShader is called.

If you are setting constant values with the API, there is no shader declaration required.


Constant Integer Register
Microsoft DirectX 9.0 SDK Update (October 2004)

Constant Integer Register

Constant integer registers are used only by loop and rep.

They can be set using def or IDirect3DDevice9::SetPixelShaderConstantI.

When used as an argument to the loop instruction:

  • .x is the iteration count. (rep uses only this component).
  • .y is the initial value for the loop counter.
  • .z is the increment step for the loop counter.
Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Constant Integer Register |  |  |  |  |  |  | x | x | x

The behavior of shader constants has changed between Microsoft DirectX 8.0 and DirectX 9.0.

  • For DirectX 9.0, constants set with defx assign values to the shader constant space. The lifetime of a constant declared with defx is confined to the execution of that shader only. Conversely, constants set using the application programming interfaces (APIs)SetXXXShaderConstantX initialize constants in global space. Constants in global space are not copied to local space (visible to the shader) until SetxxxShaderConstants is called.
  • For DirectX 8.0, constants set with defx or the APIs both assign values to the shader constant space. Each time the shader is executed, the constants are used by the current shader regardless of the technique used to set them.


Loop Counter Register
Microsoft DirectX 9.0 SDK Update (October 2004)

Loop Counter Register

The only register in this bank is the current loop counter (aL) register. It automatically gets incremented in each execution of the loop...endloop block. So it can be used in the block for relative addressing if needed and is invalid to use it outside the loop.

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Loop Counter Register |  |  |  |  |  |  |  | x | x


Predicate Register
Microsoft DirectX 9.0 SDK Update (October 2004)

Predicate Register

This pixel shader output register contains a per-channel boolean value.

Syntax

Predicate Register

Remarks

A predicate register is supported by the following versions:

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
predicate register | x | x | x

Here are the register properties.

Register type | Count | R/W | # Read ports | # Reads/inst | Dimension | RelAddr | Defaults | Requires DCL
Predicate(p) | 1 | R/W | 1 | 1 | 4 | N/A | None | N

The predicate register can be modified with setp_comp - ps. There are no default values for this register; an application needs to set the register before it is used.

Instruction Information

Minimum operating systems Windows 98


Sampler
Microsoft DirectX 9.0 SDK Update (October 2004)

Sampler

A sampler is a input pseudo-register for a pixel shader, which is used to identify the sampling stage. There are 16 pixel shader sampling stage registers: s0 to s15. Therefore, up to 16 texture surfaces can be read in a single shader pass. The instructions that use a sampler register are texld and texldp.

Syntax

Sampler

Remarks

Sampler must be declared before use with the dcl_samplerType instruction.

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Sampler | x | x | x | x | x

Samplers are pseudo registers because you cannot directly read or write to them.

A sampling unit corresponds to the texture sampling stage, encapsulating the sampling-specific state provided by IDirect3DDevice9::SetSamplerState. Each sampler uniquely identifies a single texture surface, which is set to the corresponding sampler using the IDirect3DDevice9::SetTexture. However, the same texture surface can be set at multiple samplers.

At draw time, a texture cannot be simultaneously set as a render target and a texture at a stage.

Because there are 16 samplers, up to four texture surfaces can be read from in a single shader pass. A sampler might appear as the only argument in the texture load instruction: texldl.

In ps_3_0, if a sampler is used, it needs to be declared at the beginning of the shader program using the dcl_samplerType instruction.

Sampling a texture with a higher dimension than is present in the texture coordinates is illegal. Sampling a texture with a lower dimension than is present in the texture coordinates will ignore the extra texture coordinates.

Instruction Information

Minimum operating systems Windows 98


Temporary Register
Microsoft DirectX 9.0 SDK Update (October 2004)

Temporary Register

Pixel shader input temporary registers are used to hold intermediate results.

Syntax

Temporary Register

Remarks

Syntax
no declaration is required

Remarks

Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Temporary Register | x | x | x | x | x
  • There are 12 pixel-shader temporary registers: r0 to r11.
  • These registers are used for storing intermediate results during computations.
  • If a temporary register uses components that are not defined in previous code, shader validation will fail.
  • These are at least floating-point precision.
  • A maximum of three can be used in a single instruction.

Instruction Information

Minimum operating systems Windows 98


Texture Coordinate Register
Microsoft DirectX 9.0 SDK Update (October 2004)

Texture Coordinate Register

Pixel shader input register containing texture coordinates.

Syntax

Texture Coordinate Register

Remarks

Remarks
Pixel shader versions | 1_1 | 1_2 | 1_3 | 1_4 | 2_0 | 2_sw | 2_x | 3_0 | 3_sw
Texture Coordinate Register | x | x | x | x | x

A texture coordinate register contains texture coordinate data. Before a texture coordinate register is used, it must be declared by a pixel shader declaration. For details about how to declare a texture register, see dcl.

In addition, here are some other properties of texture coordinate registers.

  • There are eight pixel-shader texture coordinate registers, t0 to t7.
  • These are read-only registers.
  • They contain four-component RGBA values iterated from input vertices.
  • They contain high precision, high dynamic range data values interpolated from the vertex data. Values are generated with perspective-correct interpolation. Data is floating-point precision, and is signed.
  • There is a maximum of one in a single instruction.
  • Multiple reads of a texture coordinate register within a shader must use identical Pixel Shader Source Register Modifiers.
  • The optional partial precision modifier [_pp] applies to dependent reads. This is because partial precision affects arithmetic operations involving the texture coordinate register. It will not affect the precision of texture address instructions because it does not affect the texture coordinate iterators.

Instruction Information

Minimum operating systems Windows 98


Output Color Register
Microsoft DirectX 9.0 SDK Update (October 2004)

Output Color Register

The pixel shader color output registers (oC#) are write-only registers that output results to multiple render targets.

Syntax

oC#

Where:

Name | Description
oC0 | render target #0 of a multiple render target texture
oC1 | render target #1 of a multiple render target texture
oC2 | render target #2 of a multiple render target texture
oC3 | render target #3 of a multiple render target texture

Remarks

  • If oC# is written but there is no corresponding render target in the multiple render-target, then this write to oC# is ignored.
  • The render states D3DRS_COLORWRITEENABLE, D3DRS_COLORWRITEENABLE1, D3DRS_COLORWRITEENABLE2 and D3DRS_COLORWRITEENABLE3 determine which components of oC# ultimately get written to the render target (after blend, if applicable). If the shader writes some but not all of the components defined by the D3DRS_COLORWRITEENABLE* render states for a given oC# register, then the unwritten channels produce undefined values in the corresponding render target. If none of the components of an oC# are written, the corresponding render target must not be updated at all (as stated above), so the D3DRS_COLORWRITEENABLE* render states do not apply.

ps_2_0 and ps_2_x Restrictions

  • oC# can only be written with the mov instruction.
  • oC0 must be always written in the shader.
  • No source swizzle (except .xyzw = default swizzle) or source modifier is allowed when writing to any oC#.
  • No destination write mask (except .xyzw = default mask) or instruction modifier is allowed when writing to any oC#.
  • If oCn is written, then oC0 - oCn-1 must also be written. For example, to write to oC2, you must also write to oC0 and oC1.
  • At most one write to any oC# per shader is allowed.
  • For ps_2_x and ps_3_0, you cannot write to oC# and oD# registers within dynamic flow control or predication (writes to oC# inside static flow control is fine).

ps_3_0 Restrictions

  • For ps_3_0, output registers oC# and oD# can be written any number of times. The output of the pixel shader comes from the contents of the output registers at the end of shader execution. If a write to an output register does not happen, perhaps due to flow control or if the shader just did not write it, the corresponding rendertarget is also not updated. If a subset of the channels in an output register are written, then undefined values will be written to the remaining channels.
  • For ps_3_0, the oC# registers can be written with any writemasks.
  • For ps_2_x and ps_3_0, you cannot write to oC# and oD# registers within dynamic flow control or predication (writes to oC# inside static flow control is fine).
  • You may not perform any gradient calculations (or operations that implicitly invoke gradient calculations such as texld, texldb, texldp) inside of flow control statements whose branching conditions vary on a per-primitive basis (ie: dynamic flow control instructions). Instruction predication is not considered dynamic flow control.

Related Topics

  • Multiple Render Targets


Output Depth Register
Microsoft DirectX 9.0 SDK Update (October 2004)

Output Depth Register

The pixel shader output depth register (oDepth) is a write-only scalar register that returns a new depth value for a depth test against the depth-stencil buffer.

Syntax

oDepth

Where:

Name | Description
oDepth | New depth value for a depth test against the depth-stencil buffer

Remarks

  • Replicate source swizzle (.x | .y | .z | .w) is required when writing to oDepth.
  • No explicit destination write mask is allowed when writing to oDepth.
  • If no depth buffer has been created or attached to the device, then write to oDepth is ignored.
  • If an application has a w-buffer set as its depth buffer, then it needs to take that into account while writing to oDepth. It potentially needs to send w-range information to the pixel shader and compute the w-range to scale the w-values written out to oDepth.

ps_2_0 and ps_2_x Restrictions

  • oDepth can only be written with the mov instruction.
  • No source modifier is allowed when writing to oDepth.
  • No instruction modifier is allowed when writing to oDepth.
  • At most one write to oDepth per shader is allowed.
  • Writing to oDepth from within a dynamic flow control construct, a static flow control construct, or using predication will produce undefined results.

ps_3_0 Restrictions

  • For ps_3_0, output registers oC# and oD# can be written any number of times. The output of the pixel shader comes from the contents of the output registers at the end of shader execution. If a write to an output register does not happen, perhaps due to flow control or if the shader just did not write it, the corresponding rendertarget is also not updated. If a subset of the channels in an output register are written, then undefined values will be written to the remaining channels.
  • For ps_2_x and ps_3_0, you cannot write to oC# and oD# registers within dynamic flow control or predication (writes to oC# inside static flow control is fine).
  • You may not perform any gradient calculations (or operations that implicitly invoke gradient calculations such as texld, texldb, texldp) inside of flow control statements whose branching conditions vary on a per-primitive basis (ie: dynamic flow control instructions). Instruction predication is not considered dynamic flow control.


Software Shaders
Microsoft DirectX 9.0 SDK Update (October 2004)

Software Shaders

Software shaders are implemented to allow development of shaders without underlying hardware support. They support the full feature set. Because they are implemented in software, they will not produce the best performance.

Version | Feature Set | Requirements
vs_2_sw | All the features of vs_2_x | Only supported by software vertex processing and a reference device.
vs_3_sw | All the features of vs_3_0 | Only supported by software vertex processing and a reference device.
ps_2_sw | All the features of ps_2_x | Only supported by a reference device.
ps_3_sw | All the features of ps_3_0 | Only supported by a reference device.

Some validations are relaxed for software shaders. This is useful for debugging and prototyping purposes. The following validations are relaxed: (all other validations remain the same)

Validation type | Relaxation
Instruction Counts: | This is relaxed for vs_2_sw, vs_3_sw and ps_2_sw, ps_3_sw. Unlimited instructions are allowed.
Float Constant Counts: | This is relaxed for vs_2_sw, vs_3_sw and ps_2_sw, ps_3_sw. Up to 8192 constants are allowed.
Integer Constant Counts: | This is relaxed for vs_2_sw, vs_3_sw and ps_2_sw, ps_3_sw. Up to 2048 constants are allowed.
Boolean Constant Counts: | This is relaxed for vs_2_sw, vs_3_sw and ps_2_sw, ps_3_sw. Up to 2048 constants are allowed.
Dependent-read depth: | This is relaxed for ps_2_sw. Like in vs_3_0 and ps_3_0, unlimited dependent reads are allowed.
Number of flow control instructions and labels: | This is relaxed for vs_2_sw. Unlimited flow control instructions and upto 2048 labels are allowed.
Loop count/start/step: | These are relaxed for vs_2_sw, vs_3_sw, ps_2_sw and ps_3_sw. Iteration start and interation step size for rep and loop instructions are 32-bit signed intergers. Interation count can be up to MAX_INT/64.
Read-port limits: | vs_2_sw, vs_3_sw, ps_2_sw and ps_3_sw have no read-port limit.
Number of interpolators: | There are 16 Output Registers (o#) in vs_3_sw and 10 Input Register (v#) for ps_3_sw.


Effect Reference
Microsoft DirectX 9.0 SDK Update (October 2004)

Effect Reference

Effects are a higher level abstraction that take advantage of vertex and pixel shaders to encapsulate rendering effects. Effects can be written with the high-level language or with the shader assembly language.

Here are the application programming interface (API) topics.

  • Interfaces
  • Functions
  • Structures
  • Constants

As an alternative to using the API to create effects, you can also use a command line compile tool. See Effect Command Line Compile.

Related Topics

  • Effect Format


Interfaces
Microsoft DirectX 9.0 SDK Update (October 2004)

Interfaces

Effects are implemented with the following interfaces.

Interface | Derives from
ID3DXBaseEffect | IUnknown
ID3DXEffect | ID3DXBaseEffect
ID3DXEffectCompiler | ID3DXBaseEffect
ID3DXEffectPool | IUnknown
ID3DXEffectStateManager | IUnknown
ID3DXInclude | None


ID3DXBaseEffect Interface

Provides methods for getting and setting effect parameters such as constants, functions, shaders, and techniques.

ID3DXBaseEffect Members

GetAnnotation | Gets the handle of an annotation.
GetAnnotationByName | Gets the handle of an annotation by looking up its name.
GetBool | Gets a BOOL value.
GetBoolArray | Gets an array of BOOL values.
GetDesc | Gets the effect description.
GetFloat | Gets a floating point value.
GetFloatArray | Gets an array of floating point values.
GetFunction | Gets the handle of a function.
GetFunctionByName | Gets the handle of a function by looking up its name.
GetFunctionDesc | Gets a function description.
GetInt | Gets an integer.
GetIntArray | Gets an array of integers.
GetMatrix | Gets a nontransposed matrix.
GetMatrixArray | Gets an array of nontransposed matrices.
GetMatrixPointerArray | Gets an array of pointers to nontransposed matrices.
GetMatrixTranspose | Gets a transposed matrix.
GetMatrixTransposeArray | Gets an array of transposed matrices.
GetMatrixTransposePointerArray | Sets an array of pointers to transposed matrices.
GetParameter | Gets the handle of a top-level parameter or a structure member parameter.
GetParameterByName | Gets the handle of a top-level parameter or a structure member parameter by looking up its name.
GetParameterBySemantic | Gets the handle of a top-level parameter or a structure member parameter by looking up its semantic with a case-insensitive search.
GetParameterDesc | Gets a parameter or annotation description.
GetParameterElement | Get the handle of an array element parameter.
GetPass | Gets the handle of a pass.
GetPassByName | Gets the handle of a pass by looking up its name.
GetPassDesc | Gets a pass description.
GetPixelShader | Gets a pixel shader.
GetString | Gets a string.
GetTechnique | Gets the handle of a technique.
GetTechniqueByName | Gets the handle of a technique by looking up its name.
GetTechniqueDesc | Gets a technique description.
GetTexture | Gets a texture.
GetValue | Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Getxxx calls in ID3DXBaseEffect.
GetVector | Gets a vector.
GetVectorArray | Gets an array of vectors.
GetVertexShader | Gets a vertex shader.
SetArrayRange | Set the range of an array to pass to the device.
SetBool | Sets a BOOL value.
SetBoolArray | Sets an array of Boolean values.
SetFloat | Sets a floating point value.
SetFloatArray | Sets an array of floating point values.
SetInt | Sets an integer.
SetIntArray | Sets an array of integers.
SetMatrix | Sets a non-transposed matrix.
SetMatrixArray | Sets an array of nontransposed matrices.
SetMatrixPointerArray | Sets an array of pointers to nontransposed matrices.
SetMatrixTranspose | Sets a transposed matrix.
SetMatrixTransposeArray | Sets an array of transposed matrices.
SetMatrixTransposePointerArray | Sets an array of pointers to transposed matrices.
SetPixelShader | Sets a pixel shader.
SetString | Sets a string.
SetTexture | Sets a texture.
SetValue | Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Setxxx calls in ID3DXBaseEffect.
SetVector | Sets a vector.
SetVectorArray | Sets an array of vectors.
SetVertexShader | Sets a vertex shader.

Remarks

The LPD3DXBASEEFFECT type is defined as a pointer to this interface.

typedef interface ID3DXBaseEffect ID3DXBaseEffect;
typedef interface ID3DXBaseEffect *LPD3DXBASEEFFECT;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9effect.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateEffect


ID3DXBaseEffect::GetAnnotation Method

Gets the handle of an annotation.

Syntax

D3DXHANDLE GetAnnotation(

    D3DXHANDLE hObject,
    UINT Index
);

Parameters

hObject
[in] Handle of a technique, pass, or top-level parameter. See Handles.
Index
[in] Annotation index.

Return Value

Returns the handle of the specified annotation, or NULL if the index was invalid. See Handles.

Remarks

Annotations are user-specific data that can be attached to any technique, pass, or parameter. See Handles.


ID3DXBaseEffect::GetAnnotationByName Method

Gets the handle of an annotation by looking up its name.

Syntax

D3DXHANDLE GetAnnotationByName(

    D3DXHANDLE hObject,
    LPCSTR pName
);

Parameters

hObject
[in] Handle of a technique, pass, or top-level parameter. See Handles.
pName
[in] String containing the annotation name.

Return Value

Returns the handle of the specified annotation, or NULL if the name was not found. See Handles.


ID3DXBaseEffect::GetBool Method

Gets a BOOL value.

Syntax

HRESULT GetBool(

    D3DXHANDLE hParameter,
    BOOL* pb
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pb
[out] Returns a Boolean value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetBool


ID3DXBaseEffect::GetBoolArray Method

Gets an array of BOOL values.

Syntax

HRESULT GetBoolArray(

    D3DXHANDLE hParameter,
    BOOL* pB,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pB
[out] Returns an array of Boolean values.
Count
[in] Number of Boolean values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetBoolArray


ID3DXBaseEffect::GetDesc Method

Gets the effect description.

Syntax

HRESULT GetDesc(

    D3DXEFFECT_DESC* pDesc
);

Parameters

pDesc
[out] Returns a description of the effect. See D3DXEFFECT_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXBaseEffect::GetFloat Method

Gets a floating point value.

Syntax

HRESULT GetFloat(

    D3DXHANDLE hParameter,
    FLOAT* pf
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pf
[out] Returns a floating point value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetFloat


ID3DXBaseEffect::GetFloatArray Method

Gets an array of floating point values.

Syntax

HRESULT GetFloatArray(

    D3DXHANDLE hParameter,
    FLOAT* pf,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pf
[out] Returns an array of floating point values.
Count
[in] Number of floating point values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetFloatArray


ID3DXBaseEffect::GetFunction Method

Gets the handle of a function.

Syntax

D3DXHANDLE GetFunction(

    UINT Index
);

Parameters

Index
[in] Function index.

Return Value

Returns the handle of the specified function, or NULL if the index was invalid. See Handles.


ID3DXBaseEffect::GetFunctionByName Method

Gets the handle of a function by looking up its name.

Syntax

D3DXHANDLE GetFunctionByName(

    LPCSTR pName
);

Parameters

pName
[in] String containing the function name.

Return Value

Returns the handle of the specified function, or NULL if the name was not found. See Handles.


ID3DXBaseEffect::GetFunctionDesc Method

Gets a function description.

Syntax

HRESULT GetFunctionDesc(

    D3DXHANDLE hFunction,
    D3DXFUNCTION_DESC* pDesc
);

Parameters

hFunction
[in] Function handle. See Handles.
pDesc
[out] Returns a description of the function. See D3DXFUNCTION_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXBaseEffect::GetInt Method

Gets an integer.

Syntax

HRESULT GetInt(

    D3DXHANDLE hParameter,
    INT* pn
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pn
[out] Returns an integer.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetInt


ID3DXBaseEffect::GetIntArray Method

Gets an array of integers.

Syntax

HRESULT GetIntArray(

    D3DXHANDLE hParameter,
    INT* pn,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pn
[out] Returns an array of integers.
Count
[in] Number of integers in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetIntArray


ID3DXBaseEffect::GetMatrix Method

Gets a nontransposed matrix.

Syntax

HRESULT GetMatrix(

    D3DXHANDLE hParameter,
    D3DXMATRIX* pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns a nontransposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

If the destination matrix is larger than the source matrix, only the upper-left components of the destination matrix will be filled, and the remaining components will be set to zero.

See Also

ID3DXBaseEffect::SetMatrix


ID3DXBaseEffect::GetMatrixArray Method

Gets an array of nontransposed matrices.

Syntax

HRESULT GetMatrixArray(

    D3DXHANDLE hParameter,
    D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns an array of nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

If the destination matrices are larger than the source matrices, only the upper-left components of each destination matrix will be filled, and the remaining destination matrix components will be set to zero.

See Also

ID3DXBaseEffect::SetMatrixArray


ID3DXBaseEffect::GetMatrixPointerArray Method

Gets an array of pointers to nontransposed matrices.

Syntax

HRESULT GetMatrixPointerArray(

    D3DXHANDLE hParameter,
    D3DXMATRIX **ppMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppMatrix
[out] Array of pointers to nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

If the destination matrices are larger than the source matrices, only the upper-left components of each destination matrix will be filled, and the remaining destination matrix components will be set to zero.

See Also

ID3DXBaseEffect::GetMatrixArray


ID3DXBaseEffect::GetMatrixTranspose Method

Gets a transposed matrix.

Syntax

HRESULT GetMatrixTranspose(

    D3DXHANDLE hParameter,
    D3DXMATRIX* pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns a transposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

If the destination matrix is larger than the source matrix, only the upper-left elements of the destination matrix will be filled, and the remaining destination matrix components will be set to zero.

See Also

ID3DXBaseEffect::SetMatrixTranspose


ID3DXBaseEffect::GetMatrixTransposeArray Method

Gets an array of transposed matrices.

Syntax

HRESULT GetMatrixTransposeArray(

    D3DXHANDLE hParameter,
    D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns an array of transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

If the destination matrices are larger than the source matrices, only the upper-left components of each destination matrix will be filled, and the remaining destination matrix components will be set to zero.

See Also

ID3DXBaseEffect::SetMatrixTransposeArray


ID3DXBaseEffect::GetMatrixTransposePointerArray Method

Sets an array of pointers to transposed matrices.

Syntax

HRESULT GetMatrixTransposePointerArray(

    D3DXHANDLE hParameter,
    D3DXMATRIX** ppMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppMatrix
[in] Array of pointers to transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

If the destination matrices are larger than the source matrices, only the upper-left components of each destination matrix will be filled, and the remaining destination matrix components will be set to zero.

See Also

ID3DXBaseEffect::GetMatrixTransposeArray


ID3DXBaseEffect::GetParameter Method

Gets the handle of a top-level parameter or a structure member parameter.

Syntax

D3DXHANDLE GetParameter(

    D3DXHANDLE hParameter,
    UINT Index
);

Parameters

hParameter
[in] Handle of the parameter, or NULL for top-level parameters. See Handles.
Index
[in] Parameter index.

Return Value

Returns the handle of the specified parameter, or NULL if the index was invalid. See Handles.


ID3DXBaseEffect::GetParameterByName Method

Gets the handle of a top-level parameter or a structure member parameter by looking up its name.

Syntax

D3DXHANDLE GetParameterByName(

    D3DXHANDLE hParameter,
    LPCSTR pName
);

Parameters

hParameter
[in] Handle of the parameter, or NULL for top-level parameters. See Handles.
pName
[in] String containing the parameter name.

Return Value

Returns the handle of the specified parameter, or NULL if the index was invalid. See Handles.


ID3DXBaseEffect::GetParameterBySemantic Method

Gets the handle of a top-level parameter or a structure member parameter by looking up its semantic with a case-insensitive search.

Syntax

D3DXHANDLE GetParameterBySemantic(

    D3DXHANDLE hParameter,
    LPCSTR pSemantic
);

Parameters

hParameter
[in] Handle of the parameter, or NULL for top-level parameters. See Handles.
pSemantic
[in] String containing the semantic name.

Return Value

Returns the handle of the first parameter that matches the specified semantic, or NULL if the semantic was not found. See Handles.


ID3DXBaseEffect::GetParameterDesc Method

Gets a parameter or annotation description.

Syntax

HRESULT GetParameterDesc(

    D3DXHANDLE hParameter,
    D3DXPARAMETER_DESC* pDesc
);

Parameters

hParameter
[in] Parameter or annotation handle. See Handles.
pDesc
[out] Returns a description of the specified parameter or annotation. See D3DXPARAMETER_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXBaseEffect::GetParameterElement Method

Get the handle of an array element parameter.

Syntax

D3DXHANDLE GetParameterElement(

    D3DXHANDLE hParameter,
    UINT ElementIndex
);

Parameters

hParameter
[in] Handle of the array. See Handles.
ElementIndex
[in] Array element index.

Return Value

Returns the handle of the specified parameter, or NULL if either hParameter or ElementIndex is invalid. See Handles.

Remarks

This method is used to get an element of a parameter that is an array.


ID3DXBaseEffect::GetPass Method

Gets the handle of a pass.

Syntax

D3DXHANDLE GetPass(

    D3DXHANDLE hTechnique,
    UINT Index
);

Parameters

hTechnique
[in] Handle of the parent technique. See Handles.
Index
[in] Index for the pass.

Return Value

Returns the handle of the specified pass inside the specified technique, or NULL if the index was invalid. See Handles.


ID3DXBaseEffect::GetPassByName Method

Gets the handle of a pass by looking up its name.

Syntax

D3DXHANDLE GetPassByName(

    D3DXHANDLE hTechnique,
    LPCSTR pName
);

Parameters

hTechnique
[in] Handle of the parent technique. See Handles.
pName
[in] String containing the pass name.

Return Value

Returns the handle of the first pass inside the specified technique that has the specified name, or NULL if the name was not found. See Handles.


ID3DXBaseEffect::GetPassDesc Method

Gets a pass description.

Syntax

HRESULT GetPassDesc(

    D3DXHANDLE hPass,
    D3DXPASS_DESC* pDesc
);

Parameters

hPass
[in] Pass handle. See Handles.
pDesc
[out] Returns a description of the specified pass. See D3DXPASS_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXBaseEffect::GetPixelShader Method

Gets a pixel shader.

Syntax

HRESULT GetPixelShader(

    D3DXHANDLE hParameter,
    LPDIRECT3DPIXELSHADER9* ppPShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppPShader
[out] Returns a pixel shader object. See IDirect3DPixelShader9 object.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetPixelShader


ID3DXBaseEffect::GetString Method

Gets a string.

Syntax

HRESULT GetString(

    D3DXHANDLE hParameter,
    LPCSTR* ppString
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppString
[out] Returns a string identified by hParameter.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetString


ID3DXBaseEffect::GetTechnique Method

Gets the handle of a technique.

Syntax

D3DXHANDLE GetTechnique(

    UINT Index
);

Parameters

Index
[in] Technique index.

Return Value

Returns the handle of the specified technique, or NULL if the index was invalid. See Handles.


ID3DXBaseEffect::GetTechniqueByName Method

Gets the handle of a technique by looking up its name.

Syntax

D3DXHANDLE GetTechniqueByName(

    LPCSTR pName
);

Parameters

pName
[in] String containing the technique name.

Return Value

Returns the handle of the first technique that has the specified name, or NULL if the name was not found. See Handles.


ID3DXBaseEffect::GetTechniqueDesc Method

Gets a technique description.

Syntax

HRESULT GetTechniqueDesc(

    D3DXHANDLE hTechnique,
    D3DXTECHNIQUE_DESC* pDesc
);

Parameters

hTechnique
[in] Technique handle. See Handles.
pDesc
[out] Returns a description of the technique. See D3DXTECHNIQUE_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXBaseEffect::GetTexture Method

Gets a texture.

Syntax

HRESULT GetTexture(

    D3DXHANDLE hParameter,
    LPDIRECT3DBASETEXTURE9* ppTexture
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppTexture
[out] Returns a texture object. See IDirect3DBaseTexture9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetTexture


ID3DXBaseEffect::GetValue Method

Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Getxxx calls in ID3DXBaseEffect.

Syntax

HRESULT GetValue(

    D3DXHANDLE hParameter,
    LPVOID pData,
    UINT Bytes
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pData
[out] Returns a buffer containing the value.
Bytes
[in] [in] Number of bytes in the buffer. Pass in D3DX_DEFAULT if you know your buffer is large enough to contain the entire parameter, and you want to skip size validation.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetValue


ID3DXBaseEffect::GetVector Method

Gets a vector.

Syntax

HRESULT GetVector(

    D3DXHANDLE hParameter,
    D3DXVECTOR4* pVector
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[out] Returns a 4-D vector.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the destination vector is larger than the source vector, only the initial components of the destination vector will be filled, and the remaining components will be set to zero.

See Also

ID3DXBaseEffect::SetVector


ID3DXBaseEffect::GetVectorArray Method

Gets an array of vectors.

Syntax

HRESULT GetVectorArray(

    D3DXHANDLE hParameter,
    D3DXVECTOR4* pVector,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[out] Returns an array of 4-D floating point vectors.
Count
[in] Number of vectors in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the destination vectors are larger than the source vectors, only the initial components of each destination vector will be filled, and the remaining destination vector components will be set to zero.

See Also

ID3DXBaseEffect::SetVectorArray


ID3DXBaseEffect::GetVertexShader Method

Gets a vertex shader.

Syntax

HRESULT GetVertexShader(

    D3DXHANDLE hParameter,
    LPDIRECT3DVERTEXSHADER9* ppVShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppVShader
[out] Returns a vertex shader object. See IDirect3DVertexShader9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXBaseEffect::SetArrayRange Method

Set the range of an array to pass to the device.

Syntax

HRESULT SetArrayRange(

    D3DXHANDLE hParameter,
    UINT Start,
    UINT Stop
);

Parameters

hParameter
[in] Unique identifier. See Handles.
Start
[in] Start index.
Stop
[in] Stop index.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXBaseEffect::SetBool Method

Sets a BOOL value.

Syntax

HRESULT SetBool(

    D3DXHANDLE hParameter,
    BOOL b
);

Parameters

hParameter
[in] Unique identifier. See Handles.
b
[in] Boolean value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetBool


ID3DXBaseEffect::SetBoolArray Method

Sets an array of Boolean values.

Syntax

HRESULT SetBoolArray(

    D3DXHANDLE hParameter,
    CONST BOOL* pB,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pB
[in] Array of Boolean values.
Count
[in] Number of Boolean values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetBoolArray


ID3DXBaseEffect::SetFloat Method

Sets a floating point value.

Syntax

HRESULT SetFloat(

    D3DXHANDLE hParameter,
    FLOAT f
);

Parameters

hParameter
[in] Unique identifier. See Handles.
f
[in] Floating point value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetFloat


ID3DXBaseEffect::SetFloatArray Method

Sets an array of floating point values.

Syntax

HRESULT SetFloatArray(

    D3DXHANDLE hParameter,
    CONST FLOAT* pf,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pf
[in] Array of floating point values.
Count
[in] Number of floating point values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetFloatArray


ID3DXBaseEffect::SetInt Method

Sets an integer.

Syntax

HRESULT SetInt(

    D3DXHANDLE hParameter,
    INT n
);

Parameters

hParameter
[in] Unique identifier. See Handles.
n
[in] Integer value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetInt


ID3DXBaseEffect::SetIntArray Method

Sets an array of integers.

Syntax

HRESULT SetIntArray(

    D3DXHANDLE hParameter,
    CONST INT* pn,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pn
[in] Array of integers.
Count
[in] Number of integers in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetIntArray


ID3DXBaseEffect::SetMatrix Method

Sets a non-transposed matrix.

Syntax

HRESULT SetMatrix(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Pointer to a nontransposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A non-transposed matrix contains row-major data. In other words, each vector is contained in a row.

If the destination matrix is smaller than the source matrix, the additional components of the source matrix will be ignored.

See Also

ID3DXBaseEffect::GetMatrix


ID3DXBaseEffect::SetMatrixArray Method

Sets an array of nontransposed matrices.

Syntax

HRESULT SetMatrixArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Array of nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

If the destination matrices are smaller than the source matrices, the additional components of the source matrices will be ignored.

See Also

ID3DXBaseEffect::GetMatrixArray


ID3DXBaseEffect::SetMatrixPointerArray Method

Sets an array of pointers to nontransposed matrices.

Syntax

HRESULT SetMatrixPointerArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX** ppMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppMatrix
[in] Array of pointers to nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

If the destination matrices are smaller than the source matrices, the additional components of the source matrices will be ignored.

See Also

ID3DXBaseEffect::GetMatrixArray


ID3DXBaseEffect::SetMatrixTranspose Method

Sets a transposed matrix.

Syntax

HRESULT SetMatrixTranspose(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Pointer to a transposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

If the destination matrix is smaller than the source matrix, the additional components of the source matrix will be ignored.

See Also

ID3DXBaseEffect::GetMatrixTranspose


ID3DXBaseEffect::SetMatrixTransposeArray Method

Sets an array of transposed matrices.

Syntax

HRESULT SetMatrixTransposeArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Array of transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

If the destination matrices are smaller than the source matrices, the additional components of the source matrices will be ignored.

See Also

ID3DXBaseEffect::GetMatrixTransposeArray


ID3DXBaseEffect::SetMatrixTransposePointerArray Method

Sets an array of pointers to transposed matrices.

Syntax

HRESULT SetMatrixTransposePointerArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX** ppMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppMatrix
[in] Array of pointers to transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

If the destination matrices are smaller than the source matrices, the additional components of the source matrices will be ignored.

See Also

ID3DXBaseEffect::GetMatrixTransposeArray


ID3DXBaseEffect::SetPixelShader Method

Sets a pixel shader.

Syntax

HRESULT SetPixelShader(

    D3DXHANDLE hParameter,
    LPDIRECT3DPIXELSHADER9 pPShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pPShader
[in] Pixel shader object. See IDirect3DPixelShader9 object.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetPixelShader


ID3DXBaseEffect::SetString Method

Sets a string.

Syntax

HRESULT SetString(

    D3DXHANDLE hParameter,
    LPCSTR pString
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pString
[in] String to set.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetString


ID3DXBaseEffect::SetTexture Method

Sets a texture.

Syntax

HRESULT SetTexture(

    D3DXHANDLE hParameter,
    LPDIRECT3DBASETEXTURE9 pTexture
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pTexture
[in] Texture object. See IDirect3DBaseTexture9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetTexture


ID3DXBaseEffect::SetValue Method

Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Setxxx calls in ID3DXBaseEffect.

Syntax

HRESULT SetValue(

    D3DXHANDLE hParameter,
    LPCVOID pData,
    UINT Bytes
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pData
[in] Pointer to a buffer containing data.
Bytes
[in] [in] Number of bytes in the buffer. Pass in D3DX_DEFAULT if you know your buffer is large enough to contain the entire parameter, and you want to skip size validation.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetValue


ID3DXBaseEffect::SetVector Method

Sets a vector.

Syntax

HRESULT SetVector(

    D3DXHANDLE hParameter,
    CONST D3DXVECTOR4* pVector
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[in] Pointer to a 4-D vector.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the destination vector is smaller than the source vector, the additional components of the source vector will be ignored.

See Also

ID3DXBaseEffect::GetVector


ID3DXBaseEffect::SetVectorArray Method

Sets an array of vectors.

Syntax

HRESULT SetVectorArray(

    D3DXHANDLE hParameter,
    CONST D3DXVECTOR4* pVector,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[in] Array of 4-D floating point vectors.
Count
[in] Number of vectors in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the destination vectors are smaller than the source vectors, the additional components of the source vectors will be ignored.

See Also

ID3DXBaseEffect::GetVectorArray


ID3DXBaseEffect::SetVertexShader Method

Sets a vertex shader.

Syntax

HRESULT SetVertexShader(

    D3DXHANDLE hParameter,
    LPDIRECT3DVERTEXSHADER9 pVertexShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVertexShader
[in] Vertex shader object. See IDirect3DVertexShader9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetVertexShader


ID3DXEffect Interface

Used to set and query effects, and to choose techniques. An effect object can contain multiple techniques to render the same effect.

ID3DXEffect Members

ApplyParameterBlock | Assign a state value to each effect parameter in a parameter block.
Begin | Starts an active technique.
BeginParameterBlock | Capture parameter effect state changes.
BeginPass | Begins a pass, within the active technique.
CloneEffect | Creates a clone of an effect.
CommitChanges | Propagate state changes that occur inside of an active pass to the device before rendering.
End | Ends an active technique.
EndParameterBlock | Stop capturing effect parameter state changes.
EndPass | End an active pass.
FindNextValidTechnique | Searches for the next valid technique, starting at the technique after the specified technique.
GetAnnotation | Gets the handle of an annotation.
GetAnnotationByName | Gets the handle of an annotation by looking up its name.
GetBool | Gets a BOOL value.
GetBoolArray | Gets an array of BOOL values.
GetCurrentTechnique | Gets the current technique.
GetDesc | Gets the effect description.
GetDevice | Retrieves the device associated with the effect.
GetFloat | Gets a floating point value.
GetFloatArray | Gets an array of floating point values.
GetFunction | Gets the handle of a function.
GetFunctionByName | Gets the handle of a function by looking up its name.
GetFunctionDesc | Gets a function description.
GetInt | Gets an integer.
GetIntArray | Gets an array of integers.
GetMatrix | Gets a nontransposed matrix.
GetMatrixArray | Gets an array of nontransposed matrices.
GetMatrixPointerArray | Gets an array of pointers to nontransposed matrices.
GetMatrixTranspose | Gets a transposed matrix.
GetMatrixTransposeArray | Gets an array of transposed matrices.
GetMatrixTransposePointerArray | Sets an array of pointers to transposed matrices.
GetParameter | Gets the handle of a top-level parameter or a structure member parameter.
GetParameterByName | Gets the handle of a top-level parameter or a structure member parameter by looking up its name.
GetParameterBySemantic | Gets the handle of a top-level parameter or a structure member parameter by looking up its semantic with a case-insensitive search.
GetParameterDesc | Gets a parameter or annotation description.
GetParameterElement | Get the handle of an array element parameter.
GetPass | Gets the handle of a pass.
GetPassByName | Gets the handle of a pass by looking up its name.
GetPassDesc | Gets a pass description.
GetPixelShader | Gets a pixel shader.
GetPool | Gets a pointer to the pool of shared parameters.
GetStateManager | Get the effect state manager.
GetString | Gets a string.
GetTechnique | Gets the handle of a technique.
GetTechniqueByName | Gets the handle of a technique by looking up its name.
GetTechniqueDesc | Gets a technique description.
GetTexture | Gets a texture.
GetValue | Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Getxxx calls in ID3DXBaseEffect.
GetVector | Gets a vector.
GetVectorArray | Gets an array of vectors.
GetVertexShader | Gets a vertex shader.
IsParameterUsed | Determines if a parameter is used by the technique.
OnLostDevice | Releases all references to video memory resources and deletes all state blocks.
OnResetDevice | Should be called after the device has been reset.
SetArrayRange | Set the range of an array to pass to the device.
SetBool | Sets a BOOL value.
SetBoolArray | Sets an array of Boolean values.
SetFloat | Sets a floating point value.
SetFloatArray | Sets an array of floating point values.
SetInt | Sets an integer.
SetIntArray | Sets an array of integers.
SetMatrix | Sets a non-transposed matrix.
SetMatrixArray | Sets an array of nontransposed matrices.
SetMatrixPointerArray | Sets an array of pointers to nontransposed matrices.
SetMatrixTranspose | Sets a transposed matrix.
SetMatrixTransposeArray | Sets an array of transposed matrices.
SetMatrixTransposePointerArray | Sets an array of pointers to transposed matrices.
SetPixelShader | Sets a pixel shader.
SetStateManager | Set the effect state manager.
SetString | Sets a string.
SetTechnique | Sets the active technique.
SetTexture | Sets a texture.
SetValue | Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Setxxx calls in ID3DXBaseEffect.
SetVector | Sets a vector.
SetVectorArray | Sets an array of vectors.
SetVertexShader | Sets a vertex shader.
ValidateTechnique | Validate a technique.

Remarks

The ID3DXEffect interface is obtained by calling D3DXCreateEffect, D3DXCreateEffectFromFile, or D3DXCreateEffectFromResource.

The LPD3DXEFFECT type is defined as a pointer to this interface.

typedef interface ID3DXEffect ID3DXEffect;
typedef interface ID3DXEffect *LPD3DXEFFECT;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | ID3DXBaseEffect
Header | d3dx9effect.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateEffect, D3DXCreateEffectFromFile, D3DXCreateEffectFromResource


ID3DXEffect::ApplyParameterBlock Method

Assign a state value to each effect parameter in a parameter block.

Syntax

HRESULT ApplyParameterBlock(

    D3DXHANDLE hParameterBlock
);

Parameters

hParameterBlock
[in] A handle to the parameter block. This is the handle returned by ID3DXEffect::EndParameterBlock.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.


ID3DXEffect::Begin Method

Starts an active technique.

Syntax

HRESULT Begin(

    UINT* pPasses,
    DWORD Flags
);

Parameters

pPasses
[out] Pointer to a value returned that indicates the number of passes needed to render the current technique.
Flags
[in] DWORD that determines if state modified by an effect is saved and restored. The default value 0 specifies that ID3DXEffect::Begin and ID3DXEffect::End will save and restore all state modified by the effect (including pixel and vertex shader constants). Valid flags can be seen at Shader State.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

An application sets one active technique in the effect system by calling ID3DXEffect::Begin. The effect system responds by capturing all the pipeline state that can be changed by the technique in a state block. An application signals the end of a technique by calling ID3DXEffect::End, which uses the state block to restore the original state. The effect system therefore takes care of saving state when a technique becomes active and restoring state when a technique ends. If you choose to disable this save and restore functionality, see D3DXFX_DONOTSAVESAMPLERSTATE.

Within the ID3DXEffect::Begin and ID3DXEffect::End pair, an application uses ID3DXEffect::BeginPass to set the active pass, ID3DXEffect::CommitChanges if any state changes occured after the pass was activated, and ID3DXEffect::EndPass to end the active pass.


ID3DXEffect::BeginParameterBlock Method

Capture parameter effect state changes.

Syntax

HRESULT BeginParameterBlock(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

Capture effect parameter state changes until ID3DXEffect::EndParameterBlock is called. Effect parameters include any state changes outside of a pass.


ID3DXEffect::BeginPass Method

Begins a pass, within the active technique.

Syntax

HRESULT BeginPass(

    UINT Pass
);

Parameters

Pass
[in] A zero-based integer index into the technique.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

An application sets one active pass (within one active technique) in the effect system by calling ID3DXEffect::BeginPass. An application signals the end of the active pass by calling ID3DXEffect::EndPass. ID3DXEffect::BeginPass and ID3DXEffect::EndPass must occur in a matching pair, within a matching pair of ID3DXEffect::Begin and ID3DXEffect::End calls.

If the application changes any effect state using any of the Effect::Setx methods inside of a ID3DXEffect::BeginPass/ID3DXEffect::EndPass matching pair, the application must call ID3DXEffect::CommitChanges to set the update the device with the state changes. If no state changes occur within a ID3DXEffect::BeginPass and ID3DXEffect::EndPass matching pair, it is not necessary to call ID3DXEffect::CommitChanges.


ID3DXEffect::CloneEffect Method

Creates a clone of an effect.

Syntax

HRESULT CloneEffect(

    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXEFFECT* ppEffect
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the effect.
ppEffect
[out] Pointer to an ID3DXEffect interface, containing the cloned effect.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

To update shared and non-shared parameters in an active technique of a cloned effect, see ID3DXEffect::CommitChanges.


ID3DXEffect::CommitChanges Method

Propagate state changes that occur inside of an active pass to the device before rendering.

Syntax

HRESULT CommitChanges(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

If the application changes any effect state using any of the ID3DXEffect::Setx methods inside of an ID3DXEffect::BeginPass/ID3DXEffect::EndPass matching pair, the application must call ID3DXEffect::CommitChanges before any DrawxPrimitive call to propagate state changes to the device before rendering. If no state changes occur within a ID3DXEffect::BeginPass and ID3DXEffect::EndPass matching pair, it is not necessary to call ID3DXEffect::CommitChanges.

This is slightly different for any shared parameters in a cloned effect. When a technique is active on a cloned effect (that is, when ID3DXEffect::Begin has been called but and ID3DXEffect::End has not been called), ID3DXEffect::CommitChanges updates parameters that are not shared as expected. To update a shared parameter (only for a cloned effect whose technique is active), call ID3DXEffect::End to deactivate the technique and ID3DXEffect::Begin to reactivate the technique before calling ID3DXEffect::CommitChanges.


ID3DXEffect::End Method

Ends an active technique.

Syntax

HRESULT End(VOID);

Return Value

This method always returns the value S_OK.

Remarks

All rendering in an effect is done within a matching pair of ID3DXEffect::Begin and ID3DXEffect::End calls. After all passes are rendered, ID3DXEffect::End must be called to end the active technique. The effect system responds by using the state block created when ID3DXEffect::Begin was called, to automatically restore the pipeline state before ID3DXEffect::Begin.

By default, the effect system takes care of saving state prior to a technique, and restoring state after a technique. If you choose to disable this save and restore functionality, see D3DXFX_DONOTSAVESAMPLERSTATE.


ID3DXEffect::EndParameterBlock Method

Stop capturing effect parameter state changes.

Syntax

D3DXHANDLE EndParameterBlock(VOID);

Return Value

Returns a handle to the parameter state block.

Remarks

Start capturing effect parameter state changes by calling ID3DXEffect::BeginParameterBlock. All effect parameters that change state (before End is called) will be saved in an effect parameter state block. ID3DXEffect::ApplyParameterBlock is then used to apply this block of state changes to effect parameters. Effect parameters include any state changes outside of a pass.


ID3DXEffect::EndPass Method

End an active pass.

Syntax

HRESULT EndPass(VOID);

Return Value

This method always returns the value S_OK.

Remarks

An application signals the end of rendering an active pass by calling ID3DXEffect::EndPass. Each ID3DXEffect::EndPass must be part of a matching pair of ID3DXEffect::BeginPass and ID3DXEffect::EndPass calls.

Each matching pair of ID3DXEffect::BeginPass and ID3DXEffect::EndPass calls must be located within a matching pair of ID3DXEffect::Begin and ID3DXEffect::End calls.

If the application changes any effect state using any of the Effect::Setx methods inside of a ID3DXEffect::BeginPass/ID3DXEffect::EndPass matching pair, the application must call ID3DXEffect::CommitChanges before any DrawxPrimitive call to propagate state changes to the device before rendering.


ID3DXEffect::FindNextValidTechnique Method

Searches for the next valid technique, starting at the technique after the specified technique.

Syntax

HRESULT FindNextValidTechnique(

    D3DXHANDLE hTechnique,
    D3DXHANDLE* pTechnique
);

Parameters

hTechnique
[in] Unique identifier to a technique. See Handles. Specify NULL for this parameter to find the first valid technique.
pTechnique
[out] Pointer to an identifier for the next technique. NULL is returned if this is the last technique. See Handles.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

D3DXTECHNIQUE_DESC, ID3DXEffect::ValidateTechnique


ID3DXEffect::GetCurrentTechnique Method

Gets the current technique.

Syntax

D3DXHANDLE GetCurrentTechnique(VOID);

Return Value

A unique identifier to the current technique. See Handles.


ID3DXEffect::GetDevice Method

Retrieves the device associated with the effect.

Syntax

HRESULT GetDevice(

    LPDIRECT3DDEVICE9* ppDevice
);

Parameters

ppDevice
[out] Address of a pointer to an IDirect3DDevice9 interface, representing the device associated with the effect.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count for the IDirect3DDevice9 interface. Be sure to call IUnknown::Release when you are done using this IDirect3DDevice9 interface or you will have a memory leak.


ID3DXEffect::GetPool Method

Gets a pointer to the pool of shared parameters.

Syntax

HRESULT GetPool(

    LPD3DXEFFECTPOOL* ppPool
);

Parameters

ppPool
[out] Pointer to a ID3DXEffectPool object.

Return Value

This method always returns the value S_OK.

Remarks

Pools contain shared parameters between effects. See Cloning and Sharing.


ID3DXEffect::GetStateManager Method

Get the effect state manager.

Syntax

HRESULT GetStateManager(

    LPD3DXEFFECTSTATEMANAGER* ppManager
);

Parameters

ppManager
[out] Returns a pointer to the state manager. See ID3DXEffectStateManager.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

The ID3DXEffectStateManager is a user-implemented interface that furnishes callbacks into an application for setting device state from an effect.

See Also

ID3DXEffect::SetStateManager


ID3DXEffect::IsParameterUsed Method

Determines if a parameter is used by the technique.

Syntax

BOOL IsParameterUsed(

    D3DXHANDLE hParameter,
    D3DXHANDLE hTechnique
);

Parameters

hParameter
[in] Unique identifier for the parameter. See Handles.
hTechnique
[in] Unique identifier for the technique. See Handles.

Return Value

Returns TRUE if the parameter is being used and returns FALSE if the parameter is not being used.


ID3DXEffect::OnLostDevice Method

Releases all references to video memory resources and deletes all state blocks.

Syntax

HRESULT OnLostDevice(VOID);

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method should be called whenever the device is lost. Before this object can be used again, the device must be reset and the ID3DXEffect::OnResetDevice method called.


ID3DXEffect::OnResetDevice Method

Should be called after the device has been reset.

Syntax

HRESULT OnResetDevice(VOID);

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method should be called after the device has been reset, before any other methods are called.


ID3DXEffect::SetStateManager Method

Set the effect state manager.

Syntax

HRESULT SetStateManager(

    LPD3DXEFFECTSTATEMANAGER pManager
);

Parameters

pManager
[in] A pointer to the state manager. See ID3DXEffectStateManager.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.

Remarks

The ID3DXEffectStateManager is a user-implemented interface that furnishes callbacks into an application for setting device state from an effect.

See Also

ID3DXEffect::GetStateManager


ID3DXEffect::SetTechnique Method

Sets the active technique.

Syntax

HRESULT SetTechnique(

    D3DXHANDLE hTechnique
);

Parameters

hTechnique
[in] Unique handle to the technique. See Handles.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXEffect::ValidateTechnique Method

Validate a technique.

Syntax

HRESULT ValidateTechnique(

    D3DXHANDLE hTechnique
);

Parameters

hTechnique
[in] Unique identifier. See Handles.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXEffect::SetTechnique


ID3DXEffectCompiler Interface

The ID3DXEffectCompiler interface compiles an effect from a function or from a vertex shader.

ID3DXEffectCompiler Members

CompileEffect | Compile an effect.
CompileShader | Compile a shader from an effect that contains one or more functions.
GetAnnotation | Gets the handle of an annotation.
GetAnnotationByName | Gets the handle of an annotation by looking up its name.
GetBool | Gets a BOOL value.
GetBoolArray | Gets an array of BOOL values.
GetDesc | Gets the effect description.
GetFloat | Gets a floating point value.
GetFloatArray | Gets an array of floating point values.
GetFunction | Gets the handle of a function.
GetFunctionByName | Gets the handle of a function by looking up its name.
GetFunctionDesc | Gets a function description.
GetInt | Gets an integer.
GetIntArray | Gets an array of integers.
GetLiteral | Gets a literal status of a parameter. A literal parameter has a value that doesn't change during the lifetime of an effect.
GetMatrix | Gets a nontransposed matrix.
GetMatrixArray | Gets an array of nontransposed matrices.
GetMatrixPointerArray | Gets an array of pointers to nontransposed matrices.
GetMatrixTranspose | Gets a transposed matrix.
GetMatrixTransposeArray | Gets an array of transposed matrices.
GetMatrixTransposePointerArray | Sets an array of pointers to transposed matrices.
GetParameter | Gets the handle of a top-level parameter or a structure member parameter.
GetParameterByName | Gets the handle of a top-level parameter or a structure member parameter by looking up its name.
GetParameterBySemantic | Gets the handle of a top-level parameter or a structure member parameter by looking up its semantic with a case-insensitive search.
GetParameterDesc | Gets a parameter or annotation description.
GetParameterElement | Get the handle of an array element parameter.
GetPass | Gets the handle of a pass.
GetPassByName | Gets the handle of a pass by looking up its name.
GetPassDesc | Gets a pass description.
GetPixelShader | Gets a pixel shader.
GetString | Gets a string.
GetTechnique | Gets the handle of a technique.
GetTechniqueByName | Gets the handle of a technique by looking up its name.
GetTechniqueDesc | Gets a technique description.
GetTexture | Gets a texture.
GetValue | Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Getxxx calls in ID3DXBaseEffect.
GetVector | Gets a vector.
GetVectorArray | Gets an array of vectors.
GetVertexShader | Gets a vertex shader.
SetArrayRange | Set the range of an array to pass to the device.
SetBool | Sets a BOOL value.
SetBoolArray | Sets an array of Boolean values.
SetFloat | Sets a floating point value.
SetFloatArray | Sets an array of floating point values.
SetInt | Sets an integer.
SetIntArray | Sets an array of integers.
SetLiteral | Toggles the literal status of a parameter. A literal parameter has a value that doesn't change during the lifetime of an effect.
SetMatrix | Sets a non-transposed matrix.
SetMatrixArray | Sets an array of nontransposed matrices.
SetMatrixPointerArray | Sets an array of pointers to nontransposed matrices.
SetMatrixTranspose | Sets a transposed matrix.
SetMatrixTransposeArray | Sets an array of transposed matrices.
SetMatrixTransposePointerArray | Sets an array of pointers to transposed matrices.
SetPixelShader | Sets a pixel shader.
SetString | Sets a string.
SetTexture | Sets a texture.
SetValue | Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Setxxx calls in ID3DXBaseEffect.
SetVector | Sets a vector.
SetVectorArray | Sets an array of vectors.
SetVertexShader | Sets a vertex shader.

Remarks

The ID3DXEffectCompiler interface is obtained by calling D3DXCreateEffectCompiler, D3DXCreateEffectCompilerFromFile, or D3DXCreateEffectCompilerFromResource.

The LPD3DXEFFECTCOMPILER type is defined as a pointer to this interface.

typedef interface ID3DXEffectCompiler ID3DXEffectCompiler;
typedef interface ID3DXEffectCompiler *LPD3DXEFFECTCOMPILER;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | ID3DXBaseEffect
Header | d3dx9effect.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateEffectCompiler, D3DXCreateEffectCompilerFromFile, D3DXCreateEffectCompilerFromResource


ID3DXEffectCompiler::CompileEffect Method

Compile an effect.

Syntax

HRESULT CompileEffect(

    DWORD Flags,
    LPD3DXBUFFER *ppEffect,
    LPD3DXBUFFER *ppErrorMsgs
);

Parameters

Flags
[in] Compile options. For more information, see D3DXSHADER Compile Options.
ppEffect
[out, retval] Buffer containing the compiled effect. For more information about accessing the buffer, see ID3DXBuffer.
ppErrorMsgs
[out, retval] Buffer containing at least the first compile error message that occurred. This includes effect compiler errors and high-level language compile errors. For more information about accessing the buffer, see ID3DXBuffer.

Return Value

If the method succeeds, the return value is S_OK.

If the arguments are invalid, the method will return D3DERR_INVALIDCALL.

If the method fails, the return value will be E_FAIL.


ID3DXEffectCompiler::CompileShader Method

Compile a shader from an effect that contains one or more functions.

Syntax

HRESULT CompileShader(

    D3DXHANDLE hFunction,
    LPCSTR pTarget,
    DWORD Flags,
    LPD3DXBUFFER* ppShader,
    LPD3DXBUFFER* ppErrorMsgs,
    LPD3DXCONSTANTTABLE* ppConstantTable
);

Parameters

hFunction
[in] Unique identifier to the function to be compiled. This value must not be NULL. See Handles.
pTarget
[in] Identifies the shader version. Use the D3DVS_VERSION macro to generate the encoded version number. See the remarks section for shader versions.
Flags
[in] Compile options. For more information, see D3DXSHADER Compile Options.
ppShader
[out, retval] Buffer containing the compiled shader. The compiler shader is an array of DWORDs. For more information about accessing the buffer, see ID3DXBuffer.
ppErrorMsgs
[out, retval] Buffer containing at least the first compile error message that occurred. This includes effect compiler errors and high-level language compile errors. For more information about accessing the buffer, see ID3DXBuffer.
ppConstantTable
[out] Returns an ID3DXConstantTable interface, which can be used to access shader constants. This value may be NULL.

Return Value

If the method succeeds, the return value is S_OK.

If the arguments are invalid, the method will return D3DERR_INVALIDCALL.

If the method fails, the return value will be E_FAIL.

Remarks

Targets can be specified for vertex shaders, pixel shaders, and texture fill functions.

Vertex shader targets | vs_1_1, vs_2_0, vs_2_sw, vs_3_0
Pixel shader targets | ps_1_1, ps_1_2, ps_1_3, ps_1_4, ps_2_0, ps_2_sw, ps_3_0
Texture fill targets | tx_0, tx_1

This method compiles a shader from a function that is written in a C-like language. For more information, see HLSL Shader Reference.

See Also

D3DXGetShaderConstantTable


ID3DXEffectCompiler::GetLiteral Method

Gets a literal status of a parameter. A literal parameter has a value that doesn't change during the lifetime of an effect.

Syntax

HRESULT GetLiteral(

    D3DXHANDLE hParameter,
    BOOL* pLiteral
);

Parameters

hParameter
[in] Unique identifier to a parameter. See Handles.
pLiteral
[out] Returns True if the parameter is a literal, and False otherwise.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This methods only changes whether the parameter is a literal or not. To change the value of a parameter, use a method like ID3DXEffectCompiler::SetBool or ID3DXEffectCompiler::SetValue.

See Also

Usages and Literals, ID3DXEffectCompiler::SetLiteral


ID3DXEffectCompiler::SetLiteral Method

Toggles the literal status of a parameter. A literal parameter has a value that doesn't change during the lifetime of an effect.

Syntax

HRESULT SetLiteral(

    D3DXHANDLE hParameter,
    BOOL Literal
);

Parameters

hParameter
[in] Unique identifier to a parameter. See Handles.
Literal
[in] Set to True to make the parameter a literal, and False if the parameter can change value during the shader lifetime.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This methods only changes whether the parameter is a literal or not. To change the value of a parameter, use a method like ID3DXEffectCompiler::SetBool or ID3DXEffectCompiler::SetValue.

See Also

Usages and Literals, ID3DXEffectCompiler::GetLiteral


ID3DXEffectPool Interface

Applications use the ID3DXEffectPool interface to identify parameters that are going to be shared across effects. See parameter sharing in Cloning and Sharing. This interface has no methods.

Remarks

The ID3DXEffectPool interface is obtained by calling D3DXCreateEffectPool.

The LPD3DXEFFECTPOOL type is defined as a pointer to this interface.

typedef interface ID3DXEffectPool ID3DXEffectPool;
typedef interface ID3DXEffectPool *LPD3DXEFFECTPOOL;

Interface Information

Inherits from | IUnknown
Header | d3dx9effect.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXEffectStateManager Interface

This is a user-implemented interface that allows a user to set the device state from an effect. Each of the methods in this interface must be implemented by the user and will then be used as callbacks to the application when either of the following occur:

  • An effect calls ID3DXEffect::BeginPass.
  • Effect state is dynamically updated by calling the appropriate state change application programming interface (API). See individual method pages for details.

When an application uses the state manager to implement custom callbacks, an effect no longer automatically saves and restores state when calling ID3DXEffect::BeginPass and ID3DXEffect::EndPass. Because the application has implemented a custom save and restore behavior in the callbacks, this automatic behavior is bypassed.

ID3DXEffectStateManager Members

LightEnable | A callback function that must be implemented by a user to enable/disable a light.
SetFVF | A callback function that must be implemented by a user to set a flexible vertex format (FVF) code.
SetLight | A callback function that must be implemented by a user to set a light.
SetMaterial | A callback function that must be implemented by a user to set material state.
SetNPatchMode | A callback function that must be implemented by a user to set the number of subdivision segments for N-patches.
SetPixelShader | A callback function that must be implemented by a user to set a pixel shader.
SetPixelShaderConstantB | A callback function that must be implemented by a user to set an array of vertex shader Boolean constants.
SetPixelShaderConstantF | A callback function that must be implemented by a user to set an array of vertex shader floating-point constants.
SetPixelShaderConstantI | A callback function that must be implemented by a user to set an array of vertex shader integer constants.
SetRenderState | A callback function that must be implemented by a user to set render state.
SetSamplerState | A callback function that must be implemented by a user to set a sampler.
SetTexture | A callback function that must be implemented by a user to set a texture.
SetTextureStageState | A callback function that must be implemented by a user to set the texture stage state.
SetTransform | A callback function that must be implemented by a user to set a transform.
SetVertexShader | A callback function that must be implemented by a user to set a vertex shader.
SetVertexShaderConstantB | A callback function that must be implemented by a user to set an array of vertex shader Boolean constants.
SetVertexShaderConstantF | A callback function that must be implemented by a user to set an array of vertex shader floating-point constants.
SetVertexShaderConstantI | A callback function that must be implemented by a user to set an array of vertex shader integer constants.

Remarks

A user creates an ID3DXEffectStateManager interface by implementing a class that derives from this interface, and implementing all the interface methods. Once the interface is created, you can get or set the state manager within an effect using ID3DXEffect::GetStateManager and ID3DXEffect::SetStateManager.

The LPD3DXEFFECTSTATEMANAGER type is defined as a pointer to this interface.

typedef interface ID3DXEffectStateManager ID3DXEffectStateManager;
typedef interface ID3DXEffectStateManager *LPD3DXEFFECTSTATEMANAGER;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9effect.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXEffectStateManager::LightEnable Method

A callback function that must be implemented by a user to enable/disable a light.

Syntax

HRESULT LightEnable(

    DWORD Index,
    BOOL Enable
);

Parameters

Index
[in] The zero-based index of the light. This is the same index in IDirect3DDevice9::SetLight.
Enable
[in] True to enable the light, false otherwise.

Return Value

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::LightEnable) will fail.


ID3DXEffectStateManager::SetFVF Method

A callback function that must be implemented by a user to set a flexible vertex format (FVF) code.

Syntax

HRESULT SetFVF(

    DWORD FVF
);

Parameters

FVF
[in] The FVF constant, that detemines how to interpret vertex data. See D3DFVF.

Return Value

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetFVF) will fail.


ID3DXEffectStateManager::SetLight Method

A callback function that must be implemented by a user to set a light.

Syntax

HRESULT SetLight(

    DWORD Index,
    CONST D3DLIGHT9* pLight
);

Parameters

Index
[in] The zero-based index of the light. This is the same index in IDirect3DDevice9::SetLight.
pLight
[in] The light object. See D3DLIGHT9.

Return Value

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetLight) will fail.


ID3DXEffectStateManager::SetMaterial Method

A callback function that must be implemented by a user to set material state.

Syntax

HRESULT SetMaterial(

    CONST D3DMATERIAL9* pMaterial
);

Parameters

pMaterial
[in] A pointer to the material state. See D3DMATERIAL9.

Return Value

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetMaterial) will fail.


ID3DXEffectStateManager::SetNPatchMode Method

A callback function that must be implemented by a user to set the number of subdivision segments for N-patches.

Syntax

HRESULT SetNPatchMode(

    FLOAT nSegments
);

Parameters

nSegments
[in] Break the surface into this number of subdivisions. This is the same as the number used by IDirect3DDevice9::SetNPatchMode.

Return Value

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetNPatchMode) will fail.


ID3DXEffectStateManager::SetPixelShader Method

A callback function that must be implemented by a user to set a pixel shader.

Syntax

HRESULT SetPixelShader(

    LPDIRECT3DPIXELSHADER9 pShader
);

Parameters

pShader
[in] A pointer to a pixel shader object. See IDirect3DPixelShader9.

Return Value

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetPixelShader) will fail.


ID3DXEffectStateManager::SetPixelShaderConstantB Method

A callback function that must be implemented by a user to set an array of vertex shader Boolean constants.

Syntax

HRESULT SetPixelShaderConstantB(

    UINT StartRegister,
    CONST BOOL* pConstantData,
    UINT RegisterCount
);

Parameters

StartRegister
[out] The zero-based index of the first constant register.
pConstantData
[out] An array of Boolean constants.
RegisterCount
[out] The number of registers in pConstantData.

Return Value

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetPixelShaderConstantB) will fail.


ID3DXEffectStateManager::SetPixelShaderConstantF Method

A callback function that must be implemented by a user to set an array of vertex shader floating-point constants.

Syntax

HRESULT SetPixelShaderConstantF(

    UINT StartRegister,
    CONST FLOAT* pConstantData,
    UINT RegisterCount
);

Parameters

StartRegister
[out] The zero-based index of the first constant register.
pConstantData
[out] An array of floating-point constants.
RegisterCount
[out] The number of registers in pConstantData.

Return Value

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetPixelShaderConstantF) will fail.


ID3DXEffectStateManager::SetPixelShaderConstantI Method

A callback function that must be implemented by a user to set an array of vertex shader integer constants.

Syntax

HRESULT SetPixelShaderConstantI(

    UINT StartRegister,
    CONST INT* pConstantData,
    UINT RegisterCount
);

Parameters

StartRegister
[out] The zero-based index of the first constant register.
pConstantData
[out] An array of integer constants.
RegisterCount
[out] The number of registers in pConstantData.

Return Value

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetPixelShaderConstantI) will fail.


ID3DXEffectStateManager::SetRenderState Method

A callback function that must be implemented by a user to set render state.

Syntax

HRESULT SetRenderState(

    D3DRENDERSTATETYPE State,
    DWORD Value
);

Parameters

State
[in] The render state to set. D3DRENDERSTATETYPE
Value
[in] The render state value. See Effect States.

Return Value

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetRenderState) will fail.


ID3DXEffectStateManager::SetSamplerState Method

A callback function that must be implemented by a user to set a sampler.

Syntax

HRESULT SetSamplerState(

    DWORD Sampler,
    D3DSAMPLERSTATETYPE Type,
    DWORD Value
);

Parameters

Sampler
[in] The zero-based sampler number.
Type
[in] Identifies sampler state, which can specify the filtering, addressing, or the border color. See D3DSAMPLERSTATETYPE.
Value
[in] A value from one of the sampler state types in Type.

Return Value

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetSamplerState) will fail.


ID3DXEffectStateManager::SetTexture Method

A callback function that must be implemented by a user to set a texture.

Syntax

HRESULT SetTexture(

    DWORD Stage,
    LPDIRECT3DBASETEXTURE9 pTexture
);

Parameters

Stage
[in] The stage to which the texture is assigned. This is the index value in IDirect3DDevice9::SetTexture or IDirect3DDevice9::SetTextureStageState.
pTexture
[in] A pointer to the texture object. This can be any of the Microsoft Direct3D texture types (cube, volume, etc.). See IDirect3DBaseTexture9.

Return Value

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetTexture) will fail.


ID3DXEffectStateManager::SetTextureStageState Method

A callback function that must be implemented by a user to set the texture stage state.

Syntax

HRESULT SetTextureStageState(

    DWORD Stage,
    D3DTEXTURESTAGESTATETYPE Type,
    DWORD Value
);

Parameters

Stage
[in] The stage that the texture is assigned to. This is the index value in IDirect3DDevice9::SetTexture or IDirect3DDevice9::SetTextureStageState.
Type
[in] Defines the type of operation that a texture stage will perform. See D3DTEXTURESTAGESTATETYPE.
Value
[in] Can be either an operation (D3DTEXTUREOP) or an argument value (D3DTA), depending on what is chosen for Type.

Return Value

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetTextureStageState) will fail.


ID3DXEffectStateManager::SetTransform Method

A callback function that must be implemented by a user to set a transform.

Syntax

HRESULT SetTransform(

    D3DTRANSFORMSTATETYPE State,
    CONST D3DMATRIX* pMatrix
);

Parameters

State
[in] The type of transform to apply the matrix to. See D3DTRANSFORMSTATETYPE.
pMatrix
[in] A transformation matrix. See D3DMATRIX.

Return Value

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetTransform) will fail.


ID3DXEffectStateManager::SetVertexShader Method

A callback function that must be implemented by a user to set a vertex shader.

Syntax

HRESULT SetVertexShader(

    LPDIRECT3DVERTEXSHADER9 pShader
);

Parameters

pShader
[in] A pointer to a vertex shader object. See IDirect3DVertexShader9.

Return Value

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetVertexShader) will fail.


ID3DXEffectStateManager::SetVertexShaderConstantB Method

A callback function that must be implemented by a user to set an array of vertex shader Boolean constants.

Syntax

HRESULT SetVertexShaderConstantB(

    UINT StartRegister,
    CONST BOOL* pConstantData,
    UINT RegisterCount
);

Parameters

StartRegister
[out] The zero-based index of the first constant register.
pConstantData
[out] An array of Boolean constants.
RegisterCount
[out] The number of registers in pConstantData.

Return Value

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetVertexShaderConstantB) will fail.


ID3DXEffectStateManager::SetVertexShaderConstantF Method

A callback function that must be implemented by a user to set an array of vertex shader floating-point constants.

Syntax

HRESULT SetVertexShaderConstantF(

    UINT StartRegister,
    CONST FLOAT* pConstantData,
    UINT RegisterCount
);

Parameters

StartRegister
[out] The zero-based index of the first constant register.
pConstantData
[out] An array of floating-point constants.
RegisterCount
[out] The number of registers in pConstantData.

Return Value

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetVertexShaderConstantF) will fail.


ID3DXEffectStateManager::SetVertexShaderConstantI Method

A callback function that must be implemented by a user to set an array of vertex shader integer constants.

Syntax

HRESULT SetVertexShaderConstantI(

    UINT StartRegister,
    CONST INT* pConstantData,
    UINT RegisterCount
);

Parameters

StartRegister
[out] The zero-based index of the first constant register.
pConstantData
[out] An array of integer constants.
RegisterCount
[out] The number of registers in pConstantData.

Return Value

The user-implemented method should return S_OK. If the callback fails when setting the device state, either of the following will occur:

  • The effect will fail during ID3DXEffect::BeginPass.
  • The dynamic effect state call (such as IDirect3DDevice9::SetVertexShaderConstantI) will fail.


ID3DXInclude Interface

ID3DXInclude is a user-implemented interface to provide callbacks for #include directives during shader compilation. Each of the methods in this interface must be implemented by the user which will then be used as callbacks to the application when one of the following occurs:

  • An high-level shader language (HLSL) shader that contains a #include is compiled by calling one of the D3DXCompileShader*** functions.
  • An assembly shader #include is assembled by calling any of the D3DXAssembleShader*** functions.
  • An effect that contains a #include is compiled by by calling any of the D3DXCreateEffect*** or D3DXCreateEffectCompiler*** functions.

ID3DXInclude Members

Close | A user-implemented method for closing a shader #include file.
Open | A user-implemented method for opening and reading the contents of a shader #include file.

Remarks

A user creates an ID3DXInclude interface by implementing a class that derives from this interface, and implementing all the interface methods.

The LPD3DXINCLUDE type is defined as a pointer to this interface.

typedef interface ID3DXInclude ID3DXInclude;
typedef interface ID3DXInclude *LPD3DXINCLUDE;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | Nothing
Header | d3dx9shader.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXInclude::Close Method

A user-implemented method for closing a shader #include file.

Syntax

HRESULT Close(

    LPCVOID pData
);

Parameters

pData
[in] Pointer to the returned buffer that contains the include directives. This is the pointer that was returned by the corresponding ID3DXInclude::Open call.

Return Value

The user-implemented method should return S_OK. If the callback fails when reading the #include file, the application programming interface (API) that caused the callback to be called will fail. This is one of the following:

  • The high-level shader language (HLSL) shader will fail one of the D3DXCompileShader*** functions.
  • The assembly shader will fail one of the D3DXAssembleShader*** functions.
  • The effect will fail one of the D3DXCreateEffect*** or D3DXCreateEffectCompiler*** functions.

Remarks

If ID3DXInclude::Open was successful, ID3DXInclude::Close is guaranteed to be called before the API using this interface returns.

An example implementation of this method is shown in the EffectEdit Sample.

See Also

ID3DXInclude::Open


ID3DXInclude::Open Method

A user-implemented method for opening and reading the contents of a shader #include file.

Syntax

HRESULT Open(

    D3DXINCLUDE_TYPE IncludeType,
    LPCSTR pFileName,
    LPCVOID pParentData,
    LPCVOID *ppData,
    UINT *pBytes
);

Parameters

IncludeType
[in] The location of the #include file. See D3DXINCLUDE_TYPE.
pFileName
[in] Name of the #include file.
pParentData
[in] Pointer to the container that includes the #include file.
ppData
[out] Pointer to the returned buffer that contains the include directives. This pointer remains valid until ID3DXInclude::Close is called.
pBytes
[out] Number of bytes returned in ppData.

Return Value

The user-implemented method should return S_OK. If the callback fails when reading the #include file, the application programming interface (API) that caused the callback to be called will fail. This is one of the following:

  • The high-level shader language (HLSL) shader will fail one of the D3DXCompileShader*** functions.
  • The assembly shader will fail one of the D3DXAssembleShader*** functions.
  • The effect will fail one of the D3DXCreateEffect*** or D3DXCreateEffectCompiler*** functions.

Remarks

An example implementation of this method is shown in the EffectEdit Sample.

See Also

ID3DXInclude::Close


Functions
Microsoft DirectX 9.0 SDK Update (October 2004)

Functions

There are several functions that help create and compile effects.

Functions

  • D3DXCreateEffect
  • D3DXCreateEffectCompiler
  • D3DXCreateEffectCompilerFromFile
  • D3DXCreateEffectCompilerFromResource
  • D3DXCreateEffectFromFile
  • D3DXCreateEffectFromResource
  • D3DXCreateEffectPool
  • D3DXDisassembleEffect


D3DXCreateEffect Function

Create an effect from an ASCII or binary effect description.

Syntax

HRESULT WINAPI D3DXCreateEffect(

    LPDIRECT3DDEVICE9 pDevice,
    LPCVOID pSrcData,
    UINT SrcDataLen,
    const D3DXMACRO *pDefines,
    LPD3DXINCLUDE pInclude,
    DWORD Flags,
    LPD3DXEFFECTPOOL pPool,
    LPD3DXEFFECT *ppEffect,
    LPD3DXBUFFER *ppCompilationErrors
);

Parameters

pDevice
[in] Pointer to the device that will create the effect. See IDirect3DDevice9.
pSrcData
[in] Pointer to a buffer containing an effect description.
SrcDataLen
[in] Length of the effect data, in bytes.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by D3DXSHADER Compile Options.
pPool
[in] Pointer to a ID3DXEffectPool object to use for shared parameters. If this value is NULL, no parameters will be shared.
ppEffect
[out] Returns a pointer to an ID3DXEffect interface.
ppCompilationErrors
[out] Returns a buffer containing a listing of compile errors.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9effect.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCompileShader, D3DXCompileShaderFromResource


D3DXCreateEffectCompiler Function

Creates an effect compiler from an ASCII or binary effect description.

Syntax

HRESULT WINAPI D3DXCreateEffectCompiler(

    LPCSTR pSrcData,
    UINT SrcDataLen,
    const D3DXMACRO *pDefines,
    LPD3DXINCLUDE pInclude,
    DWORD Flags,
    LPD3DXEFFECTCOMPILER *ppEffectCompiler,
    LPD3DXBUFFER *ppParseErrors
);

Parameters

pSrcData
[in] Pointer to a buffer containing an effect description.
SrcDataLen
[in] Length, in bytes, of the effect data.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by D3DXSHADER Compile Options.
ppEffectCompiler
[out, retval] Address of a pointer to an ID3DXEffectCompiler interface containing the effect compiler.
ppParseErrors
[out, retval] Address of a pointer to an ID3DXBuffer interface containing any error messages that occurred during compilation. This parameter can be set to NULL to ignore error messages.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9effect.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateEffectCompilerFromFile, D3DXCreateEffectCompilerFromResource


D3DXCreateEffectCompilerFromFile Function

Creates an effect compiler from an ASCII or binary effect description.

Syntax

HRESULT WINAPI D3DXCreateEffectCompilerFromFile(

    LPCTSTR pSrcFile,
    CONST D3DXMACRO* pDefines,
    LPD3DXINCLUDE pInclude,
    DWORD Flags,
    LPD3DXEFFECTCOMPILER *ppEffectCompiler,
    LPD3DXBUFFER *ppParseErrors
);

Parameters

pSrcFile
[in] Pointer to the filename. This parameter supports both Unicode and ANSI strings. See Remarks.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by D3DXSHADER Compile Options.
ppEffectCompiler
[out, retval] Address of a pointer to an ID3DXEffectCompiler interface, containing the effect compiler.
ppParseErrors
[out, retval] Address of a pointer to an ID3DXBuffer interface, containing any error messages that occurred during compilation. This parameter can be set to NULL to ignore error messages.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the LPCTSTR data type resolves to LPCSTR.

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateEffectCompilerFromFileW. Otherwise, the function call resolves to D3DXCreateEffectCompilerFromFileA because ANSI strings are being used.

Function Information

Header | d3dx9effect.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateEffectCompiler, D3DXCreateEffectCompilerFromResource


D3DXCreateEffectCompilerFromResource Function

Creates an effect compiler from an ASCII or binary effect description.

Syntax

HRESULT WINAPI D3DXCreateEffectCompilerFromResource(

    HMODULE hSrcModule,
    LPCTSTR pSrcResource,
    const D3DXMACRO *pDefines,
    LPD3DXINCLUDE pInclude,
    DWORD Flags,
    LPD3DXEFFECTCOMPILER *ppEffectCompiler,
    LPD3DXBUFFER *ppParseErrors
);

Parameters

hSrcModule
[in] Handle to a module containing the effect description. If this parameter is NULL, the current module will be used.
pSrcResource
[in] Pointer to the resource. This parameter supports both Unicode and ANSI strings. See Remarks.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by D3DXSHADER Compile Options.
ppEffectCompiler
[out, retval] Address of a pointer to an ID3DXEffectCompiler interface, containing the effect compiler.
ppParseErrors
[out, retval] Address of a pointer to an ID3DXBuffer interface, containing any error messages that occurred during compilation. This parameter can be set to NULL to ignore error messages.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the LPCTSTR data type resolves to LPCSTR.

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateEffectCompilerFromResourceW. Otherwise, the function call resolves to D3DXCreateEffectCompilerFromResourceA because ANSI strings are being used.

Function Information

Header | d3dx9effect.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCreateEffectCompiler, D3DXCreateEffectCompilerFromFile


D3DXCreateEffectFromFile Function

Create an effect from an ASCII or binary effect description.

Syntax

HRESULT WINAPI D3DXCreateEffectFromFile(

    LPDIRECT3DDEVICE9 pDevice,
    LPCTSTR pSrcFile,
    const D3DXMACRO *pDefines,
    LPD3DXINCLUDE pInclude,
    DWORD Flags,
    LPD3DXEFFECTPOOL pPool,
    LPD3DXEFFECT *ppEffect,
    LPD3DXBUFFER *ppCompilationErrors
);

Parameters

pDevice
[in] Pointer to the device that will create the effect. See IDirect3DDevice9.
pSrcFile
[in] Pointer to the filename. This parameter supports both Unicode and ANSI strings. See Remarks.
pDefines
[in] Optional NULL-terminated array of preprocessor macro definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by D3DXSHADER Compile Options.
pPool
[in] Pointer to a ID3DXEffectPool object to use for shared parameters. If this value is NULL, no parameters will be shared.
ppEffect
[out] Returns a pointer to a buffer containing the compiled effect. See ID3DXEffect.
ppCompilationErrors
[out] Returns a pointer to a buffer containing a listing of compile errors. See ID3DXBuffer.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the LPCTSTR data type resolves to LPCSTR.

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateEffectFromFileW. Otherwise, the function call resolves to D3DXCreateEffectFromFileA because ANSI strings are being used.

Function Information

Header | d3dx9effect.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCompileShader, D3DXCompileShaderFromResource


D3DXCreateEffectFromResource Function

Create an effect from an ASCII or binary effect description.

Syntax

HRESULT WINAPI D3DXCreateEffectFromResource(

    LPDIRECT3DDEVICE9 pDevice,
    HMODULE hSrcModule,
    LPCTSTR pSrcResource,
    const D3DXMACRO *pDefines,
    LPD3DXINCLUDE pInclude,
    DWORD Flags,
    LPD3DXEFFECTPOOL pPool,
    LPD3DXEFFECT *ppEffect,
    LPD3DXBUFFER *ppCompilationErrors
);

Parameters

pDevice
[in] Pointer to the device.
hSrcModule
[in] Handle to a module containing the effect description. If this parameter is NULL, the current module will be used.
pSrcResource
[in] Pointer to the resource. This parameter supports both Unicode and ANSI strings. See Remarks.
pDefines
[in] Pointer to the preprocessor definitions. See D3DXMACRO.
pInclude
[in] Optional interface pointer, ID3DXInclude, to use for handling #include directives. If this value is NULL, #includes will either be honored when compiling from a file or will cause an error when compiled from a resource or memory.
Flags
[in] Compile options identified by D3DXSHADER Compile Options.
pPool
[in] Pointer to a ID3DXEffectPool object to use for shared parameters. If this value is NULL, no parameters will be shared.
ppEffect
[out] Returns a buffer containing the compiled effect.
ppCompilationErrors
[out] Returns a buffer containing a listing of compile errors.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the LPCTSTR data type resolves to LPCSTR.

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateEffectFromResourceW. Otherwise, the function call resolves to D3DXCreateEffectFromResourceA because ANSI strings are being used.

D3DXCreateEffectFromResource loads data from a resource of type RT_RCDATA. See MSDN for more information about Windows resources.

Function Information

Header | d3dx9effect.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

D3DXCompileShader, D3DXCompileShaderFromResource


D3DXCreateEffectPool Function

Create an effect pool. A pool is used to share parameters between effects.

Syntax

HRESULT WINAPI D3DXCreateEffectPool(

    LPD3DXEFFECTPOOL* ppPool
);

Parameters

ppPool
[out] Returns a pointer to the created pool.

Return Value

If the method succeeds, the return value is S_OK.

If the arguments are invalid, the method will return D3DERR_INVALIDCALL.

If the method fails, the return value will be E_FAIL.

Remarks

For effects within a pool, shared parameters with the same name share values.

Function Information

Header | d3dx9effect.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


D3DXDisassembleEffect Function

Disassemble an effect.

Syntax

HRESULT WINAPI D3DXDisassembleEffect(

    LPD3DXEFFECT pEffect,
    BOOL EnableColorCode,
    LPD3DXBUFFER *ppDisassembly
);

Parameters

pEffect
[in] Pointer to an ID3DXEffect interface that contains the effect.
EnableColorCode
[in] Enable color coding to make the disassembly easier to read.
ppDisassembly
[out] Returns a buffer containing the disassembled shader. See ID3DXBuffer.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DXERR_INVALIDDATA | The data is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Function Information

Header | d3dx9effect.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


Effect Structures
Microsoft DirectX 9.0 SDK Update (October 2004)

Effect Structures

This section contains information about the structures used by effects.

  • D3DXEFFECT_DESC
  • D3DXEFFECTDEFAULT
  • D3DXEFFECTINSTANCE
  • D3DXFRAGMENT_DESC
  • D3DXFUNCTION_DESC
  • D3DXPARAMETER_DESC
  • D3DXPASS_DESC
  • D3DXSEMANTIC
  • D3DXTECHNIQUE_DESC


D3DXEFFECT_DESC Structure

Describes an effect object.

Syntax

typedef struct _D3DXEFFECT_DESC {
    LPCSTR Creator;
    UINT Parameters;
    UINT Techniques;
    UINT Functions;
} D3DXEFFECT_DESC;

Members

Creator
String that contains the name of the effect creator.
Parameters
Number of parameters used for effect.
Techniques
Number of techniques that can render the effect.
Functions
Number of functions that can render the effect.

Remarks

An effect object can contain multiple rendering techniques and parameters for the same effect.

Structure Information

Header | d3dx9effect.h
Minimum operating systems | Windows 98


D3DXEFFECTDEFAULT Structure

Effect default parameters.

Syntax

typedef struct _D3DXEFFECTDEFAULT {
    LPSTR pParamName;
    D3DXEFFECTDEFAULTTYPE Type;
    DWORD NumBytes;
    LPVOID pValue;
} D3DXEFFECTDEFAULT, *LPD3DXEFFECTDEFAULT;

Members

pParamName
Parameter name.
Type
Data type in pValue. For more information, see D3DXEFFECTDEFAULTTYPE
NumBytes
Size, in bytes, of the data pointed to by pValue.
pValue
Pointer to the memory location that contains the data.

Structure Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98


D3DXEFFECTINSTANCE Structure

Data type for managing a set of default effect parameters.

Syntax

typedef struct _D3DXEFFECTINSTANCE {
    LPSTR pEffectFilename;
    DWORD NumDefaults;
    LPD3DXEFFECTDEFAULT pDefaults;
} D3DXEFFECTINSTANCE, *LPD3DXEFFECTINSTANCE;

Members

pEffectFilename
Name of the effect file.
NumDefaults
Number of default parameters.
pDefaults
Pointer to an array of D3DXEFFECTDEFAULT elements, each of which contains an effect parameter.

Structure Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98


D3DXFRAGMENT_DESC Structure

Describes an annotation used by an effect object.

Syntax

typedef struct D3DXFRAGMENT_DESC {
    LPCSTR Name;
    DWORD Target;
} D3DXFRAGMENT_DESC, *LPD3DXFRAGMENT_DESC;

Members

Name
Fragment name.
Target
Fragment compile target. The compile target identifies the shader type (vertex or pixel) and the version number.

Structure Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98


D3DXFUNCTION_DESC Structure

Describes a function used by an effect.

Syntax

typedef struct D3DXFUNCTION_DESC {
    LPCSTR Name;
    UINT Annotations;
} D3DXFUNCTION_DESC;

Members

Name
Function name.
Annotations
Unused. This member will always be set to zero by ID3DXBaseEffect::GetFunctionDesc.

Structure Information

Header | d3dx9effect.h
Minimum operating systems | Windows 98


D3DXPARAMETER_DESC Structure

Describes a parameter used for an effect object.

Syntax

typedef struct _D3DXPARAMETER_DESC {
    LPCSTR Name;
    LPCSTR Semantic;
    D3DXPARAMETER_CLASS Class;
    D3DXPARAMETER_TYPE Type;
    UINT Rows;
    UINT Columns;
    UINT Elements;
    UINT Annotations;
    UINT StructMembers;
    DWORD Flags;
    UINT Bytes;
} D3DXPARAMETER_DESC;

Members

Name
Name of the parameter.
Semantic
Semantic meaning, also called the usage.
Class
Parameter class. Set this to one of the values in D3DXPARAMETER_CLASS.
Type
Parameter type. Set this to one of the values in D3DXPARAMETER_TYPE.
Rows
Number of rows in the array.
Columns
Number of columns in the array.
Elements
Number of elements in the array.
Annotations
Number of annotations.
StructMembers
Number of structure members.
Flags
Parameter attributes. See Constants.
Bytes
The size of the parameter, in bytes.

Structure Information

Header | d3dx9effect.h
Minimum operating systems | Windows 98


D3DXPASS_DESC Structure

Describes a pass for an effect object.

Syntax

typedef struct _D3DXPASS_DESC {
    LPCSTR Name;
    UINT Annotations;
    const DWORD *pVertexShaderFunction;
    const DWORD *pPixelShaderFunction;
} D3DXPASS_DESC;

Members

Name
String value used for the pass.
Annotations
Annotations are user-specific data that can be attached to any technique, pass, or parameter. See Add Information to Effect Parameters with Annotations.
pVertexShaderFunction
Pointer to the vertex shader function.
pPixelShaderFunction
Pointer to the pixel shader function.

Structure Information

Header | d3dx9effect.h
Minimum operating systems | Windows 98


D3DXSEMANTIC Structure

Semantics map a parameter to vertex or pixel shader registers. They can also be optional descriptive strings attached to non-register parameters.

Syntax

typedef struct _D3DXSEMANTIC {
    UINT Usage;
    UINT UsageIndex;
} D3DXSEMANTIC, *LPD3DXSEMANTIC;

Members

Usage
Options that identify how resources are used. See D3DDECLUSAGE.
UsageIndex
Options that modify how the usage is interpreted. The usage and usage index make up a vertex declaration. See Vertex Declaration.

Remarks

Semantics are required for vertex and pixel shader, input and output registers.

Structure Information

Header | d3dx9shader.h
Minimum operating systems | Windows 98


D3DXTECHNIQUE_DESC Structure

Describes a technique used by an effect.

Syntax

typedef struct _D3DXTECHNIQUE_DESC {
    LPCSTR Name;
    UINT Passes;
    UINT Annotations;
} D3DXTECHNIQUE_DESC;

Members

Name
String that contains the technique name.
Passes
Number of rendering passes the technique requires. See Remarks.
Annotations
The number of annotations. See Add Information to Effect Parameters with Annotations.

Remarks

Some video cards can render two textures in a single pass. However, if a card does not have this capability, it is often possible to render the same effect in two passes, using one texture for each pass.

Structure Information

Header | d3dx9effect.h
Minimum operating systems | Windows 98


Constants
Microsoft DirectX 9.0 SDK Update (October 2004)

Constants

These are shader and effect constants.

Effect Parameters

#define | Description
D3DX_PARAMETER_ANNOTATION | This parameter is marked as an annotation. See Add Information to Effect Parameters with Annotations.
D3DX_PARAMETER_LITERAL | This parameter is marked as a literal value. Literal parameters cannot change after compile, allowing the compiler to optimize their usage. Shared parameters cannot be marked as a literal. See Usages and Literals.
D3DX_PARAMETER_SHARED | The value of a parameter will be shared by all effects in the same namespace. Changing the value in one effect will change it in all shared effects. See Sharing Parameters. D3DX_PARAMETER_SHARED cannot be combined with D3DX_PARAMETER_LITERAL or D3DX_PARAMETER_ANNOTATION.

Effect parameter constants are used by D3DXPARAMETER_DESC.

D3DXHANDLE

Effects use handles to reference techniques, passes, annotations, and parameters.

typedef LPCSTR D3DXHANDLE

For more information, see Handles.

Shader State

#define | Description
D3DXFX_DONOTSAVESTATE | No state is saved when calling ID3DXEffect::Begin or restored when calling ID3DXEffect::End.
D3DXFX_DONOTSAVESAMPLERSTATE | A stateblock saves state when calling ID3DXEffect::Begin and restores state when calling ID3DXEffect::End.
D3DXFX_DONOTSAVESHADERSTATE | A stateblock saves state (except shaders and shader constants) when calling ID3DXEffect::Begin and restores state when calling ID3DXEffect::End.

See State Blocks Save and Restore State.


Effect Format
Microsoft DirectX 9.0 SDK Update (October 2004)

Effect Format

This section contains reference information for the effect format.

An effect is made up of parameters, techniques, and functions.

  • Parameters
  • Techniques and Passes
  • Functions

These are made up of id's, semantics, annotations, etc.

  • Standard Annotation Syntax
  • Cloning and Sharing
  • Expressions
  • Handles
  • Effect States
  • Usages and Literals
  • Validation


Parameters
Microsoft DirectX 9.0 SDK Update (October 2004)

Parameters

Parameters are effect variables.

Syntax

usage  type  id  [: semantic]  [< annotation(s) >]  [= expression];

Parameters can be read from and written to by the application with ID3DXEffect or ID3DXEffectCompiler.

Parameters can be referenced in functions and in techniques (specifically, in the right side of state assignments).

  • usage - Scope of the parameter. See Usages and Literals.
  • type - Any valid HLSL Shader Reference type.
  • id - A unique name.
  • semantic - A tag following identifer rules that typically indicates the usage of the parameter. Must be a particular type.
  • annotations - Zero or more pieces of user-specific information. May be any type. See Add Information to Effect Parameters with Annotations.
  • expression - Initializes the parameter's value. See Expressions.

Parameters can be initialized to any valid HLSL Shader Reference expression that reduces to a literal value.

Parameter values are not changed by the execution of state assignment or function calls.


Techniques and Passes
Microsoft DirectX 9.0 SDK Update (October 2004)

Techniques and Passes

Techniques provide the rendering muscle. A technique encapsulates the effect state that determines a rendering style. A technique is made up of one or more passes.

Techniques

The syntax for calling a technique is as follows:

technique [ id ]  [< annotation(s) >]
    { pass(es) }
Where:
  • id is an optional unique name.
  • annotation is zero or more optional pieces of user-specific information. See Add Information to Effect Parameters with Annotations.
  • pass(es) is zero or more passes. Each pass contains state assignments. See below.

Passes

A pass contains the state assignments required to render.

pass  [ id ]  [< annotation(s) >]
    { state assignment(s) }
Where:
  • id is an optional unique name.
  • annotation is one or more optional piece of user-specific information. See Add Information to Effect Parameters with Annotations.
  • assignment(s) assigns zero or more state values, or evaluates one or more expressions. See Effect States and Expressions.

Passes ignore all but the last assignment in a set of repeated assignments to the same state.


Functions
Microsoft DirectX 9.0 SDK Update (October 2004)

Functions

A function is the building block for a shader created in the high-level language. If you prefer to write shaders in a C-style language instead of in assembly language, you will want to write functions.

Syntax

type id ( [ parameters ] )
    { body }

Functions do not change parameter values in an effect.

  • type - Any valid HLSL Shader Reference type.
  • id - A unique name.
  • parameters - Function parameters.
  • body - The body of the function.

Functions are built from the high-level language. See HLSL Shader Reference.


Standard Annotation Syntax
Microsoft DirectX 9.0 SDK Update (October 2004)

Standard Annotation Syntax

Standard semantics and annotations are two types of metadata that can be added to effect parameters and techniques to add broad capability. Using industry-standard terms for semantics and annotations allows tools to be built that can take advantage of these effect parameters.

Semantics link inputs and outputs of shaders three ways:

  • Vertex buffer declarations link to vertex shaders with semantics.
  • Vertex shader outputs are linked to pixel shader inputs with semantics.
  • Pixel shader outputs link to pipeline state with semantics.

A complete listing of the standard semantics is listed below. For detailed information about shader semantic syntax, see Shader Semantic Syntax. For information about attaching semantics to shader parameters, see Varying Shader Inputs and Semantics

Annotations are additional metadata that an application can read to understand more about how the particular parameter was intended for use. Annotations are being broadly used by many graphics engines to take advantage of shader code without hard-coding each .fx file.

Standard semantics and annotations are listed in the following pages:

  • Standard Semantics Reference
  • Standard Annotations Reference
  • Standard Annotation Scripting Syntax

To get more information about using semantics and annotations, see Using Standard Semantics and Standard Annotations.


Standard Semantics Reference
Microsoft DirectX 9.0 SDK Update (October 2004)

Standard Semantics Reference

A standard semantic is a hint to an application for parameter usage. Instead of creating naming guidelines for parameters, Microsoft has created a set of standard semantics. Parameters do not have to use standard semantics (although it's recommended that they do so, see Using Standard Semantics and Standard Annotations)

Standard semantics are unrelated to shader semantics which bind shader parameters to shader registers (see Shader Semantic Syntax).

Standard Semantics | Type | Description
Ambient | float4 | Ambient color.
Attenuation float3 or float4 Attenuation value, whose value can be one of the following:
  • Distance uses 4 components.
  • Spot uses 3 components.
  • BoxX uses 3 components.
  • BoxY uses 3 components.
BoundingBoxMax | float3 | Bounding box maximum for x, y, z.
BoundingBoxMin | float3 | Bounding box minimum for x, y, z.
BoundingBoxSize | float3 | Bounding box size for x, y, z.
BoundingCenter | vector | Bounding box center.
BoundingSphereSize | float1 | Median bounding sphere radius.
BoundingSphereMin | float1 | Minimum bounding sphere radius.
BoundingSphereMax | float1 | Maximum bounding sphere radius.
Diffuse | float4 | Diffuse color.
ElapsedTime | float1 | Elapsed time. Useful when LastTime may not be accurate due to looping simulations.
Emissive | float4 | Emissive color.
EnvironmentNormal | texture | Environment normal map.
Height | 1 component numeric or a texture | Height value in a bump map.
Joint | float4 | Object space to Frame-Joint space
JointWorld | float4x4 | Joint world matrix.
JointWorldInverse | float4x4 | Joint inverse world matrix.
JointWorldInverseTranspose | float4x4 | Joint transposed, inverse world matrix.
JointWorldView | float4x4 | Joint world-view matrix.
JointWorldViewInverse | float4x4 | Joint inverse world-view matrix.
JointWorldViewInverseTranspose | float4x4 | Joint transposed, inverse world-view matrix.
JointWorldViewProjection | float4x4 | Joint world-view-projection matrix.
JointWorldViewProjectionInverse | float4x4 | Joint inverse world-view-projection matrix.
JointWorldViewProjectionInverseTranspose | float4x4 | Joint transposed, inverse world-view-projection matrix.
LastTime | float1 | Last simulation time.
Normal | 3 or 4 component numeric or texture | Surface normal vector.
Opacity | float1, float2, float3, float4, or texture | Object opacity. Can be a single value or a per-component value.
Position | float4 | XYZW position.
Projection | float4x4 | Projection matrix.
ProjectionInverse | float4x4 | Inverse projection matrix.
ProjectionInverseTranspose | float4x4 | Transposed, inverse projection matrix.
Random | numeric | Random numbers.
Refraction | float1, float2, float3, float4, or texture | Refraction value for an environment map. Can be a single value or a per-component value.
RenderColorTarget | texture | Rendertarget surface.
RenderDepthStencilTarget | texture | Depth/stencil surface.
RenderTargetClipping | 4 components | Clipping parameters which include: near distance, far distance, width angle (radians), and height angle(radians).
RenderTargetDimensions | 2 component | Rendertarget width and height in pixels.
Specular | float4 | Specular color.
SpecularPower | float1 to float4 | Specular power exponent. Can be a single value or a per-component value.
StandardsGlobal | float1 | Standard annotation version number. Default value is 0.80. This may appear only once in a script.
TextureMatrix | float4x4 | Texture coordinate transform matrix.
Time | float | Simulation time.
UnitsScale | float | Model scale value.
View | float4x4 | View matrix.
ViewInverse | float4x4 | Inverse view matrix.
ViewInverseTranspose | float4x4 | Transposed, inverse view matrix.
ViewProjection | float4x4 | View-projection matrix.
ViewProjectionInverse | float4x4 | Inverse view-projection matrix.
ViewProjectionInverseTranspose | float4x4 | Transposed, inverse view-projection matrix.
World | float4x4 | World matrix.
WorldInverse | float4x4 | Inverse world matrix.
WorldInverseTranspose | float4x4 | Transposed, inverse world matrix.
WorldView | float4x4 | Transposed, inverse world-view matrix.
WorldViewInverse | float4x4 | Inverse world-view matrix.
WorldViewInverseTranspose | float4x4 | Transposed, inverse world-view matrix.
WorldViewProjection | float4x4 | World-view-projection matrix.
WorldViewProjectionInverse | float4x4 | Inverse world-view-projection matrix.
WorldViewProjectionInverseTranspose | float4x4 | Transposed, inverse world-view-projection matrix.


Standard Annotations Reference
Microsoft DirectX 9.0 SDK Update (October 2004)

Standard Annotations Reference

An annotation is metadata attached to a parameter that can be used by an effect to get additional information about a parameter's intended usage. Instead of creating naming guidelines for parameters, Microsoft has created a set of standard annotations. Parameters do not have to use semantics or annotations (although it's recommended that they do so, see Using Standard Semantics and Standard Annotations).

Generic Annotations

Name | Type | Description
Normalize | bool | The data should be normalized.
Object string Object type, which is one of the following values:
  • Geometry
  • Camera
  • Frame
  • Light
  • RenderTarget
Semantic | string | Reserved for future use.
SemanticType string Can be Semantic = RenderColorTarget, which is one of the following values:
  • Color
  • Normal
  • Depth
  • Stencil

Can be Semantic = Attenuation, which is one of the following values:

  • Distance
  • Spot
  • BoxX
  • BoxY

Space | string | Coordinate space.
Units string Unit scale, which is one of the following values:
  • Ms, sec, min, hour
  • Mm, cm, m, km, inch, feet, yard, mile
  • Rad, deg
  • RGB, HIS, YUV, IA
  • Quaternion
Usage string Hint to the application.
string Usage = "Roughness";

Texture Annotations

Name | Type | Description
Dimensions | float1, float2, float3 | Suggested dimension for a texture (width, height, depth).
Discardable | bool | Each texture is discardable.
Format | string | Texture format. The valid values for this come from D3DFORMAT.
Function | string | Function name. This also for procedural generation of values for a variable.
MIPLevels int Number of mip levels requested. Specify zero to automatically generate miplevels.
integer MIPLevels = 4;
ResourceName | string | Resource name for objects, such as a filename for a texture.
ResourceType string Texture resource type, which can be one of the following:
  • 1D
  • 2D
  • 3D
  • cube
TargetPS, TargetVS | string | Shader compile target.
ViewportRatio | float | Suggested ratio for a texture width and height as compared to a viewport width and height.

UI Annotations

Name | Type | Description
UIHelp string Help string.
string UIHelp = "The diffuse color";
UIMax float Maximum control value.
float4 UIMax = (1.0, 1.0, 1.0, 1.0);
UIMin float Minimum control value.
float4 UIMin = (0.0, 0.0, 0.0, 0.0);
UIName string Control name.
string UIName = "My Color";
UIObject | object | Link to an object in an external application. The object is read only and the data extracted from the object is defined by the external application.
UIStep float Incremental step value when incrementing or decrementing a parameter.
Value = x ^ UIStep
UIStepPower | float | Specular reflection power.
UIWidget string Usage type of a variable. This provides more specific usage information than the usage specified by a semantic. This value is a string value that can be, but is not limited to, one of the following values:
  • Slider
  • Spinner
  • Color
  • Grayscale (all components must be set to the same value)
  • Numeric
  • String
  • Texture
  • Direction
  • Object (dependent on the object annotation)
  • None - Do not display this annotation.
string UIWidget = "Grayscale";


Standard Annotation Scripting Syntax
Microsoft DirectX 9.0 SDK Update (October 2004)

Standard Annotation Scripting Syntax

An annotation is metadata attached to a parameter that can be used by an effect to get additional information about a parameter's intended usage. Instead of creating naming guidelines for parameters, Microsoft has created a set of industry-standard annotations. Parameters do not have to use annotation scripts. To get more information about using standard semantics and standard annotations, see Using Standard Semantics and Standard Annotations.

Syntax

Annotation scripts are declared with the following syntax:

String scriptType = "[ScriptCommand]";

Where:

  • scriptType is one of:
    ScriptExecute | An entry point for scripts. It can only be placed on techniques and the parameter marked with the StandardsGlobal semantic superset of ScriptFunction.
    ScriptFunction | The script or partial script describing operation of this file.
    ScriptSetup | An entry-point script used for setup of existing state.
  • ScriptCommand is a script command.

The syntax for a ScriptCommand is:

 [ScriptCommand]  = [Command];
                    [Command]; [ScriptCommand]
                    [Command]=[Argument];
                    [Command]=[Argument]; [ScriptCommand]
 [Command] = command (see command section below)
 [Argument]= [Value]
             [Value]![Hint]
 [Value]=	 [Option:string]
             [Option: variable]
 [Option:string]=string
             string,[Option:string]
 [Option: parameter]= parameter_name
             parameter_name,[Option: parameter]
 [Hint]= parameter_name (which will selects the option by index)
             string (which helps the user select the option by index)

Where:

  • Command - One of the Script Commands.
  • Argument - An argument.
  • Value - A default value.
  • Hint - A user supplied hint.

Use:

  • A period (.) to reference a structure member.
  • A pound sign (#) to reference an array element where # is an integer.
  • An "at" sign (@) to reference an annotation.

Script Commands

Script Commands | Description
ClearSetColor | Clear the rendertarget to this color.
ClearSetDepth | Clear the rendertarget depth buffer to this value.
ClearSetStencil | Clear the rendertarget stencil buffer to this value.
Draw
  • Scene - draw all geometry.
  • Geometry - draw inside of a geometry loop. Only one Microsoft Direct3D draw call should be performed per loop outside of a geometry loop.
  • Buffer - draw a full screen quad.
  • Arbitrary - string of draw instructions that a specialized program would understand.
GeometryList Draw order hint.
  • ZFrontToBack
  • ZBackToFront
  • Scene
  • Arbitrary
Hint | Callback hint to the application.
LoopByType Control the draw loop when parameter changes are expected or multiple passes are required.
  • Passes - draw all passes.
  • Lights - draw with each light enabled.
  • Geometry - draw all geometry that uses a particular material.
  • RenderTargets - draw all render targets.
  • Arbitrary
LoopByCount | Override LoopByType. LoopByCount must precede LoopByType.
LoopEnd | End of a loop.
LoopGetCount | Loop iteration count.
LoopGetIndex | Loop index count.
Pass | Pass name or number.
RenderColorTarget Color rendertarget, whose value is one of the following:
  • Texture name
  • Blank to reset to default
RenderDepthStencilTarget Depth/stencil rendertarget, whose value is one of the following:
  • texture name
  • Blank to reset to default
Technique | Technique name or number.


Cloning and Sharing
Microsoft DirectX 9.0 SDK Update (October 2004)

Cloning and Sharing

Cloning Parameters

Cloning has the following restrictions.

  • Clones inherit the original effect's pool. See the Sharing Parameters section.
  • Clones inherit the original effect's techniques, passes, parameters, and annotations (including all annotations added with ID3DXEffect).
  • Clones inherit the original effect's dynamically added annotations.
  • Cloning onto a new device will fail if the original effect's pool was not NULL and the original effect contained a shared device-dependent parameter (such as a texture or shader).

Sharing Parameters

A pool is a buffer that shares effect parameters between different effects. To add parameters to a pool, specify a shared usage when the effect is created.

A pool has the following restrictions.

  • A parameter is added to the pool the first time an effect containing that (shared) parameter is added to the pool.
  • A pool gets initial values from the first shared parameter; parameters shared subsequently get their values from the pool.
  • A parameter is deleted from the pool when all effect references to the shared parameter are released.
  • All effects in the pool that contain the same (shared) device-dependent parameter must have the same device.

NULL can be used to specify no pool, in which case no parameters are shared. This is almost equivalent to specifying a unique pool just for this effect. The single difference is that when the effect is cloned, the clone will not share its shared parameters with the original.


Expressions
Microsoft DirectX 9.0 SDK Update (October 2004)

Expressions

Expressions are mathematical or logical statements that are used on the right hand side of an equals sign. There are many types of expressions.

Expressions

  1. Variable Reference
    ( variable ) or < variable >
  2. Numeric Scalar
    scalar
  3. Numeric Expression
    ( numeric expression )

    All standard numeric HLL expressions are supported here.

  4. Constructor
    type ( constructor arguments )
  5. List of Initializers
    { scalar value [, scalar value ...  ] }

    The scalars must be literal scalar values.

    The number of initializers must be compatible with the variable (state) on the left hand side of the equals sign.

  6. OR Expression
    token [ | token ... ]

    The tokens must be compatible with the variable (state) on the left hand side of the equals sign.

    The tokens are not case sensitive.

  7. NULL
    NULL

    NULL can only be assigned to a shader, sampler, or a texture object.

  8. Assembly Block
    asm { code }

    PS Assembly Blocks must be assigned to the PIXELSHADER state.

    VS Assembly Blocks must be assigned to the VERTEXSHADER state.

  9. Sampler State Block
    sampler_state { [ state = expression ; [ state = ... ] ] }

    Sampler state blocks are sequences of un-indexed sampler stage state or texture assignments.

    Sampler state blocks must be assigned to the SAMPLER effect state.

  10. Effect State State Block
    stateblock_state { [ state [ [index] ] = expression;
    [ state [ [index] ] = ... ] ] }

    State blocks are sequences of general state. State blocks can be nested, but cannot contain circular references.

    State blocks must be assigned to the STATEBLOCK effect state.

  11. HLSL Compile
    compile target entrypoint ( [ arguments ] )

    The vertex shader vs_m_n target indicates D3DVS_VERSION(m, n) vertex shader version. The pixel shader ps_m_n target indicates D3DPS_VERSION(m, n) pixel shader version.

    Vertex shader high-level language compile expressions can only be assigned to the VERTEXSHADER effect state. Pixel shader high-level language compile expressions can only be assigned to the PIXELSHADER effect state.


Handles
Microsoft DirectX 9.0 SDK Update (October 2004)

Handles

Handles provide an efficient means for referencing the techniques, passes, annotations, and parameters with ID3DXEffectCompiler or ID3DXEffect. They are generated dynamically when you call functions of the form Get[Parameter|Annotation|Function|Technique|Pass][ByName|BySemantic|Element].

While running a program, generating a handle to the same object multiple times will return the same handle back every time. But don't rely on the handle staying constant when you run your program multiple times. Also be aware that handles generated by different instances of ID3DXEffect and ID3DXEffectCompiler will be different.

If you view the header files, you'll notice that handles (D3DXHANDLEs) are technically string pointers. See Constants.

The handles that you pass into functions such as GetParameter[ByName|Element|BySemantic] or GetAnnotation[ByName] can be in three forms as follows:

  1. Handles that were returned by functions such as GetParameter[ByName|Element|BySemantic].
  2. Strings such as MyVariableName, MyTechniqueName, or MyArray[0].
  3. Handle = NULL. There are four cases.
    • If it is a method return value, the method failed to find the handle.
    • If a NULL handle is passed in as the first parameter of GetParameter[ByName|Element|BySemantic], the function returns a top-level parameter. Conversely, if the handle is non-NULL, the function returns a structure member or element identified by the handle.
    • If a NULL handle is passed in as the first argument of ValidateTechnique or the second argument of IsParameterUsed, the current technique is validated.
    • If a NULL handle is passed in as the first argument of FindNextValidTechnique, the search for a valid technique starts at the first technique in the effect.

Performance tip At the start of your application, perform an initialization pass to generate handles from the strings. From that point on, use only handles. Passing in strings instead of generated handles is slower.

Examples

Here are some examples using the Get[Parameter|Annotation|Function|Technique|Pass][ByName|BySemantic|Element] functions to generate handles.

// Gets handle of second top-level parameter handle in the effect file
h1 = GetParameter(NULL, 1);

// Gets handle of the third struct member of MyStruct
h2 = GetParameter("MyStruct", 2);

// Gets handle of the third array element handle of MyArray
h3 = GetParameterElement("MyArray", 2);

// Gets handle of first member of h1 (that is, the second top-level param)
h4 = GetParameter(h1, 0);

// Gets handle of MyStruct.Data
h5 = GetParameterByName("MyStruct", "Data");
// or
h6 = GetParameterByName(NULL, "MyStruct.Data");

// Gets handle of MyStruct.Data.SubData
h7 = GetParameterByName("MyStruct.Data", "SubData");
// or
h8 = GetParameterByName(NULL, "MyArray[2]");

// Gets handle of fifth annotation of h1 (that is, second top-level param)
h9 = GetAnnotation(h1, 4);

// Gets handle of MyStruct's annotation, called Author
h10 = GetAnnotationByName("MyStruct", "Author");
// or
h11 = GetParameterByName(NULL, "MyStruct@Author");


Effect States
Microsoft DirectX 9.0 SDK Update (October 2004)

Effect States

Effect states are used to initialize pipeline states in preparation for vertex and pixel processing.

effect state [ [index] ] = expression;

Where:

  • effect state - Similar to the traditional fixed function pipeline states. A complete list of states is provided below.
  • [ [index] ] - Optional integer index. The index identifies a particular state within an array of effect states. The outer brackets indicate that an index is optional. If an index is used, be sure to use the inner brackets.
  • expression - State assignment expression. See Expressions.

Effect states can be broken up into the following categories:

  • Light States
  • Material States
  • Render States
    • Pixel Pipe Render States
    • Vertex Pipe Render States
  • Sampler States
  • Sampler Stage States
  • Shader States
  • Shader Constant States
  • Texture States
  • Texture Stage States
  • Transform States

Light States

To enable the best performance for applying an effect, all components of a light or a material should be specified in the effect file. States that you fail to declare are set to some default value because there is no way for Microsoft Direct3D to set light states individually.

Light State | Type | Values
LightAmbient[n] | float4 | See the Ambient member of D3DLIGHT9.
LightAttenuation0[n] | float | See the Attenuation0 member of D3DLIGHT9.
LightAttenuation1[n] | float | See the Attenuation1 member of D3DLIGHT9.
LightAttenuation2[n] | float | See the Attenuation2 member of D3DLIGHT9.
LightDiffuse[n] | float4 | See the Diffuse member of D3DLIGHT9.
LightDirection[n] | float3 | See the Direction member of D3DLIGHT9.
LightEnable[n] | bool | True or False. See the bEnable argument in IDirect3DDevice9::LightEnable.
LightFalloff[n] | float | D3DCOLORVALUE. See the Falloff member of D3DLIGHT9.
LightPhi[n] | float | See the Phi member of D3DLIGHT9.
LightPosition[n] | float3 | See the Position member of D3DLIGHT9.
LightRange[n] | float | See the Range member of D3DLIGHT9.
LightSpecular[n] | float4 | See the Specular member of D3DLIGHT9.
LightTheta[n] | float | See the Theta member of D3DLIGHT9.
LightType[n] | dword | Same value as the array of up to n D3DLIGHTTYPE values without the D3DLIGHT_ prefix.

Material States

States that you fail to declare are set to some default value because there is no way for Direct3D to set material states individually.

Material State | Type | Values
MaterialAmbient | float4 | Same value as Ambient
MaterialDiffuse | float4 | Same value as Diffuse
MaterialEmissive | float4 | Same value as Emissive
MaterialPower | float | Same value as Power
MaterialSpecular | float4 | Same value as Specular

Render States

There are two types of render states:

  • Pixel Pipe Render States
  • Vertex Pipe Render States

Pixel Pipe Render States

Effect file render states have names similar to the fixed function pipeline states, often with the prefix removed.

Render State | Type | Values
AlphaBlendEnable | bool | True or False. Same values as D3DRS_ALPHABLENDENABLE in D3DRENDERSTATETYPE.
AlphaFunc | dword | Same values as D3DCMPFUNC without the D3DCMP_ prefix. See D3DRS_ALPHAFUNC.
AlphaRef | dword | Same values as D3DRS_ALPHAREF.
AlphaTestEnable | dword | True or False. See D3DRS_ALPHATESTENABLE.
BlendOp | dword | Same values as D3DBLENDOP without the D3DBLENDOP_ prefix.
ColorWriteEnable | dword | Bitwise combination of RED|GREEN|BLUE|ALPHA. See D3DRS_COLORWRITEENABLE.
DepthBias | float | Same values as D3DRS_DEPTHBIAS.
DestBlend | dword | Same values as D3DBLEND without the D3DBLEND_ prefix.
DitherEnable | bool | True or False. Same values as D3DRS_DITHERENABLE.
FillMode | dword | Same values as D3DFILLMODE without the D3DFILL_ prefix.
LastPixel | dword | True or False. See D3DRS_LASTPIXEL.
ShadeMode | dword | Same values as D3DSHADEMODE without the D3DSHADE_ prefix.
SlopeScaleDepthBias | float | Same values as D3DRS_SLOPESCALEDEPTHBIAS.
SrcBlend | dword | Same values as D3DBLEND without the D3DBLEND_ prefix.
StencilEnable | bool | True or False. Same values as D3DRS_STENCILENABLE.
StencilFail | dword | Same values as D3DSTENCILCAPS without the D3DSTENCILCAP_ prefix. See D3DRS_STENCILFAIL.
StencilFunc | dword | Same values as D3DCMPFUNC without the D3DCMP_ prefix. See D3DRS_STENCILFUNC.
StencilMask | dword | Same values as D3DRS_STENCILMASK.
StencilPass | dword | Same values as D3DSTENCILCAPS without the D3DSTENCILCAP_ prefix. See D3DRS_STENCILPASS.
StencilRef | int | Same values as D3DRS_STENCILREF.
StencilWriteMask | dword | Same values as D3DRS_STENCILWRITEMASK.
StencilZFail | dword | Same values as D3DSTENCILCAPS without the D3DSTENCILCAP_ prefix. See D3DRS_STENCILZFAIL.
TextureFactor | dword | Same values as D3DCOLOR. Same values as D3DRS_TEXTUREFACTOR.
Wrap0 - Wrap15 dword Values are the same as the values used by D3DRS_WRAP0. Valid values are:
  • COORD0 (which corresponds to D3DWRAPCOORD_0)
  • COORD1 (which corresponds to D3DWRAPCOORD_1)
  • COORD2 (which corresponds to D3DWRAPCOORD_2)
  • COORD3 (which corresponds to D3DWRAPCOORD_3)
  • U (which corresponds to D3DWRAP_U)
  • V (which corresponds to D3DWRAP_V)
  • W (which corresponds to D3DWRAP_W)
ZEnable | dword | Same values as D3DZBUFFERTYPE without the D3DZB_ prefix.
ZFunc | dword | Same values as D3DCMPFUNC without the D3DCMP_ prefix. See D3DRS_ZFUNC.
ZWriteEnable | bool | True or False. See D3DRS_ZWRITEENABLE.

Vertex Pipe Render States

Effect file render states have names similar to the fixed function pipeline states, often with the prefix removed.

Render State | Type | Values
Ambient | float4 | Same values as D3DRS_AMBIENT.
AmbientMaterialSource | dword | Same values as D3DMATERIALCOLORSOURCE without the D3DMCS_ prefix. See D3DRS_AMBIENTMATERIALSOURCE.
Clipping | bool | True or False. Same values as D3DRS_CLIPPING.
ClipPlaneEnable | dword | Bitwise combination of D3DCLIPPLANE0 - D3DCLIPPLANE5 macros. See D3DCLIPPLANEn and D3DRS_CLIPPLANEENABLE.
ColorVertex | bool | True or False. Same values as D3DRS_COLORVERTEX.
CullMode | dword | Same values as D3DCULL without the D3DCULL_ prefix.
DiffuseMaterialSource | dword | Same values as D3DMATERIALCOLORSOURCE without the D3DMCS_ prefix. See D3DRS_DIFFUSEMATERIALSOURCE.
EmissiveMaterialSource | dword | Same values as D3DMATERIALCOLORSOURCE without the D3DMCS_ prefix. See D3DRS_EMISSIVEMATERIALSOURCE.
FogColor | dword | Same values as D3DCOLOR. See D3DRS_FOGCOLOR.
FogDensity | float | Same values as D3DRS_FOGDENSITY.
FogEnable | bool | True or False. Same values as D3DRS_FOGENABLE.
FogEnd | float | Same values as D3DRS_FOGEND.
FogStart | float | Same values as D3DRS_FOGSTART.
FogTableMode | dword | Same values as D3DFOGMODE. See D3DRS_FOGTABLEMODE in D3DRENDERSTATETYPE.
FogVertexMode | dword | Same values as D3DFOGMODE without the D3DFOG_ prefix.
IndexedVertexBlendEnable | bool | True or False. Same values as D3DRS_INDEXEDVERTEXBLENDENABLE.
Lighting | bool | True or False. Same values as D3DRS_LIGHTING.
LocalViewer | bool | True or False. Same values as D3DRS_LOCALVIEWER.
MultiSampleAntialias | bool | Same values as D3DRS_MULTISAMPLEANTIALIAS.
MultiSampleMask | dword | Same values as D3DRS_MULTISAMPLEMASK.
NormalizeNormals | bool | True or False. Same values as D3DRS_NORMALIZENORMALS.
PatchSegments | float | Same values as nSegments in IDirect3DDevice9::SetNPatchMode.
PointScale_A | float | Same values as D3DRS_POINTSCALE_A.
PointScale_B | float | Same values as D3DRS_POINTSCALE_B.
PointScale_C | float | Same values as D3DRS_POINTSCALE_C.
PointScaleEnable | bool | Same values as D3DRS_POINTSCALEENABLE.
PointSize | float | Same values as D3DRS_POINTSIZE.
PointSize_Min | float | Same values as D3DRS_POINTSIZE_MIN.
PointSize_Max | float | Same values as D3DRS_POINTSIZE_MAX without the D3DRS_ prefix.
PointSpriteEnable | bool | True or False. Same values as D3DRS_POINTSPRITEENABLE.
RangeFogEnable | bool | True or False. Same values as D3DRS_RANGEFOGENABLE.
SpecularEnable | bool | True or False. Same values as D3DRS_SPECULARENABLE.
SpecularMaterialSource | dword | Same values as D3DMATERIALCOLORSOURCE without the D3DMCS_ prefix. See D3DRS_SPECULARMATERIALSOURCE.
TweenFactor | float | Same values as D3DRS_TWEENFACTOR.
VertexBlend | dword | Same values as D3DVERTEXBLENDFLAGS without the D3DVBF_ prefix. See D3DRS_VERTEXBLEND.

Sampler States

A sampler state represents a sampler object.

State | Type | Values
Sampler | sampler | NULL, or a sampler state block.

Sampler Stage States

Sampler stage states are used to sample textures. Sampler state determines filtering types and texture addressing modes.

Sampler State | Type | Values
AddressU[16] | dword | Same values as D3DTEXTUREADDRESS without the D3DTADDRESS_ prefix. See D3DSAMP_ADDRESSU.
AddressV[16] | dword | Same values as D3DTEXTUREADDRESS without the D3DTADDRESS_ prefix. See D3DSAMP_ADDRESSV.
AddressW[16] | dword | Same values as D3DTEXTUREADDRESS without the D3DTADDRESS_ prefix. See D3DSAMP_ADDRESSW.
BorderColor[16] | float4 | D3DCOLOR. Same values as D3DTEXTUREFILTERTYPE without the D3DTEXF_ prefix. See D3DSAMP_BORDERCOLOR.
MagFilter[16] | dword | Same values as D3DTEXTUREFILTERTYPE without the D3DTEXF_ prefix. See D3DSAMP_MAGFILTER.
MaxAnisotropy[16] | dword | Same values as D3DSAMP_MAXANISOTROPY without the D3DSAMP_ prefix.
MaxMipLevel[16] | int | Same values as D3DSAMP_MAXMIPLEVEL without the D3DSAMP_ prefix.
MinFilter[16] | dword | Same values as D3DSAMP_MINFILTER without the D3DSAMP_ prefix.
MipFilter[16] | dword | Same values as D3DSAMP_MIPFILTER without the D3DSAMP_ prefix.
MipMapLodBias[16] | float | Same values as D3DSAMP_MIPMAPLODBIAS without the D3DSAMP_ prefix.
SRGBTexture | float | Same value as D3DSAMP_SRGBTEXTURE without the D3DSAMP_ prefix.

Shader States

There are only two effect shader states: one associated with a vertex shader object and the other associated with a pixel shader object.

Shader State | Type | Values
PixelShader | pixelshader | NULL, an assembly block, a compile target, or a pixel shader parameter.
VertexShader | vertexshader | NULL, an assembly block, a compile target, or a pixel shader parameter.

Shader Constant States

Shader constant states are used to access shader constant parameters.

Shader Constant State | Type | Values
PixelShaderConstant | float[m[n]] | m x n array of floats; m and n are optional.
PixelShaderConstant1 | float4 | One 4-D float.
PixelShaderConstant2 | float4x2 | Two 4-D floats.
PixelShaderConstant3 | float4x3 | Three 4-D floats.
PixelShaderConstant4 | float4x4 | Four 4-D floats.
PixelShaderConstantB | bool[m[n]] | m x n array of bools; m and n are optional.
PixelShaderConstantI | int[m[n]] | m x n array of ints. m and n are optional.
PixelShaderConstantF | float[m[n]] | m x n array of floats. m and n are optional.
VertexShaderConstant | float[m[n]] | m x n array of floats. m and n are optional.
VertexShaderConstant1 | float4 | One 4-D float.
VertexShaderConstant2 | float4x2 | Two 4-D floats.
VertexShaderConstant3 | float4x3 | Three 4-D floats.
VertexShaderConstant4 | float4x4 | Four 4-D floats.
VertexShaderConstantB | bool[m[n]] | m x n array of bools. m and n are optional.
VertexShaderConstantI | int[m[n]] | m x n array of ints. m and n are optional.
VertexShaderConstantF | float[m[n]] | m x n array of floats. m and n are optional.

Texture States

Texture states initialize textures used by the multitexture blender.

Texture State | Type | Values
Texture[8] | texture | NULL, or a texture parameter.

Texture Stage States

Texture stage states set up textures and the texture stages in the multitexture blender.

Texture Stage State | Type | Values
AlphaOp[8] | dword | Same as D3DTEXTUREOP without the D3DTOP_ prefix. See D3DTSS_ALPHAOP.
AlphaArg0[8] | dword | Same as D3DTA without the D3DTA_ prefix. See D3DTSS_ALPHAARG0.
AlphaArg1[8] | dword | Same as D3DTA without the D3DTA_ prefix. See D3DTSS_ALPHAARG1.
AlphaArg2[8] | dword | Same as D3DTA without the D3DTA_ prefix. See D3DTSS_ALPHAARG2.
ColorArg0[8] | dword | Same as D3DTA without the D3DTA_ prefix. See D3DTSS_COLORARG0.
ColorArg1[8] | dword | Same as D3DTA without the D3DTA_ prefix. See D3DTSS_COLORARG1.
ColorArg2[8] | dword | Same as D3DTA without the D3DTA_ prefix. See D3DTSS_COLORARG2.
ColorOp[8] | dword | Same as D3DTEXTUREOP without the D3DTOP_ prefix. See D3DTSS_COLOROP.
BumpEnvLScale[8] | float | Same values as D3DTSS_BUMPENVLSCALE without the D3DTSS_TCI prefix.
BumpEnvLOffset[8] | float | Same values as D3DTSS_BUMPENVLOFFSET without the D3DTSS_TCI prefix.
BumpEnvMat00[8] | float | Same values as D3DTSS_BUMPENVMAT00.
BumpEnvMat01[8] | float | Same values as D3DTSS_BUMPENVMAT01.
BumpEnvMat10[8] | float | Same values as D3DTSS_BUMPENVMAT10.
BumpEnvMat11[8] | float | Same values as D3DTSS_BUMPENVMAT11.
ResultArg[8] | dword | Same as D3DTA without the D3DTA_ prefix. See D3DTSS_RESULTARG.
TexCoordIndex[8] | dword | Same values as D3DTSS_TEXCOORDINDEX without the D3DTSS_TCI prefix.
TextureTransformFlags[8] | dword | Same values as D3DTEXTURETRANSFORMFLAGS values without the D3DTTFF_ prefix. See D3DTSS_TEXTURETRANSFORMFLAGS.

Transform States

Set transform states to initialize transformation matrices. Effects use transposed matrices for efficiency. You can provide transposed matrices to an effect, or an effect will automatically transpose the matrices before using them.

Transform State | Type | Values
ProjectionTransform | float4x4 | A 4x4 matrix of floats. Same values as D3DTS_PROJECTION without the D3DTS_ prefix.
TextureTransform[8] | float4x4 | A 4x4 matrix of floats. Same values as D3DTRANSFORMSTATETYPE without the D3DTS_ prefix.
ViewTransform | float4x4 | A 4x4 matrix of floats. Same values as D3DTS_VIEW without the D3DTS_ prefix.
WorldTransform | float4x4 | A 4x4 matrix of floats.


Usages and Literals
Microsoft DirectX 9.0 SDK Update (October 2004)

Usages and Literals

Usage

Usage is similar to a parameter's scope, because it defines the scope in which the parameter is valid.

Value | Description
const | The parameter will be constant within the scope of all functions. (Note that such parameters can still be written to with either ID3DXEffect or ID3DXEffectCompiler, because this occurs outside the scope of all functions.)
shared | The parameter will be shared in the effect pool.
static | The parameter will be invisible to the application, that is, you cannot access them from ID3DXEffectCompiler or ID3DXEffectCompiler.

Literals

Marking a parameter as literal indicates that its value will never change. This enables the effect compiler to do extra optimization.

Only non-shared top-level parameters can be marked as literal. Parameters can only be marked as literal with ID3DXEffectCompiler. Literal values cannot be set with ID3DXEffect.


Validation
Microsoft DirectX 9.0 SDK Update (October 2004)

Validation

Validation is performed during the effect compile. To validate the current technique, specify NULL as the technique handle to be validated.

Validation will fail for any of the following:

  • If the specified technique handle does not exist.
  • If the application of any state in any pass of the technique fails.
  • If device validation fails after the application of all the states in any pass of the technique.
  • If the PIXELSHADER or VERTEXSHADER effect states are assigned invalid shaders in any pass of the technique.
  • If the device caps do not support cube mapping, and a TEXTURE effect state is assigned a value of type textureCUBE in any pass of the technique.
  • If the device caps do not support volume mapping and a TEXTURE effect state is assigned a value of type texture3D in any pass of the technique.

For more information, see Effect States.


Effect Command-Line Compiler
Microsoft DirectX 9.0 SDK Update (October 2004)

Effect Command-Line Compiler

Effects can be compiled into object files using the Fxc.exe utility in DXSDK/Utilities/ with a target of fx_2_0. The object file can then be used to create an effect directly, using D3DXCreateEffect. The usage is:

Syntax

fxc <options> <file>

Where:

  • options are the compile switch options. Valid options include:
    Switch option | Description
    /T <profile> Target profile, which is a single selection from the following profiles:
    • Effect profile: fx_2_0
    • Procedural texture profile: tx_1_0
    • Vertex shader profiles are contained in: D3DXGetVertexShaderProfile
    • Pixel shader profiles are contained in: D3DXGetPixelShaderProfile
    /E <name> | Entrypoint name.
    /Od | Disable optimizations.
    /Vd | Disable validation.
    /Zi | Enable debugging information.
    /Zpr | Pack matrices in row-major order.
    /Zpc | Pack matrices in column-major order.
    /Gpp | Force partial precision.
    /Fo <file> | Output object file.
    /Fc <file> | Output assembly code listing file.
    /Fx <file> | Output assembly code and hex listing file.
    /Fh <file> | Output header containing object code.
    /D <id>= <text> | Define macro.
    /nologo | Suppress copyright message.
  • file is the filename of the effect to be compiled.

Related Topics

  • DirectX Extensions for Visual Studio .NET


Sample Framework Reference
Microsoft DirectX 9.0 SDK Update (October 2004)

Sample Framework Reference

This section contains reference information for the elements provided by the Microsoft Direct3D sample framework in the Dxut.h header file. The framework provides helper functions, structures, and constant values used in the 3-D graphics C++ sample applications in the Microsoft DirectX software development kit (SDK).

Reference material is divided into the following sections:

  • Functions
  • Callback Functions
  • Structures
  • Enumerations
  • Constants

Related Topics

  • Sample Framework Programming Guide
  • Tutorials and Samples


Functions
Microsoft DirectX 9.0 SDK Update (October 2004)

Functions

The Microsoft Direct3D sample framework supplies the following functions that can be used by an application:

Functions

  • DXUTCreateDevice
  • DXUTCreateDeviceFromSettings
  • DXUTCreateWindow
  • DXUTFindValidDeviceSettings
  • DXUTGetBackBufferSurfaceDesc
  • DXUTGetD3DDevice
  • DXUTGetD3DObject
  • DXUTGetDeviceCaps
  • DXUTGetDeviceSettings
  • DXUTGetDeviceStats
  • DXUTGetElapsedTime
  • DXUTGetExitCode
  • DXUTGetFPS
  • DXUTGetFrameStats
  • DXUTGetHWND
  • DXUTGetHWNDDeviceFullScreen
  • DXUTGetHWNDDeviceWindowed
  • DXUTGetHWNDFocus
  • DXUTGetPresentParameters
  • DXUTGetShowSettingsDialog
  • DXUTGetTime
  • DXUTGetWindowClientRect
  • DXUTGetWindowTitle
  • DXUTInit
  • DXUTIsKeyDown
  • DXUTIsMouseButtonDown
  • DXUTIsRenderingPaused
  • DXUTIsTimePaused
  • DXUTIsWindowed
  • DXUTKillTimer
  • DXUTMainLoop
  • DXUTPause
  • DXUTRender3DEnvironment
  • DXUTResetFrameworkState
  • DXUTSetCallbackDeviceCreated
  • DXUTSetCallbackDeviceDestroyed
  • DXUTSetCallbackDeviceLost
  • DXUTSetCallbackDeviceReset
  • DXUTSetCallbackFrameMove
  • DXUTSetCallbackFrameRender
  • DXUTSetCallbackKeyboard
  • DXUTSetCallbackMouse
  • DXUTSetCallbackMsgProc
  • DXUTSetConstantFrameTime
  • DXUTSetCursorSettings
  • DXUTSetDevice
  • DXUTSetMultimonSettings
  • DXUTSetShowSettingsDialog
  • DXUTSetTimer
  • DXUTSetWindow
  • DXUTShutdown
  • DXUTStaticWndProc
  • DXUTToggleFullscreen
  • DXUTToggleREF


DXUTCreateDevice Function

Creates a Microsoft Direct3D device.

Syntax

HRESULT DXUTCreateDevice(

    UINT AdapterOrdinal,
    bool bWindowed,
    INT nSuggestedWidth,
    INT nSuggestedHeight,
    LPDXUTCALLBACKISDEVICEACCEPTABLE pCallbackIsDeviceAcceptable,
    LPDXUTCALLBACKMODIFYDEVICESETTINGS pCallbackModifyDeviceSettings
);

Parameters

AdapterOrdinal
[in] The index of the desired adapter, or D3DADAPTER_DEFAULT for the primary display. The default value is D3DADAPTER_DEFAULT.
bWindowed
[in] If TRUE, the application will start in windowed mode; if FALSE, the application will start in full-screen mode. The default value is TRUE.
nSuggestedWidth
[in] The requested initial width of the application's back buffer. The actual width may be adjusted to fit device and operating system constraints. The default value is 640.
nSuggestedHeight
[in] The requested initial height of the application's back buffer. The actual height may be adjusted to fit device and operating system constraints. The default value is 480.
pCallbackIsDeviceAcceptable
[in] Pointer to a callback function which assists in selecting a suitable Direct3D device. If set, the callback function will be called during device enumeration to allow the application to exclude devices from the enumerated list; if NULL, the sample framework will add all available devices to the enumerated list. After device enumeration, the framework will use what it determines to be the best device in the enumerated list. The default value is NULL.
pCallbackModifyDeviceSettings
[in] Pointer to a callback function to allow the application to adjust device settings. If the callback function is supplied, it will be called before creating a device.

The callback function is provided with what the framework determines to be the best device settings. The framework allows the application to change device settings; for example, the application can change the behavior flags or the presentation parameters. However, upon creation of the first device, the command-line settings have priority over device setting changes made by the callback function.

If the callback function changes the device settings such that the settings become invalid, the framework will not correct the settings, and device creation will fail.

If NULL, the framework will use what it determines to be the best device settings. The default value is NULL.

Return Value

If the function succeeds, the return value is S_OK.

If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

This function creates a new Direct3D device for the application; alternately, the application can use the DXUTCreateDeviceFromSettings or handle device creation and pass the desired device to the framework by using the DXUTSetDevice function. If neither DXUTCreateDevice, DXUTCreateDeviceFromSettings, nor DXUTSetDevice have been called before calling DXUTMainLoop, the framework will automatically call DXUTCreateDevice using the default parameter values.

The application can call this method after a device has already been created to change the current device.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Creating a Device, DXUTCreateDeviceFromSettings, DXUTMainLoop, DXUTSetDevice


DXUTCreateDeviceFromSettings Function

Creates a Microsoft Direct3D device based on a device described by a DXUTDeviceSettings structure.

Syntax

HRESULT DXUTCreateDeviceFromSettings(

    DXUTDeviceSettings *pDeviceSettings,
    BOOL bPreserveInput
);

Parameters

pDeviceSettings
[in] Pointer to a DXUTDeviceSettings structure that contains the settings for the new device.
bPreserveInput
[in] Indicates whether the input device settings are to be preserved. If TRUE, the device settings in the pDeviceSettings structure will be used without change; however, it is possible that no valid device will be found, causing this function to return a failure code. If FALSE, a valid device will be created with device settings that are as near as possible to the original device settings in pDeviceSettings.

The default value is FALSE.

Return Value

If the function succeeds, the return value is S_OK.

If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

To alter the settings of a current device, the application can call DXUTGetDeviceSettings to get the device settings structure, change it, and then call DXUTCreateDeviceFromSettings. The application can use DXUTFindValidDeviceSettings to ensure that the device settings are valid before calling DXUTCreateDeviceFromSettings.

This function creates a new Direct3D device for the application; alternately, the application can handle device creation and pass the desired device to the sample framework by using the DXUTSetDevice function or calling DXUTCreateDevice. If neither DXUTCreateDevice, DXUTCreateDeviceFromSettings, nor DXUTSetDevice has been called before a framework method that relies on a device object, the framework will automatically call DXUTCreateDevice using the default parameter values.

The application can call this method to change the current device that has already been created.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

DXUTFindValidDeviceSettings


DXUTCreateWindow Function

Creates the window for the application.

Syntax

HRESULT DXUTCreateWindow(

    const WCHAR *strWindowTitle,
    HINSTANCE hInstance,
    HICON hIcon,
    HMENU hMenu,
    INT x,
    INT y
);

Parameters

strWindowTitle
[in] Title bar caption for the window. The default value is L"Direct3D Window".
hInstance
[in] Handle of the application's instance, or NULL to retrieve the handle of the current module. The default value is NULL.
hIcon
[in] Handle to the application's icon, or NULL to use the first icon embedded in the application's executable. The default value is NULL.
hMenu
[in] Handle to the application's menu resource, or NULL to indicate no menu. The default value is NULL.
x
[in] Horizontal coordinate of the window's upper left corner, in screen coordinates. Using a value of CW_USEDEFAULT allows Microsoft Windows to choose an appropriate location. The default value is CW_USEDEFAULT.
y
[in] Vertical coordinate of the window's upper left corner, in screen coordinates. Using a value of CW_USEDEFAULT allows Windows to choose an appropriate location. The default value is CW_USEDEFAULT.

Return Value

If the function succeeds, the return value is S_OK.

If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

This function creates a new window for the application; alternately, the application can handle window creation and pass the desired window handle to the sample framework by using the DXUTSetWindow function. If neither DXUTCreateWindow nor DXUTSetWindow has been called before calling a device creation framework method, the framework will call DXUTCreateWindow using the default parameter values. The window width and height are set later using the device settings.

All parameters are optional.

If both x and y are CW_USEDEFAULT and a windowed non-primary Microsoft Direct3D device is created, the window will automatically be moved to the adapter's monitor to ensure maximum performance.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Creating a Window, CreateWindow Function World Wide Web link


DXUTFindValidDeviceSettings Function

Finds valid device settings to be used to create a new device.

Syntax

HRESULT DXUTFindValidDeviceSettings(

    DXUTDeviceSettings *pOut,
    DXUTDeviceSettings *pIn,
    DXUTMatchOptions *pMatchOptions
);

Parameters

pOut
[out] Pointer to a DXUTDeviceSettings structure that contains valid settings for the new device.
pIn
[in] Pointer to a DXUTDeviceSettings structure that contains desired settings for the new device. The default value is NULL.
pMatchOptions
[in] Pointer to a DXUTMatchOptions structure that contains flags describing how to use the device settings when choosing valid output device settings. Optimal device settings will be created based upon the match values in DXUTMatchOptions.

If NULL, the function acts as if all members of this structure were DXUTMT_IGNORE_INPUT, meaning that the function will return valid device settings as close as possible to default device settings. See Remarks.

The default value is NULL.

Return Value

If the function succeeds, the return value is S_OK.

If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

This function attempts to find valid device settings based upon the input device settings, given by pIn. For each device setting, a match option in the DXUTDeviceSettings structure specifies how the function makes decisions. For example, suppose the application needs a hardware abstraction layer (HAL) device with a back buffer format of D3DFMT_A2B10G10R10, but the HAL device on the system does not support that format. If, however, a reference device is installed that does support the D3DFMT_A2B10G10R10 format, then the function has a choice to either use the reference device or to change to a back buffer format compatible with the HAL device. The match options in DXUTMatchOptions let the application control how these choices are made.

This function is internally used when toggling between full screen and windowed modes, when selecting between HAL and reference devices, and in DXUTCreateDevice.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Selecting the Best Available Device, DXUTMatchOptions, DXUTCreateDeviceFromSettings


DXUTGetBackBufferSurfaceDesc Function

Gets a pointer to a D3DSURFACE_DESC surface description of the back buffer on the current adapter.

Syntax

const D3DSURFACE_DESC *DXUTGetBackBufferSurfaceDesc(VOID);

Return Value

Pointer to a D3DSURFACE_DESC surface description of the back buffer on the current adapter.

Remarks

If no device exists, then the D3DSURFACE_DESC structure is filled with zeros.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTGetD3DDevice Function

Gets a pointer to the IDirect3DDevice9 interface that represents the current device.

Syntax

IDirect3DDevice9 *DXUTGetD3DDevice(VOID);

Return Value

Pointer to the IDirect3DDevice9 that represents the current device. NULL is returned if no device has been created. See Remarks.

Remarks

This function exposes access to a global IDirect3DDevice9 object. The reference count on this device interface is not incremented, so a calling function should not release the IDirect3DDevice9 interface pointer returned by this function.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTGetD3DObject Function

Gets a pointer to the IDirect3D9 object.

Syntax

IDirect3D9 *DXUTGetD3DObject(VOID);

Return Value

Pointer to the IDirect3D9 object. NULL is returned if no IDirect3D9 object has been created. See Remarks.

Remarks

This function exposes access to a global IDirect3D9 object. The reference count on this object interface is not incremented, so a calling function should not release the IDirect3D9 interface pointer returned by this function.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTGetDeviceCaps Function

Gets a pointer to the D3DCAPS9 capabilities of the current device.

Syntax

const D3DCAPS9 *DXUTGetDeviceCaps(VOID);

Return Value

Pointer to the D3DCAPS9 capabilities of the current device.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTGetDeviceSettings Function

Gets the DXUTDeviceSettings structure used to create the current device.

Syntax

DXUTDeviceSettings DXUTGetDeviceSettings(VOID);

Return Value

DXUTDeviceSettings structure used to create the current device.

Remarks

If no device exists, then the DXUTDeviceSettings structure is filled with zeros.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTGetDeviceStats Function

Gets a pointer to a string containing the current device type, vertex processing behavior, and device name.

Syntax

LPCWSTR DXUTGetDeviceStats(VOID);

Return Value

Pointer to a string containing the current device type, vertex processing behavior, and device name.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTGetElapsedTime Function

Gets the time elapsed since the last frame.

Syntax

FLOAT DXUTGetElapsedTime(VOID);

Return Value

Time elapsed, in seconds, since the last frame.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTGetExitCode Function

Gets the sample framework exit code.

Syntax

INT DXUTGetExitCode(VOID);

Return Value

A sample framework exit code, which will be one of the following possible values. There is no exit code value of 1.

Value | Description
0 | Successful execution.
2 | No IDirect3D9 object could be found.
3 | No IDirect3DDevice9 device could be found with the specified device settings.
4 | The Microsoft DirectX software development kit (SDK) media file could not be found.
5 | The IDirect3DDevice9 device has a non-zero reference count, meaning that some objects were not released.
6 | An error occurred when attempting to create an IDirect3DDevice9 device.
7 | An error occurred when attempting to reset an IDirect3DDevice9 device.
8 | An error occurred in the device creation callback function.
9 | An error occurred in the device creation callback function.
10 | The incorrect version of Microsoft Direct3D or D3DX is installed.

Remarks

The return value of this function is typically used as the return code of the application's WinMain function. Command-line tests can be performed on applications using this return code.

The following is an example of command-line usage that returns the sample framework exit code:

start /wait BasicHLSL.exe
echo %errorlevel%

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTGetFPS Function

Gets the current number of frames being presented per second.

Syntax

FLOAT DXUTGetFPS(VOID);

Return Value

The current number of frames being presented per second.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTGetFrameStats Function

Gets a pointer to a string containing the current number of frames per second, resolution, back buffer format, and depth stencil format.

Syntax

LPCWSTR DXUTGetFrameStats(VOID);

Return Value

Pointer to a string containing the current number of frames per second, resolution, back buffer format, and depth stencil format.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTGetHWND Function

Gets a handle to the current device window.

Syntax

HWND DXUTGetHWND(VOID);

Return Value

A handle to the current device window.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Creating a Window


DXUTGetHWNDDeviceFullScreen Function

Gets the handle of the full-screen mode device window.

Syntax

HWND DXUTGetHWNDDeviceFullScreen(VOID);

Return Value

Returns a handle to the device window.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTGetHWNDDeviceWindowed Function

Gets the handle of the windowed-mode device window.

Syntax

HWND DXUTGetHWNDDeviceWindowed(VOID);

Return Value

Returns a handle to the device window.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTGetHWNDFocus Function

Gets the handle of the focus window.

Syntax

HWND DXUTGetHWNDFocus(VOID);

Return Value

Handle to the focus window.

Remarks

The focus window informs Microsoft Direct3D when the application is switched to a background window with an ALT+TAB key entry, a mouse click, or by other means.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTGetPresentParameters Function

Gets the presentation parameters of the current device.

Syntax

D3DPRESENT_PARAMETERS DXUTGetPresentParameters(VOID);

Return Value

The presentation parameters of the current device.

Remarks

If no device exists, then the D3DPRESENT_PARAMETERS structure is filled with zeros.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTGetShowSettingsDialog Function

Indicates whether the sample framework's device settings dialog box is currently showing.

Syntax

BOOL DXUTGetShowSettingsDialog(VOID);

Return Value

TRUE if the sample framework's device settings dialog box is currently showing; otherwise FALSE.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTGetTime Function

Gets the current time, in seconds.

Syntax

DOUBLE DXUTGetTime(VOID);

Return Value

The current time, in seconds.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTGetWindowClientRect Function

Gets the client rectangle of the application device window.

Syntax

const RECT &DXUTGetWindowClientRect(VOID);

Return Value

Address of the RECT World Wide Web link structure of the window for which the application device has a handle.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTGetWindowTitle Function

Gets a pointer to the application window title.

Syntax

LPCWSTR DXUTGetWindowTitle(VOID);

Return Value

Pointer to the application window title.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTInit Function

Initializes the sample framework.

Syntax

HRESULT DXUTInit(

    BOOL bParseCommandLine,
    BOOL bHandleDefaultHotkeys,
    BOOL bShowMsgBoxOnError
);

Parameters

bParseCommandLine
[in] If TRUE, the sample framework checks for command-line arguments. The application performs the following actions based upon the entered command-line arguments.

Command-line Argument | Action
-adapter:# | Forces the application to use this adapter ordinal. Fails if the adapter ordinal does not exist.
-fullscreen | Starts in full-screen mode.
-windowed | Starts in windowed mode.
-startx:# | For windowed mode, sets the x-coordinate of the window position to the value of #.
-starty:# | For windowed mode, sets the y-coordinate of the window position to the value of #.
-height:# | Sets the window height to the value of #. For full-screen mode, the sample framework picks the closest possible supported mode.
-width:# | Sets the window width to the value of #. For full-screen mode, the sample framework picks the closest possible supported mode.
-forcehal | Forces the application to use a hardware abstraction layer (HAL) device type, D3DDEVTYPE_HAL. Fails if a HAL device does not exist.
-forcehwvp | Forces the application to use hardware vertex processing. Fails if the device does not support this mode.
-forcepurehwvp | Forces the application to use pure hardware vertex processing. Fails if the device does not support this mode.
-forceref | Forces the application to use a reference device type, D3DDEVTYPE_REF. Fails if a reference device does not exist.
-forceswvp | Forces the application to use software vertex processing.
-constantframetime | Uses a constant frame time.
-noerrormsgboxes | Prevents the display of message boxes generated by the framework, allowing the application to be run without user interaction.
-quitafterframe:# | Forces the application to quit after frame #.

Command-line arguments take precedence over options set by the application when a Microsoft Direct3D device is first created, but they are ignored afterward to allow the user to interactively change the settings.

The default value of this parameter is TRUE.

bHandleDefaultHotkeys
[in] If TRUE, the sample framework automatically responds to certain keyboard input. The following table lists the keyboard input that is handled by default.

Key | Action
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.
F2 | Prompts the user to select a new rendering device or display mode.
F3 | Toggles between HAL and reference devices.
F8 | Toggles between wireframe and rendered views.
PAUSE | Pauses the application.

The default value of this parameter is TRUE. If FALSE, the application is free to respond to these keystrokes as desired.

bShowMsgBoxOnError
[in] If TRUE, the sample framework displays a message box if there is an error condition. The default value of this parameter is TRUE.

Return Value

If the function succeeds, the return value is S_OK.

If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

If this function has not been called before DXUTCreateWindow or DXUTSetWindow, the framework will automatically call this function using the default parameter values.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Initializing the Sample Framework, Device Types, Processing Vertex Data, DXUTCreateWindow, DXUTSetWindow, Error Messages


DXUTIsKeyDown Function

Indicates whether a specified keyboard key is up or down at the time the function is called.

Syntax

BOOL DXUTIsKeyDown(

    BYTE vKey
);

Parameters

vKey
[in] Virtual key code World Wide Web link of a keyboard key. For example VK_F1, VK_LSHIFT, VK_RCONTROL, VK_RMENU, and 41 (representing the 'A' key).

Return Value

TRUE if the specified vKey keyboard key is down; FALSE otherwise.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

DXUTIsMouseButtonDown


DXUTIsMouseButtonDown Function

Indicates whether a specified mouse button is up or down at the time the function is called.

Syntax

BOOL DXUTIsMouseButtonDown(

    BYTE vButton
);

Parameters

vButton
[in] Virtual key code World Wide Web link of a mouse button. Allowed values are VK_LBUTTON, VK_RBUTTON, VK_MBUTTON, VK_XBUTTON1, and VK_XBUTTON2.

Return Value

TRUE if the specified vButton mouse button is down; FALSE otherwise.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

DXUTIsKeyDown


DXUTIsRenderingPaused Function

Indicates whether rendering has been paused on the current device.

Syntax

BOOL DXUTIsRenderingPaused(VOID);

Return Value

TRUE if rendering has been paused.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTIsTimePaused Function

Indicates whether time has been paused on the current device.

Syntax

BOOL DXUTIsTimePaused(VOID);

Return Value

TRUE if time has been paused.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTIsWindowed Function

Indicates whether the application is in windowed mode.

Syntax

BOOL DXUTIsWindowed(VOID);

Return Value

If TRUE, the application is in windowed mode. If the application is not in windowed mode, or no device exists, then FALSE is returned.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTKillTimer Function

Uninstalls an existing timer.

Syntax

HRESULT DXUTKillTimer(

    UINT nIDEvent
);

Parameters

nIDEvent
[in] The event identifier (ID) for the timer being destroyed. This ID is provided to the application by the DXUTSetTimer method.

Return Value

If the function succeeds, the return value is S_OK.

If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

Timers created with DXUTSetTimer can be destroyed with DXUTKillTimer.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

LPDXUTCALLBACKTIMER, DXUTSetTimer


DXUTMainLoop Function

Starts the main execution loop of the sample framework.

Syntax

HRESULT DXUTMainLoop(

    HACCEL hAccel
);

Parameters

hAccel
[in] Handle to an accelerator table to use in translating keyboard messages from the Microsoft Windows message queue, or NULL if not using an accelerator table. The default value is NULL.

Return Value

If the function succeeds, the return value is S_OK.

If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

This function starts the message loop that will run for the lifetime of the application. During execution, DXUTMainLoop calls the registered callback functions to inform the application of input events and to trigger resource management and render calls.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Using the Main Loop with the Sample Framework


DXUTPause Function

Sets the paused state of the sample framework internal timer and/or rendering process.

Syntax

VOID DXUTPause(

    BOOL bPauseTime,
    BOOL bPauseRendering
);

Parameters

bPauseTime
[in] If TRUE, the sample framework internal timer is paused. If FALSE, the timer is resumed from a paused state. See Remarks.
bPauseRendering
[in] If TRUE, the sample framework will not call the LPDXUTCALLBACKFRAMERENDER callback function; the framework will continue to call the LPDXUTCALLBACKFRAMEMOVE callback function. If FALSE, rendering will resume from a paused state. See Remarks.

Return Value

No return value.

Remarks

The timer controls the fTime and fElapsedTime parameters passed to the LPDXUTCALLBACKFRAMEMOVE or LPDXUTCALLBACKFRAMERENDER callback functions.

When time is paused, fTime will remain unchanged and fElapsedTime will be 0.0f. The LPDXUTCALLBACKFRAMEMOVE and LPDXUTCALLBACKFRAMERENDER callback functions will still be called. The camera can therefore move while time is paused.

When rendering is paused, the LPDXUTCALLBACKFRAMERENDER callback function and IDirect3DDevice9::Present will not be called, and the framework will periodically yield time to other processes by calling Sleep World Wide Web link.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

DXUTSetCallbackFrameMove, DXUTSetCallbackFrameRender, LPDXUTCALLBACKFRAMEMOVE, LPDXUTCALLBACKFRAMERENDER


DXUTRender3DEnvironment Function

Renders the 3-D environment and updates application and device parameters.

Syntax

VOID DXUTRender3DEnvironment(VOID);

Return Value

No return value.

Remarks

This method does not normally need to be called. It is useful only when the application does not use DXUTMainLoop but still wants the sample framework to assist with rendering.

This method checks whether the device is lost. If so, the method attempts to reset the device and then calls the LPDXUTCALLBACKFRAMEMOVE and LPDXUTCALLBACKFRAMERENDER callback functions.

If the application window is minimized or the application is paused, CPU time is yielded to other processes.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Using the Main Loop with the Sample Framework


DXUTResetFrameworkState Function

Resets the sample framework state to its initial default state. All previous framework state changes are lost.

Syntax

VOID DXUTResetFrameworkState(VOID);

Return Value

No return value.

Remarks

This function is useful for testing purposes because the application process does not have to be restarted.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTSetCallbackDeviceCreated Function

Sets the Microsoft Direct3D device-created callback function.

Syntax

VOID DXUTSetCallbackDeviceCreated(

    LPDXUTCALLBACKDEVICECREATED pCallbackDeviceCreated
);

Parameters

pCallbackDeviceCreated
[in] Pointer to a LPDXUTCALLBACKDEVICECREATED callback function. If the callback function is supplied, it will be called after the Direct3D device has been created. Device creation will happen during application initialization and if the device is changed.

If NULL, the sample framework will not notify the application about device creation.

Return Value

No return value.

Remarks

The LPDXUTCALLBACKDEVICECREATED callback function is the appropriate location for the application to create resources in D3DPOOL_MANAGED or D3DPOOL_SYSTEMMEM memory, because these resources do not need to be reloaded whenever the device is reset. Resources created in the LPDXUTCALLBACKDEVICECREATED callback function should be deleted in the LPDXUTCALLBACKDEVICEDESTROYED callback function.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Device Events, LPDXUTCALLBACKDEVICECREATED, LPDXUTCALLBACKDEVICEDESTROYED, DXUTSetCallbackDeviceDestroyed


DXUTSetCallbackDeviceDestroyed Function

Sets the Microsoft Direct3D device-destroyed callback function.

Syntax

VOID DXUTSetCallbackDeviceDestroyed(

    LPDXUTCALLBACKDEVICEDESTROYED pCallbackDeviceDestroyed
);

Parameters

pCallbackDeviceDestroyed
[in] Pointer to a LPDXUTCALLBACKDEVICEDESTROYED callback function. If the callback function is supplied, it will be called when the Direct3D device has been destroyed. Device destruction will happen as a result of program termination and if the Direct3D device changes.

If NULL, the sample framework will not notify the application about device destroyed events.

Return Value

No return value.

Remarks

Resources created in the LPDXUTCALLBACKDEVICECREATED callback function should be deleted in the LPDXUTCALLBACKDEVICEDESTROYED callback function. The deleted resources will generally include all resources created in D3DPOOL_MANAGED or D3DPOOL_SYSTEMMEM memory.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Device Events, LPDXUTCALLBACKDEVICEDESTROYED, LPDXUTCALLBACKDEVICECREATED, DXUTSetCallbackDeviceCreated


DXUTSetCallbackDeviceLost Function

Sets the Microsoft Direct3D lost-device callback function.

Syntax

VOID DXUTSetCallbackDeviceLost(

    LPDXUTCALLBACKDEVICELOST pCallbackDeviceLost
);

Parameters

pCallbackDeviceLost
[in] Pointer to a LPDXUTCALLBACKDEVICELOST callback function. If the callback function is supplied, it will be called when the Direct3D device has been lost, which will happen after a lost-device scenario.

If NULL, the sample framework will not notify the application about lost-device events.

Return Value

No return value.

Remarks

Resources created in the LPDXUTCALLBACKDEVICERESET callback function should be deleted in the LPDXUTCALLBACKDEVICELOST callback function. The deleted resources will generally include all resources created in D3DPOOL_DEFAULT memory.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Device Events, LPDXUTCALLBACKDEVICELOST, LPDXUTCALLBACKDEVICERESET, DXUTSetCallbackDeviceReset, Lost Devices


DXUTSetCallbackDeviceReset Function

Sets the Microsoft Direct3D device reset callback function.

Syntax

VOID DXUTSetCallbackDeviceReset(

    LPDXUTCALLBACKDEVICERESET pCallbackDeviceReset
);

Parameters

pCallbackDeviceReset
[in] Pointer to a LPDXUTCALLBACKDEVICERESET callback function. If the callback function is supplied, it will be called when the Direct3D device has been reset, which will happen after a lost-device scenario.

If NULL, the sample framework will not notify the application about device reset events.

Return Value

No return value.

Remarks

The LPDXUTCALLBACKDEVICERESET callback function is the appropriate location for the application to create default pool resources, in D3DPOOL_DEFAULT memory, because these resources need to be reloaded whenever the device is reset. Resources created in the LPDXUTCALLBACKDEVICERESET callback function should be deleted in the LPDXUTCALLBACKDEVICELOST callback function.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Device Events, LPDXUTCALLBACKDEVICERESET, LPDXUTCALLBACKDEVICELOST, DXUTSetCallbackDeviceLost, Lost Devices


DXUTSetCallbackFrameMove Function

Sets the frame update callback function.

Syntax

VOID DXUTSetCallbackFrameMove(

    LPDXUTCALLBACKFRAMEMOVE pCallbackFrameMove
);

Parameters

pCallbackFrameMove
[in] Pointer to a LPDXUTCALLBACKFRAMEMOVE callback function. If the callback function is supplied, it will be called at the beginning of every frame to facilitate updates to the scene.

If NULL, the sample framework will not notify the application about new frames.

Return Value

No return value.

Remarks

The LPDXUTCALLBACKFRAMEMOVE callback function is the appropriate location for the application to handle updates to the scene. However, LPDXUTCALLBACKFRAMEMOVE is not intended to contain actual rendering calls, which should instead be placed in the LPDXUTCALLBACKFRAMERENDER callback function.

The LPDXUTCALLBACKFRAMEMOVE callback function will be called once per frame, while the LPDXUTCALLBACKFRAMERENDER callback function will be called when the scene needs to be rendered, which might be more than once per frame.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Frame Events, LPDXUTCALLBACKFRAMEMOVE, LPDXUTCALLBACKFRAMERENDER, DXUTSetCallbackFrameRender


DXUTSetCallbackFrameRender Function

Sets the frame render callback function.

Syntax

VOID DXUTSetCallbackFrameRender(

    LPDXUTCALLBACKFRAMERENDER pCallbackFrameRender
);

Parameters

pCallbackFrameRender
[in] Pointer to a LPDXUTCALLBACKFRAMERENDER callback function. If the callback function is supplied, it will be called at the end of every frame to facilitate rendering of the scene.

If NULL, the sample framework will not prompt the application to render the scene.

Return Value

No return value.

Remarks

The LPDXUTCALLBACKFRAMERENDER callback function is the appropriate location for the application to render the current scene. The LPDXUTCALLBACKFRAMEMOVE callback function will be called once per frame, while LPDXUTCALLBACKFRAMERENDER will be called when the scene needs to be rendered, which might be more than once per frame.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Frame Events, LPDXUTCALLBACKFRAMERENDER, LPDXUTCALLBACKFRAMEMOVE, DXUTSetCallbackFrameMove


DXUTSetCallbackKeyboard Function

Sets the keyboard event callback function.

Syntax

VOID DXUTSetCallbackKeyboard(

    LPDXUTCALLBACKKEYBOARD pCallbackKeyboard
);

Parameters

pCallbackKeyboard
[in] Pointer to a LPDXUTCALLBACKKEYBOARD keyboard event callback function. If supplied, the callback function will be called for keyboard events.

If NULL, the sample framework will not notify the application about keyboard events.

Return Value

No return value.

Remarks

The pCallbackKeyboard keyboard event callback function will be called when any one of the following keyboard events occurs:

  • WM_KEYDOWN World Wide Web link
  • WM_KEYUP World Wide Web link
  • WM_SYSKEYDOWN World Wide Web link
  • WM_SYSKEYUP World Wide Web link

This callback mechanism is provided to simplify handling keyboard messages through the windows message pump, but does not preclude the application from handling those messages directly through the Microsoft Windows WindowProc World Wide Web link callback function.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Message Events, LPDXUTCALLBACKKEYBOARD, LPDXUTCALLBACKMOUSE, LPDXUTCALLBACKMSGPROC, DXUTSetCallbackMouse, DXUTSetCallbackMsgProc, WindowProc World Wide Web link


DXUTSetCallbackMouse Function

Sets the mouse event callback function.

Syntax

VOID DXUTSetCallbackMouse(

    LPDXUTCALLBACKMOUSE pCallbackMouse,
    BOOL bIncludeMouseMove
);

Parameters

pCallbackMouse
[in] Pointer to an LPDXUTCALLBACKMOUSE mouse event callback function. If supplied, the callback function will be called for mouse events.

If NULL, the sample framework will not notify the application about mouse events.
bIncludeMouseMove
[in] If TRUE, the Microsoft Windows WM_MOUSEMOVE World Wide Web link message is passed to the pCallbackMouse callback function. Default value is FALSE.

Return Value

No return value.

Remarks

The pCallbackMouse mouse event callback function will be called when any one of the following mouse events occurs:

  • WM_LBUTTONDBLCLK World Wide Web link
  • WM_LBUTTONDOWN World Wide Web link
  • WM_LBUTTONUP World Wide Web link
  • WM_MBUTTONDBLCLK World Wide Web link
  • WM_MBUTTONDOWN World Wide Web link
  • WM_MBUTTONUP World Wide Web link
  • WM_MOUSEWHEEL World Wide Web link
  • WM_RBUTTONDBLCLK World Wide Web link
  • WM_RBUTTONDOWN World Wide Web link
  • WM_RBUTTONUP World Wide Web link
  • WM_XBUTTONDBLCLK World Wide Web link
  • WM_XBUTTONDOWN World Wide Web link
  • WM_XBUTTONUP World Wide Web link

This callback mechanism is provided to simplify handling mouse messages through the Windows message pump, but does not preclude the application from handling those messages directly through the Windows WindowProc World Wide Web link callback function.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Message Events, LPDXUTCALLBACKMOUSE, LPDXUTCALLBACKKEYBOARD, LPDXUTCALLBACKMSGPROC, DXUTSetCallbackKeyboard, DXUTSetCallbackMsgProc, WindowProc World Wide Web link


DXUTSetCallbackMsgProc Function

Sets the window message callback function.

Syntax

VOID DXUTSetCallbackMsgProc(

    LPDXUTCALLBACKMSGPROC pCallbackMsgProc
);

Parameters

pCallbackMsgProc
[in] Pointer to a LPDXUTCALLBACKMSGPROC callback function. If supplied, the sample framework will call this function when it receives window messages.

If NULL, the sample framework will not notify the application about window messages.

Return Value

No return value.

Remarks

With the use of the LPDXUTCALLBACKMSGPROC pbNoFurtherProcessing parameter, the application can contol the framework's level of involvement in processing window messages. If the application sets the pbNoFurtherProcessing parameter to TRUE in the call to LPDXUTCALLBACKMSGPROC, the framework will not process the message and will immediately return with the value returned by LPDXUTCALLBACKMSGPROC. If the application sets pbNoFurtherProcessing to FALSE, the framework will handle window management events.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Creating a Window, Message Events, LPDXUTCALLBACKMSGPROC, DXUTSetCallbackKeyboard, DXUTSetCallbackMouse, LPDXUTCALLBACKKEYBOARD, LPDXUTCALLBACKMOUSE, WindowProc World Wide Web link


DXUTSetConstantFrameTime Function

Enables or disables a constant frame time.

Syntax

HRESULT DXUTSetConstantFrameTime(

    BOOL bEnabled,
    FLOAT fTimePerFrame
);

Parameters

bEnabled
[in] If TRUE, a constant frame time will be enabled.
fTimePerFrame
[in] Time per frame, in seconds. The default value is 0.0333f, so the fTime parameter of LPDXUTCALLBACKFRAMEMOVE and LPDXUTCALLBACKFRAMERENDER will advance one second for every 30 frames.

Return Value

If the function succeeds, the return value is S_OK.

If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

This function simulates a fixed-frame rate render loop by sending a constant value for elapsed time to the LPDXUTCALLBACKFRAMEMOVE and LPDXUTCALLBACKFRAMERENDER callback functions. The default rate is one second for every 30 frames. The application itself will continue to render at an unregulated rate (which may be far higher than the specified frame rate).

This function is useful for saving the rendered output to a video format for playback, allowing animation at a rate independent of the actual rate at which frames were rendered.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

LPDXUTCALLBACKFRAMEMOVE, LPDXUTCALLBACKFRAMERENDER


DXUTSetCursorSettings Function

Sets options for cursor usage in full-screen mode.

Syntax

HRESULT DXUTSetCursorSettings(

    BOOL bShowCursorWhenFullScreen,
    BOOL bClipCursorWhenFullScreen
);

Parameters

bShowCursorWhenFullScreen
[in] Cursor visibility flag. If TRUE, the cursor will be visible when the application is running in full-screen mode.
bClipCursorWhenFullScreen
[in] Cursor clipping flag. If TRUE, the cursor will be restricted from exiting the screen boundaries when the application is running in full screen mode.

Return Value

If the function succeeds, the return value is S_OK.

If the function fails, the return value can be one of the error codes in DXUTERR.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTSetDevice Function

Sets an existing Microsoft Direct3D device for use by the sample framework.

Syntax

HRESULT DXUTSetDevice(

    IDirect3DDevice9 *pd3dDevice
);

Parameters

pd3dDevice
[in] Pointer to a IDirect3DDevice9 object to use for rendering.

Return Value

If the function succeeds, the return value is S_OK.

If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

This function relies on an existing Direct3D device object created by the application. Alternately, the application can call DXUTCreateDevice or DXUTCreateDeviceFromSettings to have the sample framework create a device. If neither DXUTCreateDevice, DXUTCreateDeviceFromSettings, nor DXUTSetDevice have been called before a framework method that relies on a device, the framework will automatically call DXUTCreateDevice using the default parameter values.

The application can call this function after a device has already been created to change the current device.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Using Your Own Device, DXUTCreateDevice, DXUTCreateDeviceFromSettings


DXUTSetMultimonSettings Function

Sets options for how the sample framework functions on multiple monitors.

Syntax

VOID DXUTSetMultimonSettings(

    BOOL bAutoChangeAdapter
);

Parameters

bAutoChangeAdapter
[in] If TRUE and the application window is relocated to a different monitor, the sample framework will automatically change to use the new monitor's adapter, and device callback functions will be called to recreate the scene.

Return Value

No return value.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTSetShowSettingsDialog Function

Shows or hides the sample framework's device settings dialog box.

Syntax

VOID DXUTSetShowSettingsDialog(

    BOOL bShow
);

Parameters

bShow
[in] If TRUE, the settings dialog box will be displayed.

Return Value

No return value.

Remarks

The sample framework's device settings dialog box provides the user with easy run-time access to change most of the device settings. The sample framework will handle all user input and rendering while the settings dialog box is visible.

Note The settings dialog does not have direct access to the internal sample framework state. A similar custom dialog box interface with the framework uses public framework functions, such as DXUTGetDeviceSettings and DXUTCreateDeviceFromSettings.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTSetTimer Function

Installs a new timer.

Syntax

HRESULT DXUTSetTimer(

    LPDXUTCALLBACKTIMER pCallbackTimer,
    FLOAT fTimeoutInSecs,
    UINT *pnIDEvent
);

Parameters

pCallbackTimer
[in] Pointer to a timer callback function. The callback function is to be called at the specified fTimeoutInSecs timeout intervals. May not be NULL.
fTimeoutInSecs
[in] Interval, in seconds, between successive calls to the timer callback function. The default value is 1.0f.
pnIDEvent
[in] Optional pointer to a variable to receive the event identifier (ID) for the new timer. This event ID will be passed to the timer callback function to indicate which timer generated the event, allowing the application to use a single callback function for multiple timers. The default value is NULL.

Return Value

If the function succeeds, the return value is S_OK.

If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

Timers created with DXUTSetTimer can be destroyed with DXUTKillTimer.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

LPDXUTCALLBACKTIMER, DXUTKillTimer


DXUTSetWindow Function

Sets a previously created window for use by the sample framework.

Syntax

HRESULT DXUTSetWindow(

    HWND hWndFocus,
    HWND hWndDeviceFullScreen,
    HWND hWndDeviceWindowed,
    BOOL bHandleMessages
);

Parameters

hWndFocus
[in] Handle of the Microsoft Direct3D focus window. Must not be NULL.
hWndDeviceFullScreen
[in] Handle of the Direct3D device window when in full-screen mode. Must not be NULL.
hWndDeviceWindowed
[in] Handle of the Direct3D device window when in windowed mode. Must not be NULL.
bHandleMessages
[in] If TRUE, the framework will handle and respond to messages for the window. If FALSE, the framework will not handle messages for the window, giving the application full responsibility for responding to messages.

The default value is TRUE.

Return Value

If the function succeeds, the return value is S_OK.

If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

This function relies on an existing window object created by the application. Alternately, the application can call DXUTCreateWindow to have the sample framework create a window. If neither DXUTCreateWindow nor DXUTSetWindow has been called before calling a framework device creation method, the framework will automatically call DXUTCreateWindow using the default parameter values.

No input parameter may be NULL. However, the same handle may be used for more than one parameter.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Using Your Own Window, DXUTCreateWindow


DXUTShutdown Function

Triggers program termination and sample framework cleanup.

Syntax

VOID DXUTShutdown(VOID);

Return Value

No return value.

Remarks

It is not necessary for the application to call this function, since the application lifespan is handled by the framework. However, the application can call this function to cleanly terminate the application process.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTStaticWndProc Function

Processes messages sent to a window.

Syntax

LRESULT_CALLBACK DXUTStaticWndProc(

    HWND hWnd,
    UINT uMsg,
    WPARAM wParam,
    LPARAM lParam
);

Parameters

hWnd
[in] Handle to the window.
uMsg
[in] Specifies the message.
wParam
[in] Specifies additional message information. The contents of this parameter depend on the value of the uMsg parameter.
lParam
[in] Specifies additional message information. The contents of this parameter depend on the value of the uMsg parameter.

Return Value

If the function has processed window messages successfully, returns zero; otherwise, returns a nonzero value.

Remarks

This function is typically used when the application creates the window. This function can be called from inside the application's window procedure, or it can be used directly as the window procedure.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Using Your Own Window, DXUTSetCallbackMsgProc, DXUTSetCallbackKeyboard, DXUTSetCallbackMouse, LPDXUTCALLBACKKEYBOARD, LPDXUTCALLBACKMOUSE, LPDXUTCALLBACKMSGPROC, WindowProc World Wide Web link


DXUTToggleFullscreen Function

Switches the application between windowed and full-screen modes.

Syntax

HRESULT DXUTToggleFullscreen(VOID);

Return Value

If the function succeeds, the return value is S_OK.

If the function fails, the return value can be one of the error codes in DXUTERR.

Remarks

Toggling between windowed and full-screen modes will result in the Microsoft Direct3D device being reset or re-created.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


DXUTToggleREF Function

Switches the application between hardware abstraction layer (HAL) and reference devices.

Syntax

VOID DXUTToggleREF(VOID);

Return Value

No return value.

Remarks

Toggling between HAL and reference devices will result in the Microsoft Direct3D device being re-created.

Function Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98


Callback Functions
Microsoft DirectX 9.0 SDK Update (October 2004)

Callback Functions

The Microsoft Direct3D sample framework supplies the following callback functions that may be implemented by an application:

Functions

  • LPDXUTCALLBACKDEVICECREATED
  • LPDXUTCALLBACKDEVICEDESTROYED
  • LPDXUTCALLBACKDEVICELOST
  • LPDXUTCALLBACKDEVICERESET
  • LPDXUTCALLBACKFRAMEMOVE
  • LPDXUTCALLBACKFRAMERENDER
  • LPDXUTCALLBACKISDEVICEACCEPTABLE
  • LPDXUTCALLBACKKEYBOARD
  • LPDXUTCALLBACKMODIFYDEVICESETTINGS
  • LPDXUTCALLBACKMOUSE
  • LPDXUTCALLBACKMSGPROC
  • LPDXUTCALLBACKTIMER


LPDXUTCALLBACKDEVICECREATED Prototype

Application-defined resource creation callback function, called by the sample framework after the device is created. Passes a pointer to the newly created Microsoft Direct3D device.

Syntax

typedef HRESULT (CALLBACK *LPDXUTCALLBACKDEVICECREATED)(

    IDirect3DDevice9 *pd3dDevice,
    const D3DSURFACE_DESC *pBackBufferSurfaceDesc
);

Parameters

pd3dDevice
[out] Pointer to the newly created IDirect3DDevice9 device.
pBackBufferSurfaceDesc
[out] Pointer to a D3DSURFACE_DESC surface description of the back buffer.

Return Value

In general, if no error occurs, program the function to return S_OK.

Program the function to return an HRESULT failure code if the function fails. If the sample framework receives a failure HRESULT code, it will shut down the application.

Remarks

This callback function is the appropriate location for the application to create resources in D3DPOOL_MANAGED or D3DPOOL_SYSTEMMEM memory, since these resources do not need to be reloaded whenever the device is reset. Resources created in this callback function should be deleted in the LPDXUTCALLBACKDEVICEDESTROYED callback function.

Prototype Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Device Events, DXUTSetCallbackDeviceCreated, DXUTSetCallbackDeviceDestroyed, LPDXUTCALLBACKDEVICEDESTROYED


LPDXUTCALLBACKDEVICEDESTROYED Prototype

Application-defined resource deletion callback function, to be called by the sample framework immediately after the device is destroyed.

Syntax

typedef VOID (CALLBACK *LPDXUTCALLBACKDEVICEDESTROYED)(VOID);

Return Value

No return value.

Remarks

This callback function should be used to delete resources created in the LPDXUTCALLBACKDEVICECREATED callback function. The deleted resources will generally include all resources created in D3DPOOL_MANAGED or D3DPOOL_SYSTEMMEM memory.

Prototype Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Device Events, DXUTSetCallbackDeviceDestroyed, DXUTSetCallbackDeviceCreated, LPDXUTCALLBACKDEVICECREATED


LPDXUTCALLBACKDEVICELOST Prototype

Application-defined resource deletion callback function, called by the sample framework after the Microsoft Direct3D device is lost.

Syntax

typedef VOID (CALLBACK *LPDXUTCALLBACKDEVICELOST)(VOID);

Return Value

No return value.

Remarks

This callback function should be used to delete resources created in the LPDXUTCALLBACKDEVICERESET callback function. The deleted resources will generally include all resources created in D3DPOOL_DEFAULT memory.

Prototype Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Device Events, DXUTSetCallbackDeviceLost, DXUTSetCallbackDeviceReset, LPDXUTCALLBACKDEVICERESET, Lost Devices


LPDXUTCALLBACKDEVICERESET Prototype

Application-defined resource creation callback function, called by the sample framework after the Microsoft Direct3D device is reset. Passes a pointer to the newly reset device.

Syntax

typedef HRESULT (CALLBACK *LPDXUTCALLBACKDEVICERESET)(

    IDirect3DDevice9 *pd3dDevice,
    const D3DSURFACE_DESC *pBackBufferSurfaceDesc
);

Parameters

pd3dDevice
[out] Pointer to the reset IDirect3DDevice9 device.
pBackBufferSurfaceDesc
[out] Pointer to a D3DSURFACE_DESC surface description of the back buffer.

Return Value

In general, if no error occurs, program the function to return S_OK.

Program the function to return an HRESULT error code if the function fails. If the sample framework receives a failure HRESULT code, it will shut down the application.

Remarks

This callback function is the appropriate location for the application to create default pool resources, in D3DPOOL_DEFAULT memory, since these resources need to be reloaded whenever the device is reset. Resources created in this callback function should be deleted in the LPDXUTCALLBACKDEVICELOST callback function.

Prototype Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Device Events, DXUTSetCallbackDeviceReset, DXUTSetCallbackDeviceLost, LPDXUTCALLBACKDEVICELOST, Lost Devices


LPDXUTCALLBACKFRAMEMOVE Prototype

Application-defined callback function that allows for updating the scene. This function is called by the sample framework once each frame, before the application renders the scene.

Syntax

typedef VOID (CALLBACK *LPDXUTCALLBACKFRAMEMOVE)(

    IDirect3DDevice9 *pd3dDevice,
    DOUBLE fTime,
    FLOAT fElapsedTime
);

Parameters

pd3dDevice
[in] IDirect3DDevice9 device used for rendering.
fTime
[in] Time elapsed since the application started, in seconds.
fElapsedTime
[in] Time elapsed since the last frame, in seconds.

Return Value

No return value.

Remarks

This callback function is the appropriate location for the application to handle updates to the scene. This function is not intended to contain actual rendering calls, which should instead be placed in the LPDXUTCALLBACKFRAMERENDER callback function.

This callback function will be called once per frame, but the LPDXUTCALLBACKFRAMERENDER callback function will be called whenever the scene needs to be rendered, which might be more than once per frame.

Prototype Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Frame Events, DXUTSetCallbackFrameMove, DXUTSetCallbackFrameRender, LPDXUTCALLBACKFRAMERENDER


LPDXUTCALLBACKFRAMERENDER Prototype

Application-defined callback function that allows for updating the scene. This function is called by the sample framework at the end of every frame, and whenever the application needs to paint the scene.

Syntax

typedef VOID (CALLBACK *LPDXUTCALLBACKFRAMERENDER)(

    IDirect3DDevice9 *pd3dDevice,
    DOUBLE fTime,
    FLOAT fElapsedTime
);

Parameters

pd3dDevice
[in] IDirect3DDevice9 device used for rendering.
fTime
[in] Time elapsed since the application started, in seconds.
fElapsedTime
[in] Time elapsed since the last frame, in seconds.

Return Value

No return value.

Remarks

This callback function is the appropriate location for the application to render the current scene. The framework calls this function whenever the scene needs to be rendered or painted, but not if rendering is paused.

The framework will call this function after the LPDXUTCALLBACKFRAMEMOVE callback function.

Prototype Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Frame Events, DXUTSetCallbackFrameRender, DXUTSetCallbackFrameMove, LPDXUTCALLBACKFRAMEMOVE


LPDXUTCALLBACKISDEVICEACCEPTABLE Prototype

Application-defined callback function, called by the sample framework to build an enumerated list of all possible devices. The framework then selects the best device for creation among this list. This callback function allows the application to prevent unwanted devices from being added to the list.

Syntax

typedef bool (CALLBACK *LPDXUTCALLBACKISDEVICEACCEPTABLE)(

    D3DCAPS9 *pCaps,
    D3DFORMAT AdapterFormat,
    D3DFORMAT BackBufferFormat,
    bool bWindowed
);

Parameters

pCaps
[in] D3DCAPS9 structure of the device.
AdapterFormat
[in] Adapter surface format. See D3DFORMAT.
BackBufferFormat
[in] Back buffer format. See D3DPRESENT_PARAMETERS.BackBufferFormat.
bWindowed
[in] Indicates windowed mode. TRUE if the application runs windowed; FALSE if the application runs full-screen. See D3DPRESENT_PARAMETERS.Windowed.

Return Value

Program the application to return TRUE if the device settings are acceptable. If not, the application should return FALSE.

Remarks

This function's parameters describe a set of unique valid device settings that could be used to create a device. The application can examine and reject this set if desired.

All possible unique valid combinations of the following device settings are sent to this callback function:

  • DeviceType member of pCaps.
  • AdapterOrdinal member of pCaps.
  • AdapterFormat
  • BackBufferFormat
  • bWindowed

After the application rejects the unwanted device settings combinations, the sample framework picks the best of the remaining combinations and uses that best combination to create the device. Before creating the device, the framework calls LPDXUTCALLBACKMODIFYDEVICESETTINGS to allow the application to change any of the device creation settings.

Prototype Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Choosing the Best Device Settings, Controlling the Device Selection Dialog


LPDXUTCALLBACKKEYBOARD Prototype

Application-defined keyboard event callback function, called by the sample framework.

Syntax

typedef VOID (CALLBACK *LPDXUTCALLBACKKEYBOARD)(

    UINT nChar,
    bool bKeyDown,
    bool bAltDown
);

Parameters

nChar
[in] Keyboard hotkey behavior flag. The application can define behaviors that occur in response to different virtual-key codes. See Virtual-Key Codes World Wide Web link.
bKeyDown
[in] TRUE if the uMsg parameter of LPDXUTCALLBACKMSGPROC is either WM_KEYDOWN World Wide Web link or WM_SYSKEYDOWN World Wide Web link. See Remarks.
bAltDown
[in] ALT key behavior flag. The application can define a behavior that occurs in response to the ALT key being pressed. See Remarks.

Return Value

No return value.

Remarks

This callback function will be called when any one of the following keyboard events occurs:

  • WM_KEYDOWN World Wide Web link
  • WM_KEYUP World Wide Web link
  • WM_SYSKEYDOWN World Wide Web link
  • WM_SYSKEYUP World Wide Web link

This callback mechanism is provided to simplify handling keyboard messages through the window's message pump, but the application may still handle keyboard messages directly through the Microsoft Windows WindowProc World Wide Web link callback function.

Prototype Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Message Events, DXUTSetCallbackKeyboard, DXUTSetCallbackMouse, DXUTSetCallbackMsgProc, LPDXUTCALLBACKMSGPROC, LPDXUTCALLBACKMOUSE, WindowProc World Wide Web link


LPDXUTCALLBACKMODIFYDEVICESETTINGS Prototype

Application-defined callback function, called by the sample framework to allow changes in device settings before the device is created with DXUTCreateDevice.

Syntax

typedef VOID (CALLBACK *LPDXUTCALLBACKMODIFYDEVICESETTINGS)(

    DXUTDeviceSettings *pDeviceSettings,
    const D3DCAPS9 *pCaps
);

Parameters

pDeviceSettings
[in] Pointer to a DXUTDeviceSettings structure that contains the settings for the new device.
pCaps
[in] D3DCAPS9 structure that describes hardware capabilities.

Return Value

No return value.

Remarks

Anything in pDeviceSettings can be changed by the application.

Warning The sample framework will not prevent the failure of device creation caused by changes to device settings.

Prototype Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Modifying Available Device Settings, DXUTCreateDevice


LPDXUTCALLBACKMOUSE Prototype

Application-defined mouse event callback function, called by the sample framework when it receives mouse events.

Syntax

typedef VOID (CALLBACK *LPDXUTCALLBACKMOUSE)(

    bool bLeftButtonDown,
    bool bRightButtonDown,
    bool bMiddleButtonDown,
    bool bSideButton1Down,
    bool bSideButton2Down,
    INT nMouseWheelDelta,
    INT xPos,
    INT yPos
);

Parameters

bLeftButtonDown
[in] The left mouse button is down.
bRightButtonDown
[in] The right mouse button is down.
bMiddleButtonDown
[in] The middle mouse button is down.
bSideButton1Down
[in] Microsoft Windows 2000/Windows XP: The first X button is down.
bSideButton2Down
[in] Windows 2000/Windows XP: The second X button is down.
nMouseWheelDelta
[in] The distance and direction the mouse wheel has rolled, expressed in multiples or divisions of WHEEL_DELTA, which is 120. A positive value indicates that the wheel was rotated forward, away from the user; a negative value indicates that the wheel was rotated backward, toward the user.
xPos
[in] x-coordinate of the pointer, relative to the upper-left corner of the client area.
yPos
[in] y-coordinate of the pointer, relative to the upper-left corner of the client area.

Return Value

No return value.

Remarks

This callback function will be called when any one of the following mouse events occurs:

  • WM_LBUTTONDOWN World Wide Web link
  • WM_LBUTTONDBLCLK World Wide Web link
  • WM_LBUTTONUP World Wide Web link
  • WM_MBUTTONDBLCLK World Wide Web link
  • WM_MBUTTONDOWN World Wide Web link
  • WM_MBUTTONUP World Wide Web link
  • WM_MOUSEWHEEL World Wide Web link
  • WM_RBUTTONDBLCLK World Wide Web link
  • WM_RBUTTONDOWN World Wide Web link
  • WM_RBUTTONUP World Wide Web link
  • WM_XBUTTONDOWN World Wide Web link
  • WM_XBUTTONDBLCLK World Wide Web link
  • WM_XBUTTONUP World Wide Web link

This callback mechanism is provided to simplify handling mouse messages through the window's message pump, but the application may still handle mouse messages directly through the Windows WindowProc World Wide Web link callback function.

Prototype Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Message Events, DXUTSetCallbackMouse, DXUTSetCallbackKeyboard, DXUTSetCallbackMsgProc, LPDXUTCALLBACKMSGPROC, LPDXUTCALLBACKKEYBOARD, WindowProc World Wide Web link


LPDXUTCALLBACKMSGPROC Prototype

Application-defined function that processes messages from the sample framework message pump.

Syntax

typedef LRESULT (CALLBACK *LPDXUTCALLBACKMSGPROC)(

    HWND hWnd,
    UINT uMsg,
    WPARAM wParam,
    LPARAM lParam,
    bool *pbNoFurtherProcessing
);

Parameters

hWnd
[in] Handle to the window.
uMsg
[in] Specifies the message.
wParam
[in] Specifies additional message information. The contents of this parameter depend on the value of the uMsg parameter.
lParam
[in] Specifies additional message information. The contents of this parameter depend on the value of the uMsg parameter.
pbNoFurtherProcessing
[out] If TRUE, prevents the sample framework from handling the message.

Return Value

Returns zero if the function has processed window messages successfully; otherwise, returns a nonzero value.

Remarks

With the use of the pbNoFurtherProcessing parameter, the application can control the framework's level of involvement in processing window messages. If the application sets pbNoFurtherProcessing to TRUE in the call to LPDXUTCALLBACKMSGPROC, the framework will not process the message and will immediately return with the value returned by LPDXUTCALLBACKMSGPROC. If the application sets pbNoFurtherProcessing to FALSE, the framework will handle window management events.

This function and its parameters are used similarly to the Microsoft Windows WindowProc World Wide Web link function.

Prototype Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

Creating a Window, Message Events, DXUTSetCallbackMsgProc, DXUTSetCallbackKeyboard, DXUTSetCallbackMouse, LPDXUTCALLBACKKEYBOARD, LPDXUTCALLBACKMOUSE, DXUTStaticWndProc, WindowProc World Wide Web link


LPDXUTCALLBACKTIMER Prototype

A timer to be called at specified time intervals by the sample framework.

Syntax

typedef VOID (CALLBACK *LPDXUTCALLBACKTIMER)(

    UINT idEvent
);

Parameters

idEvent
[in] Specifies a nonzero timer event identifier (ID). Indicates which timer generated the event, allowing the application to use a single callback function for multiple timers.

Return Value

No return value.

Remarks

The framework will call this function at the start of the frame, before calling LPDXUTCALLBACKFRAMEMOVE or LPDXUTCALLBACKFRAMERENDER.

In general, the framework timer is more accurate than the Microsoft Windows WM_TIMER World Wide Web link system timer, since the framework uses QueryPerformanceCounter World Wide Web link.

Prototype Information

Header | dxut.h
Import library | None
Minimum operating systems | Windows 98

See Also

DXUTSetTimer, DXUTKillTimer


Structures
Microsoft DirectX 9.0 SDK Update (October 2004)

Structures

The Microsoft Direct3D sample framework supplies the following structures:

Structures

  • DXUTDeviceSettings
  • DXUTMatchOptions


DXUTDeviceSettings Structure

Describes the settings needed to create a Microsoft Direct3D device.

Syntax

struct DXUTDeviceSettings
{
    UINT AdapterOrdinal;
    D3DDEVTYPE DeviceType;
    D3DFORMAT AdapterFormat;
    DWORD BehaviorFlags;
    D3DPRESENT_PARAMETERS pp;
};

Members

AdapterOrdinal
Ordinal number that denotes the display adapter.
DeviceType
Enumerated type of the device. See D3DDEVTYPE.
AdapterFormat
Adapter surface format. See D3DFORMAT.
BehaviorFlags
Behavior flags. This member can be a combination of one or more of the D3DCREATE values.
pp
Presentation parameters structure. See D3DPRESENT_PARAMETERS.

Structure Information

Header | dxut.h
Minimum operating systems | Windows 98

See Also

Modifying Available Device Settings


DXUTMatchOptions Structure

Describes match options for finding valid device settings in DXUTFindValidDeviceSettings. Each member of this structure corresponds to a setting described by the DXUTDeviceSettings structure.

Default values are used when a member is set to DXUTMT_IGNORE_INPUT. See Remarks.

Syntax

struct DXUTMatchOptions
{
    DXUT_MATCH_TYPE eAdapterOrdinal;
    DXUT_MATCH_TYPE eDeviceType;
    DXUT_MATCH_TYPE eWindowed;
    DXUT_MATCH_TYPE eAdapterFormat;
    DXUT_MATCH_TYPE eVertexProcessing;
    DXUT_MATCH_TYPE eResolution;
    DXUT_MATCH_TYPE eBackBufferFormat;
    DXUT_MATCH_TYPE eBackBufferCount;
    DXUT_MATCH_TYPE eMultiSample;
    DXUT_MATCH_TYPE eSwapEffect;
    DXUT_MATCH_TYPE eDepthFormat;
    DXUT_MATCH_TYPE eStencilFormat;
    DXUT_MATCH_TYPE ePresentFlags;
    DXUT_MATCH_TYPE eRefreshRate;
    DXUT_MATCH_TYPE ePresentInterval;
};

Members

eAdapterOrdinal
Match type for the display adapter ordinal. If set to DXUTMT_IGNORE_INPUT, then the default value is D3DADAPTER_DEFAULT.
eDeviceType
Match type for the enumerated type of the device. See D3DDEVTYPE. If set to DXUTMT_IGNORE_INPUT, then the default value is D3DDEVTYPE_HAL.
eWindowed
Match type for the windowed or full-screen mode. See D3DPRESENT_PARAMETERS.Windowed. If set to DXUTMT_IGNORE_INPUT, then the default value is windowed mode (TRUE).
eAdapterFormat
Match type for the adapter surface format. See D3DFORMAT. If set to DXUTMT_IGNORE_INPUT, then the default value is the desktop display mode, or D3DFMT_X8R8G8B8 if the desktop display mode is less than 32 bits.
eVertexProcessing
Match type for the vertex processing flags D3DCREATE_HARDWARE_VERTEXPROCESSING, D3DCREATE_MIXED_VERTEXPROCESSING, or D3DCREATE_SOFTWARE_VERTEXPROCESSING. See D3DCREATE. If set to DXUTMT_IGNORE_INPUT, then the default value is D3DCREATE_HARDWARE_VERTEXPROCESSING.
eResolution
Match type for the display mode resolution. See D3DDISPLAYMODE. If set to DXUTMT_IGNORE_INPUT, then the default value is 640 x 480 pixels for windowed mode, or the desktop resolution for full-screen mode.
eBackBufferFormat
Match type for the back buffer format. See D3DPRESENT_PARAMETERS.BackBufferFormat. If set to DXUTMT_IGNORE_INPUT, then the default value is to match the adapter format.
eBackBufferCount
Match type for the number of back buffers. See D3DPRESENT_PARAMETERS.BackBufferCount. If set to DXUTMT_IGNORE_INPUT, then the default value is 2 for triple buffering.
eMultiSample
Match type for the quality level. See D3DPRESENT_PARAMETERS.MultiSampleQuality. If set to DXUTMT_IGNORE_INPUT, then the default value is to disable multisampling (MultiSampleQuality = 0).
eSwapEffect
Match type for the swap effect. See D3DPRESENT_PARAMETERS.SwapEffect. If set to DXUTMT_IGNORE_INPUT, then the default value is D3DSWAPEFFECT_DISCARD.
eDepthFormat
Match type for the depth format of the automatic depth-stencil surface that the device will create. See D3DPRESENT_PARAMETERS.AutoDepthStencilFormat. If both eDepthFormat and eStencilFormat are set to DXUTMT_IGNORE_INPUT, then the default value is D3DFMT_D16 if the backbuffer format is 16 bits or less, or D3DFMT_D32 otherwise.
eStencilFormat
Match type for the stencil format of the automatic depth-stencil surface that the device will create. See D3DPRESENT_PARAMETERS.AutoDepthStencilFormat. If both eDepthFormat and eStencilFormat are set to DXUTMT_IGNORE_INPUT, then the default value is D3DFMT_D16 if the backbuffer format is 16 bits or less, or D3DFMT_D32 otherwise.
ePresentFlags
Match type for the presentation parameters flags. See D3DPRESENT_PARAMETERS.Flags. If set to DXUTMT_IGNORE_INPUT, then the default value is D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL.
eRefreshRate
Match type for the rate at which the display adapter refreshes the screen. See D3DPRESENT_PARAMETERS.FullScreen_RefreshRateInHz. If set to DXUTMT_IGNORE_INPUT, then the default value is 0, indicating windowed mode.
ePresentInterval
Match type for the presentation interval. See D3DPRESENT_PARAMETERS.PresentationInterval. If set to DXUTMT_IGNORE_INPUT, then the default value is D3DPRESENT_INTERVAL_IMMEDIATE for windowed mode, or D3DPRESENT_INTERVAL_DEFAULT for full-screen mode.

Remarks

For each member of this structure, match options are specified using the constant values of the DXUT_MATCH_TYPE enumeration, as in the following code example.

matchOptions.eResolution = DXUTMT_CLOSEST_TO_INPUT;

To use default device settings instead, use the DXUTMT_IGNORE_INPUT flag as follows:

matchOptions.eResolution = DXUTMT_IGNORE_INPUT;

Structure Information

Header | dxut.h
Minimum operating systems | Windows 98

See Also

Creating a Device, Selecting the Best Available Device, DXUT_MATCH_TYPE, DXUTFindValidDeviceSettings, DXUTDeviceSettings


Enumerations
Microsoft DirectX 9.0 SDK Update (October 2004)

Enumerations

The Microsoft Direct3D sample framework supplies the following enumerated type:

Enumerations

  • DXUT_MATCH_TYPE


DXUT_MATCH_TYPE Enumerated Type

Describes how to match input device settings when creating a new device with a function.

Syntax

typedef enum _DXUT_MATCH_TYPE {
    DXUTMT_IGNORE_INPUT = 0,
    DXUTMT_PRESERVE_INPUT,
    DXUTMT_CLOSEST_TO_INPUT
} DXUT_MATCH_TYPE;

Constants

DXUTMT_IGNORE_INPUT

Ignore the device setting input, and return a device setting as close as possible to a default device setting.

DXUTMT_PRESERVE_INPUT

Return without changing the device setting that was given as input to the function. However, the DXUTFindValidDeviceSettings function will fail if no valid device is found.

DXUTMT_CLOSEST_TO_INPUT

Return a device setting as close as possible to the device setting that was given as input to the function.

Enumerated Type Information

Header | dxut.h
Minimum operating systems | Windows 98

See Also

DXUTMatchOptions, DXUTFindValidDeviceSettings, DXUTCreateDeviceFromSettings


Constants
Microsoft DirectX 9.0 SDK Update (October 2004)

Constants

The Microsoft Direct3D sample framework supplies the following constant values:

Constants

  • DXUTERR


DXUTERR
Microsoft DirectX 9.0 SDK Update (October 2004)

DXUTERR

The following table lists the values that can be returned by functions in the Microsoft Direct3D sample framework.

#define | Description
DXUTERR_CREATINGDEVICE | An error occurred when attempting to create an IDirect3DDevice9 device.
DXUTERR_CREATINGDEVICEOBJECTS | An error occurred in the device creation callback function.
DXUTERR_INCORRECTVERSION | The incorrect version of Direct3D or D3DX is installed.
DXUTERR_MEDIANOTFOUND | The Microsoft DirectX software development kit (SDK) media file could not be found.
DXUTERR_NOCOMPATIBLEDEVICES | No IDirect3DDevice9 device could be found with the specified device settings.
DXUTERR_NODIRECT3D | No IDirect3D9 object could be found.
DXUTERR_NONZEROREFCOUNT | The IDirect3DDevice9 device has a non-zero reference count, meaning that some objects were not released.
DXUTERR_RESETTINGDEVICE | An error occurred when attempting to reset an IDirect3DDevice9 device.
DXUTERR_RESETTINGDEVICEOBJECTS | An error occurred in the device creation callback function.

Constant Information

Header | dxut.h
Minimum operating system | Windows 98


X File Reference
Microsoft DirectX 9.0 SDK Update (October 2004)

X File Reference

This section contains reference information for the application programming interface (API) elements used to work with Microsoft DirectX .x files. These topics are new with the DirectX 9.0 SDK Update (Summer 2004).

  • Interfaces
  • Functions
  • Structures
  • Constants

Templates are described in X File Format Reference.

Interfaces and functions in the Dxfile.h header are available to support legacy applications. See X File Reference (Legacy).


Interfaces
Microsoft DirectX 9.0 SDK Update (October 2004)

Interfaces

This section contains reference information for the Component Object Model (COM) interfaces used to read to and write from .x files.

Interfaces

  • ID3DXFile
  • ID3DXFileData
  • ID3DXFileEnumObject
  • ID3DXFileSaveData
  • ID3DXFileSaveObject


ID3DXFile Interface

Applications use the methods of the ID3DXFile interface to create instances of the ID3DXFileEnumObject and ID3DXFileSaveObject interfaces, and to register templates.

ID3DXFile Members

CreateEnumObject | Creates an enumerator object that will read a .x file.
CreateSaveObject | Creates a save object that will be used to save data to a .x file.
RegisterEnumTemplates | Registers custom templates, given an ID3DXFileEnumObject enumeration object.
RegisterTemplates | Registers custom templates.

Remarks

An ID3DXFile object also contains a local template store. This local storage may be added to only with the ID3DXFile::RegisterEnumTemplates and ID3DXFile::RegisterTemplates methods.

ID3DXFileEnumObject and ID3DXFileSaveObject objects created with ID3DXFile::CreateEnumObject and ID3DXFile::CreateSaveObject also utilize the template store of the parent ID3DXFile object.

The ID3DXFile interface is obtained by calling the D3DXFileCreate function.

The globally unique identifier (GUID) for the ID3DXFile interface is IID_ID3DXFile.

The LPD3DXFILE type is defined as a pointer to the ID3DXFile interface.

typedef interface ID3DXFile *LPD3DXFILE;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9xof.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXFile::CreateEnumObject Method

Creates an enumerator object that will read a .x file.

Syntax

HRESULT CreateEnumObject(

    LPCVOID pvSource,
    D3DXF_FILELOADOPTIONS loadflags,
    ID3DXFileEnumObject **ppEnumObj
);

Parameters

pvSource
[out] Pointer to data whose contents depend on the value of loadflags.
loadflags
[in] Value that specifies the source of the data. This value can be one of the D3DXF_FILELOADOPTIONS flags.
ppEnumObj
[out] Address of a pointer to an ID3DXFileEnumObject interface, representing the created enumerator object.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DXFERR_BADVALUE | A variable is outside its expected range; typically returned when an object pointer is invalid.
D3DXFERR_PARSEERROR | Data stream could not be parsed.

Remarks

After using this method, use one of the ID3DXFileEnumObject methods to retrieve a data object.

See Also

ID3DXFileEnumObject


ID3DXFile::CreateSaveObject Method

Creates a save object that will be used to save data to a .x file.

Syntax

HRESULT CreateSaveObject(

    LPCVOID pData,
    D3DXF_FILESAVEOPTIONS flags,
    D3DXF_FILEFORMAT dwFileFormat,
    ID3DXFileSaveObject **ppSaveObj
);

Parameters

pData
[in] Pointer to the name of the file to use for saving data.
flags
[in] Value that specifies the name of the file to which data is to be saved. This value can be one of the D3DXF_FILESAVEOPTIONS flags.
dwFileFormat
[in] Indicates the format to use when saving the .x file. This value can be one of the D3DXF_FILEFORMAT flags. For more information, see Remarks.
ppSaveObj
[out] Address of a pointer to an ID3DXFileSaveObject interface, representing the created save object.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DXFERR_BADVALUE | A variable is outside its expected range; typically returned when an object pointer is invalid.
D3DXFERR_PARSEERROR | Data stream could not be parsed.

Remarks

After using this method, use methods of the ID3DXFileSaveObject interface to create data objects and to save templates or data.

For the saved file format dwFileFormat, one of the binary, legacy binary, or text flags in D3DXF_FILEFORMAT must be specified. The file can be compressed by using the optional D3DXF_FILEFORMAT_COMPRESSED flag.

The file format values can be combined in a logical OR to create compressed text or compressed binary files. If you indicate that the file format should be text and compressed, the file will be written out first as text and then compressed. However, compressed text files are not as efficient as binary text files; in most cases, therefore, you will want to indicate binary and compressed.

See Also

ID3DXFileSaveObject


ID3DXFile::RegisterEnumTemplates Method

Registers custom templates, given an ID3DXFileEnumObject enumeration object.

Syntax

HRESULT RegisterEnumTemplates(

    ID3DXFileEnumObject *pEnum
);

Parameters

pEnum
[in] Pointer to an ID3DXFileEnumObject enumeration object that contains templates.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned:

D3DXFERR_BADVALUE A variable is outside its expected range; typically returned when an object pointer is invalid.

Remarks

When this method is called, it copies templates stored with the ID3DXFileEnumObject, representing the file, to the local template store of the ID3DXFile object.

If an ID3DXFileEnumObject pointer is not available, call the ID3DXFile::RegisterTemplates method instead.

See Also

ID3DXFile::RegisterTemplates


ID3DXFile::RegisterTemplates Method

Registers custom templates.

Syntax

HRESULT RegisterTemplates(

    LPCVOID pvData,
    SIZE_T cbSize
);

Parameters

pvData
[in] Pointer to a buffer consisting of a .x file in text or binary format that contains templates.
cbSize
[in] Size of the buffer pointed to by pvData, in bytes.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DXFERR_BADVALUE | A variable is outside its expected range; typically returned when an object pointer is invalid.
D3DXFERR_PARSEERROR | Data stream could not be parsed.

Remarks

The following code fragment provides an example call to RegisterTemplates and example contents for the buffer to which pvData points.

#define XSKINEXP_TEMPLATES \
    "xof 0303txt 0032\
    template XSkinMeshHeader \
    { \
        <3CF169CE-FF7C-44ab-93C0-F78F62D172E2> \
        WORD nMaxSkinWeightsPerVertex; \
        WORD nMaxSkinWeightsPerFace; \
        WORD nBones; \
    } \
    template VertexDuplicationIndices \
    { \
        <B8D65549-D7C9-4995-89CF-53A9A8B031E3> \
        DWORD nIndices; \
        DWORD nOriginalVertices; \
        array DWORD indices[nIndices]; \
    } \
    template SkinWeights \
    { \
        <6F0D123B-BAD2-4167-A0D0-80224F25FABB> \
        STRING transformNodeName;\
        DWORD nWeights; \
        array DWORD vertexIndices[nWeights]; \
        array float weights[nWeights]; \
        Matrix4x4 matrixOffset; \
    }"
.
.
.

LPD3DXFILE pD3DXFile = NULL;

if ( FAILED
        (hr = pD3DXFile->RegisterTemplates(
            (LPVOID)XSKINEXP_TEMPLATES,
            sizeof( XSKINEXP_TEMPLATES ) - 1 ) ) )
    goto End;

All templates must specify a name and a universally unique identifier (UUID).

This method calls the ID3DXFile::RegisterEnumTemplates method, obtaining an ID3DXFileEnumObject interface pointer by calling ID3DXFile::CreateEnumObject with pvData as the first parameter.

See Also

ID3DXFile::RegisterEnumTemplates


ID3DXFileData Interface

Applications use the methods of the ID3DXFileData interface to build or to access the immediate hierarchy of the data object. Template restrictions determine the hierarchy.

ID3DXFileData Members

GetChild | Retrieves a child object in this file data object.
GetChildren | Retrieves the number of children in this file data object.
GetEnum | Retrieves the enumeration object in this file data object.
GetId | Retrieves the globally unique identifier (GUID) of this file data object.
GetName | Retrieves the name of this file data object.
GetType | Retrieves the template identifier (ID) in this file data object.
IsReference | Indicates whether this file data object is a reference object that points to another child data object.
Lock | Accesses the .x file data.
Unlock | Ends the lifespan of the ppData pointer returned by ID3DXFileData::Lock.

Remarks

Data types allowed by the template are called optional members. The optional members are not required, but an object might miss important information without them. These optional members are saved as children of the data object. A child can be another data object or a reference to an earlier data object.

The GUID for the ID3DXFileData interface is IID_ID3DXFileData.

The LPD3DXFILEDATA type is defined as a pointer to this interface.

typedef interface ID3DXFileData *LPD3DXFILEDATA;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9xof.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXFileData::GetChild Method

Retrieves a child object in this file data object.

Syntax

HRESULT GetChild(

    SIZE_T uiChild,
    ID3DXFileData **ppChild
);

Parameters

uiChild
[in] Identifier (ID) of the child object to retrieve.
ppChild
[in] Address of a pointer to receive the child object's interface pointer.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following values:

D3DXFERR_BADVALUE | A variable is outside its expected range; typically returned when an object pointer is invalid.
D3DXFERR_NOMOREOBJECTS | No more child objects are available.


ID3DXFileData::GetChildren Method

Retrieves the number of children in this file data object.

Syntax

HRESULT GetChildren(

    SIZE_T *puiChildren
);

Parameters

puiChildren
[in] Address of a pointer to receive the number of children in this file data object.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DXFERR_BADVALUE A variable is outside its expected range; typically returned when an object pointer is invalid.


ID3DXFileData::GetEnum Method

Retrieves the enumeration object in this file data object.

Syntax

HRESULT GetEnum(

    ID3DXFileEnumObject **ppObj
);

Parameters

ppObj
[in] Address of a pointer to receive the enumeration object in this file data object.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DXFERR_BADVALUE A variable is outside its expected range; typically returned when an object pointer is invalid.


ID3DXFileData::GetId Method

Retrieves the globally unique identifier (GUID) of this file data object.

Syntax

HRESULT GetId(

    LPGUID pId
);

Parameters

pId
[out] Pointer to a GUID to receive the identifier (ID) of this file data object. If the file data object has no ID, the returned parameter value will be GUID_NULL.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DXFERR_BADVALUE A variable is outside its expected range; typically returned when an object pointer is invalid.


ID3DXFileData::GetName Method

Retrieves the name of this file data object.

Syntax

HRESULT GetName(

    LPSTR szName,
    SIZE_T *puiSize
);

Parameters

szName
[in] Address of a pointer to receive the name of this file data object.

If this parameter is NULL, then puiSize will return the size of the string. If szName points to valid memory, the name of this file data object will be copied into szName up to the number of characters given by puiSize.
puiSize
[in, out] Pointer to the size of the string that represents the name of this file data object. This parameter can be NULL if szName provides a reference to the name.

This parameter will return the size of the string if szName is NULL.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DXFERR_BADVALUE A variable is outside its expected range; typically returned when an object pointer is invalid.

Remarks

For this method to succeed, either szName or puiSize must be non-NULL.


ID3DXFileData::GetType Method

Retrieves the template identifier (ID) in this file data object.

Syntax

HRESULT GetType(

    const GUID *pType
);

Parameters

pType
[in] Pointer to the globally unique identifier (GUID) representing the template in this file data object.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DXFERR_BADVALUE A variable is outside its expected range; typically returned when an object pointer is invalid.


ID3DXFileData::IsReference Method

Indicates whether this file data object is a reference object that points to another child data object.

Syntax

BOOL IsReference(VOID);

Return Value

Returns TRUE if the file data object is a reference object; returns FALSE otherwise.


ID3DXFileData::Lock Method

Accesses the .x file data.

Syntax

HRESULT Lock(

    SIZE_T *pSize,
    const VOID **ppData
);

Parameters

pSize
[in] Pointer to the size of the .x file data.
ppData
[in] Address of a pointer to receive the ID3DXFileData file data object's interface pointer. See Remarks.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned:

D3DXFERR_BADVALUE A variable is outside its expected range; typically returned when an object pointer is invalid.

Remarks

The ppData pointer is only valid during a ID3DXFileData::Lock ... ID3DXFileData::Unlock sequence. You can make multiple lock calls. However, you must ensure that the number of lock calls matches the number of unlock calls.

Because file data is not guaranteed to be aligned properly with byte boundaries, you should access ppData with UNALIGNED pointers.

Returned parameter values are not guaranteed to be valid due to possible file corruption; therefore, your code should verify the returned parameter values.


ID3DXFileData::Unlock Method

Ends the lifespan of the ppData pointer returned by ID3DXFileData::Lock.

Syntax

BOOL Unlock(VOID);

Return Value

The return value is S_OK.

Remarks

You must ensure that the number of ID3DXFileData::Lock calls matches the number of ID3DXFileData::Unlock calls. After calling ID3DXFileData::Unlock, the ppData pointer returned by ID3DXFileData::Lock should no longer be used.


ID3DXFileEnumObject Interface

Applications use the methods of the ID3DXFileEnumObject interface to cycle through the child file data objects in the file and to retrieve a child object by its globally unique identifier (GUID) or by its name.

ID3DXFileEnumObject Members

GetChild | Retrieves a child object in this file data object.
GetChildren | Retrieves the number of child objects in this file data object.
GetDataObjectById | Retrieves the data object that has the specified GUID.
GetDataObjectByName | Retrieves the data object that has the specified name.
GetFile | Retrieves the ID3DXFile object.

Remarks

The GUID for the ID3DXFileEnumObject interface is IID_ID3DXFileEnumObject.

The LPD3DXFILEENUMOBJECT type is defined as a pointer to this interface.

typedef interface ID3DXFileEnumObject *LPD3DXFILEENUMOBJECT;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9xof.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXFileEnumObject::GetChild Method

Retrieves a child object in this file data object.

Syntax

HRESULT GetChild(

    SIZE_T id,
    ID3DXFileData **ppObj
);

Parameters

id
[in] Identifier (ID) of the child object to retrieve.
ppObj
[out] Address of a pointer to receive the child object's interface pointer.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DXFERR_BADVALUE | A variable is outside its expected range; typically returned when an object pointer is invalid.
D3DXFERR_NOMOREOBJECTS | No more child objects are available.


ID3DXFileEnumObject::GetChildren Method

Retrieves the number of child objects in this file data object.

Syntax

HRESULT GetChildren(

    SIZE_T *puiChildren
);

Parameters

puiChildren
[in] Address of a pointer to receive the number of child objects in this file data object.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DXFERR_BADVALUE A variable is outside its expected range; typically returned when an object pointer is invalid.


ID3DXFileEnumObject::GetDataObjectById Method

Retrieves the data object that has the specified globally unique identifier (GUID).

Syntax

HRESULT GetDataObjectById(

    REFGUID rguid,
    LPD3DXFILEDATA *ppDataObj
);

Parameters

rguid
[in] Reference to the requested GUID.
ppDataObj
[out] Address of a pointer to an ID3DXFileData interface, representing the returned file data object.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

DXFILEERR_BADVALUE | Parameter is invalid.
DXFILEERR_NOTFOUND | Object could not be found.

Remarks

Obtain the GUID rguid of the current file data object with the ID3DXFileData::GetId method.


ID3DXFileEnumObject::GetDataObjectByName Method

Retrieves the data object that has the specified name.

Syntax

HRESULT GetDataObjectByName(

    LPCSTR szName,
    ID3DXFileData **ppObj
);

Parameters

szName
[in] Pointer to the requested name.
ppObj
[out] Address of a pointer to an ID3DXFileData interface, representing the returned file data object.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

DXFILEERR_BADVALUE | Parameter is invalid.
DXFILEERR_NOTFOUND | Object could not be found.

Remarks

Obtain the name szName of the current file data object with the ID3DXFileData::GetName method.


ID3DXFileEnumObject::GetFile Method

Retrieves the ID3DXFile object.

Syntax

HRESULT GetFile(

    ID3DXFile **ppFile
);

Parameters

ppFile
[out] Address of a pointer to an ID3DXFile interface, representing the returned object.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DXFERR_BADVALUE A variable is outside its expected range; typically returned when an object pointer is invalid.


ID3DXFileSaveData Interface

Applications use the methods of the ID3DXFileSaveData interface to add data objects as children of a .x file data node.

ID3DXFileSaveData Members

AddDataObject | Adds a data object as a child of the ID3DXFileSaveData file data node.
AddDataReference | Adds a data reference as a child of this ID3DXFileSaveData file data node. The data reference points to a file data object.
GetId | Retrieves the globally unique identifier (GUID) of this ID3DXFileSaveData file data node.
GetName | Retrieves the name of this ID3DXFileSaveData file data node.
GetSave | Retrieves a pointer to this ID3DXFileSaveObject file data node.
GetType | Retrieves the template identifier (ID) of this file data node.

Remarks

The GUID for the ID3DXFileSaveObject interface is IID_ID3DXFileSaveObject.

The LPD3DXFILESAVEDATA type is defined as a pointer to this interface.

typedef interface ID3DXFileSaveData *LPD3DXFILESAVEDATA;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9xof.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXFileSaveData::AddDataObject Method

Adds a data object as a child of the ID3DXFileSaveData file data node.

Syntax

HRESULT AddDataObject(

    REFGUID rguidTemplate,
    LPCSTR szName,
    const GUID *pId,
    SIZE_T cbSize,
    LPCVOID pvData,
    ID3DXFileSaveData **ppObj
);

Parameters

rguidTemplate
[in] Globally unique identifier (GUID) representing the data object's template.
szName
[in] Pointer to the name of the data object to add. Specify NULL if the object does not have a name.
pId
[in] Pointer to a GUID representing the data object. The data object must have been registered with ID3DXFile::RegisterTemplates or ID3DXFile::RegisterEnumTemplates. Specify NULL if the object does not have a GUID.
cbSize
[in] Size of the data object, in bytes.
pvData
[in] Pointer to a buffer containing all required data in the data object.
ppObj
[in, retval] Address of a pointer to an ID3DXFileSaveData interface, representing the file data node to which the data object will be added.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DXFERR_BADOBJECT | Data could not be read from or written to an object.
D3DXFERR_BADVALUE | A variable is outside its expected range; typically returned when an object pointer is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.


ID3DXFileSaveData::AddDataReference Method

Adds a data reference as a child of this ID3DXFileSaveData file data node. The data reference points to a file data object.

Syntax

HRESULT AddDataReference(

    LPCSTR szName,
    const GUID *pId
);

Parameters

szName
[in] Pointer to the name of the data object to add by reference. Specify NULL if the data object does not have a name.
pId
[in] Pointer to a globally unique identifier (GUID) representing the data object to add by reference. If NULL, a reference will be added that points to the data object with the name given by szName.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DXFERR_BADOBJECT | Data could not be read from or written to an object.
D3DXFERR_BADVALUE | A variable is outside its expected range; typically returned when an object pointer is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

The file data object being referenced must have either a name or a GUID. The file data object must also derive from a different parent ID3DXFileSaveData object.


ID3DXFileSaveData::GetId Method

Retrieves the globally unique identifier (GUID) of this ID3DXFileSaveData file data node.

Syntax

HRESULT GetId(

    LPGUID pId
);

Parameters

pId
[out] Pointer to a GUID to receive the identifier (ID) of this file data node. If the object has no ID, the returned parameter value will be GUID_NULL.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DXFERR_BADVALUE A variable is outside its expected range; typically returned when an object pointer is invalid.


ID3DXFileSaveData::GetName Method

Retrieves the name of this ID3DXFileSaveData file data node.

Syntax

HRESULT GetName(

    LPSTR szName,
    SIZE_T *puiSize
);

Parameters

szName
[in] Address of a pointer to receive the name of this file data node.

If this parameter is NULL, then puiSize will return the size of the string. If szName points to valid memory, the name of this file data node will be copied into szName up to the number of characters given by puiSize.
puiSize
[in, out] Pointer to the size of the string that represents the name of this file data node. This parameter can be NULL if szName provides a reference to the name.

This parameter will return the size of the string if szName is NULL.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DXFERR_BADVALUE A variable is outside its expected range; typically returned when an object pointer is invalid.

Remarks

For this method to succeed, either szName or puiSize must be non-NULL.


ID3DXFileSaveData::GetSave Method

Retrieves a pointer to this ID3DXFileSaveObject file data node.

Syntax

HRESULT GetSave(

    ID3DXFileSaveObject **ppObj
);

Parameters

ppObj
[out] Address of a pointer to an ID3DXFileSaveObject interface representing this file data node.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the following value will be returned.

D3DXFERR_BADVALUE A variable is outside its expected range; typically returned when an object pointer is invalid.


ID3DXFileSaveData::GetType Method

Retrieves the template identifier (ID) of this file data node.

Syntax

HRESULT GetType(

    GUID *type
);

Parameters

type
[in] Pointer to the globally unique identifier (GUID) representing the template in this file data node.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DXFERR_BADOBJECT | Data could not be read from or written to an object.
D3DXFERR_BADVALUE | A variable is outside its expected range; typically returned when an object pointer is invalid.


ID3DXFileSaveObject Interface

Applications use the methods of the ID3DXFileSaveObject interface to write a .x file to disk, and to add and save data objects and templates.

ID3DXFileSaveObject Members

AddDataObject | Adds a data object as a child of the ID3DXFileSaveData object.
GetFile | Gets the ID3DXFile interface of the object that created this ID3DXFileSaveObject object.
Save | Saves a data object and its children to a .x file on disk.

Remarks

Templates are not required in every file. For example, you could put all templates into a single .x file rather than duplicating them in every .x file.

The ID3DXFileSaveObject interface is obtained by calling the ID3DXFile::CreateSaveObject method.

The globally unique identifier (GUID) for the ID3DXFileSaveObject interface is IID_ID3DXFileSaveObject.

The LPD3DXFILESAVEOBJECT type is defined as a pointer to this interface.

typedef interface ID3DXFileSaveObject *LPD3DXFILESAVEOBJECT;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | d3dx9xof.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98


ID3DXFileSaveObject::AddDataObject Method

Adds a data object as a child of the ID3DXFileSaveData object.

Syntax

HRESULT AddDataObject(

    REFGUID rguidTemplate,
    LPCSTR szName,
    const GUID *pId,
    SIZE_T cbSize,
    LPCVOID pvData,
    ID3DXFileSaveData **ppObj
);

Parameters

rguidTemplate
[in] Globally unique identifier (GUID) representing the data object's template.
szName
[in] Pointer to the name of the data object. Specify NULL if the object does not have a name.
pId
[in] Pointer to a GUID representing the data object. Specify NULL if the object does not have a GUID.
cbSize
[in] Size of the data object, in bytes.
pvData
[in] Pointer to a buffer containing all required data in the data object.
ppObj
[in, retval] Address of a pointer to an ID3DXFileSaveData interface, representing the file data node to which the data object will be added.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DXFERR_BADOBJECT | Data could not be read from or written to an object.
DXFILEERR_BADVALUE | Parameter is invalid.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

If a data reference object will reference the data object, either the szName or pId parameter must be non-NULL.

Save the created data to disk by using the ID3DXFileSaveObject::Save method.

See Also

ID3DXFileSaveObject::Save


ID3DXFileSaveObject::GetFile Method

Gets the ID3DXFile interface of the object that created this ID3DXFileSaveObject object.

Syntax

HRESULT GetFile(

    ID3DXFile ppFile
);

Parameters

ppFile
[in] Address of a pointer to an ID3DXFile object.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following:

D3DXFERR_BADVALUE | A variable is outside its expected range; typically returned when an object pointer is invalid.
E_NOINTERFACE | No object interface is available.
E_POINTER | An invalid pointer, usually NULL, was passed as a parameter.


ID3DXFileSaveObject::Save Method

Saves a data object and its children to a .x file on disk.

Syntax

HRESULT Save(VOID);

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be the following:

D3DXFERR_BADOBJECT Data could not be read from or written to an object.

Remarks

After this method succeeds, ID3DXFileSaveObject::AddDataObject, ID3DXFileSaveData::AddDataObject and ID3DXFileSaveData::AddDataReference can no longer be called until a new ID3DXFile object is created.


Functions
Microsoft DirectX 9.0 SDK Update (October 2004)

Functions

This section contains reference information for a function that you can use to work with .x files.

Functions

  • D3DXFileCreate


D3DXFileCreate Function

Creates an instance of an ID3DXFile object.

Syntax

STDAPI D3DXFileCreate(

    ID3DXFile **lplpDirectXFile
);

Parameters

lplpDirectXFile
Address of a pointer to an ID3DXFile interface, representing the created .x file object.

Return Value

If the function succeeds, the return value is S_OK.

If the function fails, the return value can be one of the following values:

E_POINTER | An invalid pointer, usually NULL, was passed as a parameter.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

After using this function, use ID3DXFile::RegisterTemplates or ID3DXFile::RegisterEnumTemplates to register templates, ID3DXFile::CreateEnumObject to create an enumerator object, or ID3DXFile::CreateSaveObject to create a save object.

Function Information

Header | d3dx9xof.h
Import library | d3dx9.lib
Minimum operating systems | Windows 98

See Also

ID3DXFile::CreateEnumObject, ID3DXFile::CreateSaveObject, ID3DXFile::RegisterEnumTemplates, ID3DXFile::RegisterTemplates


Structures
Microsoft DirectX 9.0 SDK Update (October 2004)

Structures

This section contains information about the structures used with .x files.

Structures

  • D3DXF_FILELOADMEMORY
  • D3DXFILELOADRESOURCE
  • XFILECOMPRESSEDANIMATIONSET


D3DXF_FILELOADMEMORY Structure

Identifies memory data.

Syntax

typedef struct _D3DXF_FILELOADMEMORY {
    LPCVOID lpMemory;
    SIZE_T dSize;
} D3DXF_FILELOADMEMORY;

Members

lpMemory
Pointer to a block of memory to be loaded.
dSize
Size of the block of memory to be loaded, in bytes.

Remarks

This structure identifies data to be loaded from memory when an application uses the ID3DXFile::CreateEnumObject method and specifies the D3DXF_FILELOAD_FROMMEMORY flag.

Structure Information

Header | d3dx9xof.h
Minimum operating systems | Windows 98

See Also

ID3DXFile::CreateEnumObject, D3DXFILE


D3DXF_FILELOADRESOURCE Structure

Identifies resource data.

Syntax

typedef struct _D3DXF_FILELOADRESOURCE {
    HMODULE hModule;
    LPCSTR lpName;
    LPCSTR lpType;
} D3DXF_FILELOADRESOURCE;

Members

hModule
Handle of the module containing the resource to be loaded. If this member is NULL, the resource must be attached to the executable file that will use it.
lpName
Pointer to a string specifying the name of the resource to be loaded. For example, if the resource is a mesh, this member should specify the name of the mesh file.
lpType
Pointer to a string specifying the user-defined type identifying the resource.

Remarks

This structure identifies a resource to be loaded when an application uses the ID3DXFile::CreateEnumObject method and specifies the D3DXF_FILELOAD_FROMRESOURCE flag.

Structure Information

Header | d3dx9xof.h
Minimum operating systems | Windows 98

See Also

ID3DXFile::CreateEnumObject, D3DXFILE


XFILECOMPRESSEDANIMATIONSET Structure

Identifies compressed key frame animation data.

Syntax

typedef struct _XFILECOMPRESSEDANIMATIONSET {
    DWORD CompressedBlockSize;
    FLOAT TicksPerSec;
    DWORD PlaybackType;
    DWORD BufferLength;
} XFILECOMPRESSEDANIMATIONSET;

Members

CompressedBlockSize
Total size, in bytes, of the compressed data in the compressed key frame animation data buffer.
TicksPerSec
Number of animation key frame ticks that occur per second.
PlaybackType
Type of the animation set playback loop. See D3DXPLAYBACK_TYPE.
BufferLength
Minimum buffer size, in bytes, required to hold compressed key frame animation data. Value is equal to ( ( CompressedBlockSize + 3 ) / 4 ).

Structure Information

Header | d3dx9mesh.h
Minimum operating systems | Windows 98

See Also

ID3DXCompressedAnimationSet


Constants
Microsoft DirectX 9.0 SDK Update (October 2004)

Constants

This section contains information about the constants used with .x files.

Constants

  • D3DXFILE
  • Return Values


D3DXF
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DXF

These constant values are used to specify operations with .x file data.

D3DXF_FILEFORMAT

The following flags specify what file type to use when saving data. All but D3DXF_FILEFORMAT_COMPRESSED are mutually exclusive.

#define | Value | Description
D3DXF_FILEFORMAT_BINARY | 0 | Legacy-format binary file. See X File Reference (Legacy).
D3DXF_FILEFORMAT_COMPRESSED | 2 | Compressed file. May be used in combination with other D3DXF_FILEFORMAT_ flags. This flag is not sufficient to completely specify the saved file format.
D3DXF_FILEFORMAT_TEXT | 1 | Text file.

D3DXF_FILELOADOPTIONS

The following flags specify what file type to use when loading data. All flags are mutually exclusive.

#define | Value | Description
D3DXF_FILELOAD_FROMFILE | 0x00L | Load data from a file, with the file name specified with an LPCSTR.
D3DXF_FILELOAD_FROMMEMORY | 0x03L | Load data from memory.
D3DXF_FILELOAD_FROMRESOURCE | 0x02L | Load data from a resource.
D3DXF_FILELOAD_FROMWFILE | 0x01L | Load data from a file, with the file name specified with an LPWSTR.

D3DXF_FILESAVEOPTIONS

The following flags are used to specify the name of a file to which data is to be saved. All flags are mutually exclusive.

#define | Value | Description
D3DXF_FILESAVE_TOFILE | 0x00L | Save to the file with its name specified with an LPCSTR.
D3DXF_FILESAVE_TOWFILE | 0x01L | Save to the file with its name specified with an LPWSTR.

Constant Information

Header | d3dx9xof.h
Minimum operating system | Windows 98


D3DXFERR Return Values Enumerated Type

The methods used to work with Microsoft DirectX .x files can return the following values in addition to the standard Component Object Model (COM) return values.

Syntax

typedef enum {
    D3DXFERR_BADARRAYSIZE,
    D3DXFERR_BADCACHEFILE,
    D3DXFERR_BADDATAREFERENCE,
    D3DXFERR_BADFILE,
    D3DXFERR_BADFILEFLOATSIZE,
    D3DXFERR_BADFILETYPE,
    D3DXFERR_BADFILEVERSION,
    D3DXFERR_BADOBJECT,
    D3DXFERR_BADRESOURCE,
    D3DXFERR_BADTYPE,
    D3DXFERR_BADVALUE,
    D3DXFERR_FILENOTFOUND,
    D3DXFERR_NOMOREDATA,
    D3DXFERR_NOMOREOBJECTS,
    D3DXFERR_NOTDONEYET,
    D3DXFERR_NOTFOUND,
    D3DXFERR_PARSEERROR,
    D3DXFERR_RESOURCENOTFOUND
} D3DXFERR Return Values;

Constants

D3DXFERR_BADARRAYSIZE

An array exceeds the allowable size.

D3DXFERR_BADCACHEFILE

A cache file could not be read.

D3DXFERR_BADDATAREFERENCE

Template member data could not be retrieved.

D3DXFERR_BADFILE

A file read or write operation failed.

D3DXFERR_BADFILEFLOATSIZE

File is not the expected size.

D3DXFERR_BADFILETYPE

File has an invalid format.

D3DXFERR_BADFILEVERSION

File has an invalid format version.

D3DXFERR_BADOBJECT

Data could not be read from or written to an object.

D3DXFERR_BADRESOURCE

An operation on a resource failed.

D3DXFERR_BADTYPE

File did not match known template types.

D3DXFERR_BADVALUE

A variable is outside its expected range; typically returned when an object pointer is invalid.

D3DXFERR_FILENOTFOUND

A valid handle could not be found for the specified file.

D3DXFERR_NOMOREDATA

Pointer offset extended beyond the end of the buffer.

D3DXFERR_NOMOREOBJECTS

No more child objects are available.

D3DXFERR_NOTDONEYET

Data type did not match allowed types.

D3DXFERR_NOTFOUND

Object could not be found from the specified parameters.

D3DXFERR_PARSEERROR

Data stream could not be parsed.

D3DXFERR_RESOURCENOTFOUND

A valid handle could not be found for the specified resource.

Remarks

The .x file error facility code _FACD3DXF is used to generate error codes. For example:

#define _FACD3DXF           0x876
#define D3DXFERR_BADOBJECT  MAKE_HRESULT( 1, _FACD3DXF, 900 )

Enumerated Type Information

Header | d3dx9xof.h
Minimum operating systems | Windows 98


X File Reference (Legacy)
Microsoft DirectX 9.0 SDK Update (October 2004)

X File Reference (Legacy)

This section contains reference information for the application programming interface (API) elements for working with Microsoft DirectX .x files to support legacy applications.

  • Interfaces
  • Functions
  • Structures
  • DXFILE
  • Return Values

For information on .x file API elements that are new with the DirectX 9.0 SDK Update (Summer 2004), see X File Reference.


Interfaces
Microsoft DirectX 9.0 SDK Update (October 2004)

Interfaces

This section contains reference information for the Component Object Model (COM) interfaces used to read to and write from Microsoft DirectX .x files. Deprecated.

Interfaces

  • IDirectXFile
  • IDirectXFileBinary
  • IDirectXFileData
  • IDirectXFileDataReference
  • IDirectXFileEnumObject
  • IDirectXFileObject
  • IDirectXFileSaveObject

The following tables illustrate the relationship between the .x file interfaces.

Interface | Derives from | Derives from
 | IDirectXFile | IUnknown
IDirectXFileBinary | IDirectXFileObject | IUnknown
IDirectXFileData | IDirectXFileObject | IUnknown
IDirectXFileReference | IDirectXFileObject | IUnknown
 | IDirectXFileSaveObject | IUnknown


IDirectXFile Interface

Applications use the methods of the IDirectXFile interface to create instances of the IDirectXFileEnumObject and IDirectXFileSaveObject interfaces, and to register templates. Deprecated.

IDirectXFile Members

CreateEnumObject | Creates an enumerator object. Deprecated.
CreateSaveObject | Creates a save object. Deprecated.
RegisterTemplates | Registers custom templates. Deprecated.

Remarks

The globally unique identifier (GUID) for the IDirectXFile interface is IID_IDirectXFile.

The IDirectXFile interface is obtained by calling the DirectXFileCreate function.

The LPDIRECTXFILE type is defined as a pointer to this interface.

typedef interface IDirectXFile *LPDIRECTXFILE;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | dxfile.h
Import library | d3dxof.lib
Minimum operating systems | Windows 98


IDirectXFile::CreateEnumObject Method

Creates an enumerator object. Deprecated.

Syntax

HRESULT CreateEnumObject(

    LPVOID pvSource,
    DXFILELOADOPTIONS dwLoadOptions,
    LPDIRECTXFILEENUMOBJECT *ppEnumObj
);

Parameters

pvSource
[out] Pointer to data whose contents depend on the value of dwLoadOptions
dwLoadOptions
[in] Value that specifies the source of the data. This value can be one of the DXFILELOAD_xxx flags in DXFILE.
ppEnumObj
[out, retval] Address of a pointer to an IDirectXFileEnumObject interface, representing the created enumerator object.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC | Memory allocation failed.
DXFILEERR_BADFILEFLOATSIZE | Floating-point size is invalid.
DXFILEERR_BADFILETYPE | File is not a Microsoft DirectX (.x) file.
DXFILEERR_BADFILEVERSION | File version is not valid.
DXFILEERR_BADRESOURCE | Resource is invalid.
DXFILEERR_BADVALUE | Parameter is invalid.
DXFILEERR_FILENOTFOUND | File could not be found.
DXFILEERR_RESOURCENOTFOUND | Resource could not be found.
DXFILEERR_URLNOTFOUND | URL could not be found.

Remarks

After using this method, use one of the IDirectXFileEnumObject methods to retrieve a data object.

See Also

IDirectXFileEnumObject


IDirectXFile::CreateSaveObject Method

Creates a save object. Deprecated.

Syntax

HRESULT CreateSaveObject(

    LPCSTR szFileName,
    DXFILEFORMAT dwFileFormat,
    LPDIRECTXFILESAVEOBJECT* ppSaveObj
);

Parameters

szFileName
[in] Pointer to the name of the file to use for saving data.
dwFileFormat
[in] Indicates the format to use when saving the Microsoft DirectX file. This value can be one of the DXFILEFORMAT_xxx flags in DXFILE. For more information, see Remarks.
ppSaveObj
[out, retval] Address of a pointer to an IDirectXFileSaveObject interface, representing the created save object.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC | Memory allocation failed.
DXFILEERR_BADFILE | File is invalid.
DXFILEERR_BADVALUE | Parameter is invalid.

Remarks

After using this method, use methods of the IDirectXFileSaveObject interface to create data objects and to save templates or data.

The default value for the file format is DXFILEFORMAT_BINARY. The file format values can be combined in a logical OR to create compressed text or compressed binary files. If a file is specified as both binary (0) and text (1), it will be saved as a text file because the value will be indistinguishable from the text file format value (0 + 1 = 1). If you indicate that the file format should be text and compressed, the file will first be written out as text and then compressed. However, compressed text files are not as efficient as binary text files, so in most cases you will want to indicate binary and compressed. Setting a file to be compressed without specifying a format will result in a binary, compressed file.

See Also

IDirectXFileSaveObject


IDirectXFile::RegisterTemplates Method

Registers custom templates. Deprecated.

Syntax

HRESULT RegisterTemplates(

    LPVOID pvData,
    DWORD cbSize
);

Parameters

pvData
[in] Pointer to a buffer consisting of a Microsoft DirectX file in text or binary format that contains templates.
cbSize
[in] Size of the buffer pointed to by pvData, in bytes.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADFILEFLOATSIZE | Floating-point size is invalid.
DXFILEERR_BADFILETYPE | File is not a DirectX (.x) file.
DXFILEERR_BADFILEVERSION | File version is not valid.
DXFILEERR_BADVALUE | Parameter is invalid.
DXFILEERR_PARSEERROR | File could not be parsed.

Remarks

The following code fragment provides an example call to RegisterTemplates and example contents for the buffer to which pvData points.

TIDirectXFile * pDXFile;
char *szTemplates = "xof 0303txt 0032\
    template SimpleData { \
        <2b934580-9e9a-11cf-ab39-0020af71e433> \
        DWORD item1;DWORD item2;DWORD item3;} \
    template ArrayData { \
        <2b934581-9e9a-11cf-ab39-0020af71e433> \
        DWORD cItems; array DWORD aItem[2][cItems]; [...] } \
    template RestrictedData { \
        <2b934582-9e9a-11cf-ab39-0020af71e433> \
        DWORD item; [SimpleData]}";
hr = pDXFile->RegisterTemplates(szTemplates, strlen(szTemplates));

All templates must specify a name and a Universally Unique Identifier (UUID).


IDirectXFileBinary Interface

Applications use the methods of the IDirectXFileBinary interface to read and retrieve information about binary data. Deprecated.

IDirectXFileBinary Members

GetId | Retrieves a pointer to the globally unique identifier (GUID) that identifies a Microsoft DirectX file object. Deprecated.
GetMimeType | Retrieves the Multipurpose Internet Mail Extensions (MIME) type for the binary data. Deprecated.
GetName | Retrieves a pointer to a DirectX file object's name. Deprecated.
GetSize | Retrieves the size of the binary data. Deprecated.
Read | Reads the binary data. Deprecated.

Remarks

The GUID for the IDirectXFileBinary interface is IID_IDirectXFileBinary.

The LPDIRECTXFILEBINARY type is defined as a pointer to this interface.

typedef interface IDirectXFileBinary *LPDIRECTXFILEBINARY;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IDirectXFileObject
Header | dxfile.h
Import library | d3dxof.lib
Minimum operating systems | Windows 98


IDirectXFileBinary::GetMimeType Method

Retrieves the Multipurpose Internet Mail Extensions (MIME) type for the binary data. Deprecated.

Syntax

HRESULT GetMimeType(

    LPCSTR *pszMimeType
);

Parameters

pszMimeType
[out] Address of a pointer to receive the MIME type string.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be DXFILEERR_BADVALUE.

Remarks

When there is no MIME type specified in a Microsoft DirectX file for a binary object, the function will set pszMimeType to NULL.


IDirectXFileBinary::GetSize Method

Retrieves the size of the binary data. Deprecated.

Syntax

HRESULT GetSize(

    DWORD *pcbSize
);

Parameters

pcbSize
[out] Pointer to the returned size of the binary data, in bytes.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be DXFILEERR_BADVALUE.


IDirectXFileBinary::Read Method

Reads the binary data. Deprecated.

Syntax

HRESULT Read(

    LPVOID pvData,
    DWORD cbSize,
    LPDWORD pcbRead
);

Parameters

pvData
[out] Pointer to the buffer that receives the data that has been read.
cbSize
[in] Size of the buffer pointed to by pvData, in bytes.
pcbRead
[out] Pointer to the number of bytes actually read.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADVALUE | Parameter is invalid.
DXFILEERR_NOMOREDATA | No further data is available.


IDirectXFileData Interface

Applications use the methods of the IDirectXFileData interface to build or to access the immediate hierarchy of the data object. Template restrictions determine the hierarchy. Data types allowed by the template are called optional members. The optional members are not required, but an object might miss important information without them. These optional members are saved as children of the data object. The children can be another data object, a reference to an earlier data object, or a binary object. Deprecated.

IDirectXFileData Members

AddBinaryObject | Creates a binary object and adds it as a child object. Deprecated.
AddDataObject | Adds a data object as a child object. Deprecated.
AddDataReference | Creates and adds a data reference object as a child object. Deprecated.
GetData | Retrieves the data for one of the object's members or the data for all members. Deprecated.
GetId | Retrieves a pointer to the globally unique identifier (GUID) that identifies a Microsoft DirectX file object. Deprecated.
GetName | Retrieves a pointer to a DirectX file object's name. Deprecated.
GetNextObject | Retrieves the next child data object, data reference object, or binary object in the DirectX file. Deprecated.
GetType | Retrieves the GUID of the object's template. Deprecated.

Remarks

The GUID for the IDirectXFileData interface is IID_IDirectXFileData.

The LPDIRECTXFILEDATA type is defined as a pointer to this interface.

typedef interface IDirectXFileData *LPDIRECTXFILEDATA;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IDirectXFileObject
Header | dxfile.h
Import library | d3dxof.lib
Minimum operating systems | Windows 98


IDirectXFileData::AddBinaryObject Method

Creates a binary object and adds it as a child object. Deprecated.

Syntax

HRESULT AddBinaryObject(

    LPCSTR szName,
    const GUID *pguid,
    LPCSTR szMimeType,
    LPVOID pvData,
    DWORD cbSize
);

Parameters

szName
[in] Pointer to the name of the object. Specify NULL if the object does not need a name.
pguid
[in] Pointer to the globally unique identifier (GUID) representing the object. Specify NULL if the object does not need a GUID.
szMimeType
[in] Pointer to the object's MIME type.
pvData
[in] Pointer to the object's data.
cbSize
[in] Size of the buffer pointed to by pvData, in bytes.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC | Memory allocation failed.
DXFILEERR_BADVALUE | Parameter is invalid.

See Also

IDirectXFileBinary::GetMimeType


IDirectXFileData::AddDataObject Method

Adds a data object as a child object. Deprecated.

Syntax

HRESULT AddDataObject(

    LPDIRECTXFILEDATA pDataObj
);

Parameters

pDataObj
[in] Pointer to an IDirectXFileData interface, representing the file data object to add as a child object.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC | Memory allocation failed.
DXFILEERR_BADVALUE | Parameter is invalid.

Remarks

Use the IDirectXFileSaveObject::CreateDataObject method to create the IDirectXFileData object before calling this method.

See Also

IDirectXFileSaveObject::CreateDataObject


IDirectXFileData::AddDataReference Method

Creates and adds a data reference object as a child object. Deprecated.

Syntax

HRESULT AddDataReference(

    LPCSTR szRef,
    const GUID *pguidRef
);

Parameters

szRef
[in] Pointer to the name of the referenced data object. This parameter can be NULL if pguidRef provides a reference to the globally unique identifier (GUID).
pguidRef
[in] Pointer to the GUID representing the data. This parameter can be NULL if szRef provides a reference to the name.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC | Memory allocation failed.
DXFILEERR_BADVALUE | Parameter is invalid.

Remarks

For this method to succeed, either the szRef or pguidRef parameter must be non-NULL.


IDirectXFileData::GetData Method

Retrieves the data for one of the object's members or the data for all members. Deprecated.

Syntax

HRESULT GetData(

    LPCSTR szMember,
    DWORD *pcbSize,
    void **ppvData
);

Parameters

szMember
[in] Pointer to the name of the member for which to retrieve data. Specify NULL to retrieve all required members' data.
pcbSize
[out] Pointer to receive the ppvData buffer size, in bytes.
ppvData
[out] Address of a pointer to the buffer to receive the data associated with szMember. If szMember is NULL, ppvData is set to point to a buffer containing all required members' data in a contiguous block of memory.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADARRAYSIZE | Array size is invalid.
DXFILEERR_BADDATAREFERENCE | Data reference is invalid.
DXFILEERR_BADVALUE | Parameter is invalid.

Remarks

This method retrieves the data for required members of a data object but no data for optional (child) members. Use IDirectXFileData::GetNextObject to retrieve child objects.

See Also

IDirectXFileData::GetNextObject


IDirectXFileData::GetNextObject Method

Retrieves the next child data object, data reference object, or binary object in the Microsoft DirectX file. Deprecated.

Syntax

HRESULT GetNextObject(

    LPDIRECTXFILEOBJECT *ppChildObj
);

Parameters

ppChildObj
[out, retval] Address of a pointer to an IDirectXFileObject interface, representing the returned child object's file object interface.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADVALUE | Parameter is invalid.
DXFILEERR_NOMOREOBJECTS | All objects have been enumerated.

Remarks

To determine the type of object retrieved, use QueryInterface to query the retrieved object for support of IDirectXFileData, IDirectXFileDataReference, or IDirectXFileBinary interfaces. The interface supported indicates the type of object (data, data reference, or binary).

See Also

IDirectXFileBinary, IDirectXFileData, IDirectXFileDataReference


IDirectXFileData::GetType Method

Retrieves the globally unique identifier (GUID) of the object's template. Deprecated.

Syntax

HRESULT GetType(

    const GUID **ppguid
);

Parameters

ppguid
[out, retval] Address of a pointer to receive the GUID of the object's template.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be DXFILEERR_BADVALUE.


IDirectXFileDataReference Interface

Applications use the methods of the IDirectXFileDataReference interface to support data reference objects. A data reference object refers to a data object that is defined earlier in the file. This enables you to use the same object multiple times without repeating it in the file. Deprecated.

IDirectXFileDataReference Members

GetId | Retrieves a pointer to the globally unique identifier (GUID) that identifies a Microsoft DirectX file object. Deprecated.
GetName | Retrieves a pointer to a DirectX file object's name. Deprecated.
Resolve | Resolves data references. Deprecated.

Remarks

After you have determined that an object is a data reference object, use the IDirectXFileDataReference::Resolve method to retrieve the referenced object defined earlier in the file. For information about how to identify a data reference object, see the IDirectXFileData interface.

The GUID for the IDirectXFileDataReference interface is IID_IDirectXFileDataReference.

The LPDIRECTXFILEDATAREFERENCE type is defined as a pointer to this interface.

typedef interface IDirectXFileDataReference *LPDIRECTXFILEDATAREFERENCE;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IDirectXFileObject
Header | dxfile.h
Import library | d3dxof.lib
Minimum operating systems | Windows 98


IDirectXFileDataReference::Resolve Method

Resolves data references. Deprecated.

Syntax

HRESULT Resolve(

    LPDIRECTXFILEDATA *ppDataObj
);

Parameters

ppDataObj
[out, retval] Address of a pointer to an IDirectXFileData interface, representing the returned file data object.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADVALUE | Parameter is invalid.
DXFILEERR_NOTFOUND | Object could not be found.


IDirectXFileEnumObject Interface

Applications use the methods of the IDirectXFileEnumObject interface to cycle through the data objects in the file and to retrieve a data object by its globally unique identifier (GUID) or by its name. Deprecated.

IDirectXFileEnumObject Members

GetDataObjectById | Retrieves the data object that has the specified GUID. Deprecated.
GetDataObjectByName | Retrieves the data object that has the specified name. Deprecated.
GetNextDataObject | Retrieves the next top-level object in the Microsoft DirectX file. Deprecated.

Remarks

The GUID for the IDirectXFileEnumObject interface is IID_IDirectXFileEnumObject.

The LPDIRECTXFILEENUMOBJECT type is defined as a pointer to this interface.

typedef interface IDirectXFileEnumObject *LPDIRECTXFILEENUMOBJECT;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | dxfile.h
Import library | d3dxof.lib
Minimum operating systems | Windows 98


IDirectXFileEnumObject::GetDataObjectById Method

Retrieves the data object that has the specified globally unique identifier (GUID). Deprecated.

Syntax

HRESULT GetDataObjectById(

    REFGUID rguid,
    LPDIRECTXFILEDATA *ppDataObj
);

Parameters

rguid
[in] Reference to the requested GUID.
ppDataObj
[out] Address of a pointer to an IDirectXFileData interface, representing the returned file data object.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADVALUE | Parameter is invalid.
DXFILEERR_NOTFOUND | Object could not be found.


IDirectXFileEnumObject::GetDataObjectByName Method

Retrieves the data object that has the specified name. Deprecated.

Syntax

HRESULT GetDataObjectByName(

    LPCSTR szName,
    LPDIRECTXFILEDATA *ppDataObj
);

Parameters

szName
[in] Pointer to the requested name.
ppDataObj
[out] Address of a pointer to an IDirectXFileData interface, representing the returned file data object.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADVALUE | Parameter is invalid.
DXFILEERR_NOTFOUND | Object could not be found.


IDirectXFileEnumObject::GetNextDataObject Method

Retrieves the next top-level object in the Microsoft DirectX file. Deprecated.

Syntax

HRESULT GetNextDataObject(

    LPDIRECTXFILEDATA *ppDataObj
);

Parameters

ppDataObj
[out] Address of a pointer to an IDirectXFileData interface, representing the returned file data object.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADVALUE | Parameter is invalid.
DXFILEERR_NOMOREOBJECTS | All objects have been enumerated.

Remarks

Top-level objects are always data objects. Data reference objects and binary objects can only be children of data objects.


IDirectXFileObject Interface

Applications use the methods of the IDirectXFileObject interface to retrieve information about Microsoft DirectX file objects. Deprecated.

IDirectXFileObject Members

GetId | Retrieves a pointer to the globally unique identifier (GUID) that identifies a DirectX file object. Deprecated.
GetName | Retrieves a pointer to a DirectX file object's name. Deprecated.

Remarks

The GUID for the IDirectXFileObject interface is IID_IDirectXFileObject.

The LPDIRECTXFILEOBJECT type is defined as a pointer to this interface.

typedef interface IDirectXFileObject *LPDIRECTXFILEOBJECT;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | dxfile.h
Import library | d3dxof.lib
Minimum operating systems | Windows 98


IDirectXFileObject::GetId Method

Retrieves a pointer to the globally unique identifier (GUID) that identifies a Microsoft DirectX file object. Deprecated.

Syntax

HRESULT GetId(

    LPGUID pGuid
);

Parameters

pGuid
[out, retval] Pointer to a GUID to receive the object's ID. The function will set the GUID to a NULL GUID if the object does not have an ID.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be DXFILEERR_BADVALUE.


IDirectXFileObject::GetName Method

Retrieves a pointer to a Microsoft DirectX file object's name. Deprecated.

Syntax

HRESULT GetName(

    LPSTR pstrNameBuf,
    LPDWORD pdwBufLen
);

Parameters

pstrNameBuf
[out] Pointer to the buffer in which the DirectX file object's name will be copied. Set to NULL if only the buffer length is needed.
pdwBufLen
[in, out] Pointer to a DWORD specifying the length of the buffer pointed to by pstrNameBuf. The pdwBufLen parameter value will be modified to the buffer length needed to hold the object's name even if pstrNameBuf is NULL. In either case, the function will return DXFILEERR_BADVALUE if the original value of pdwBufLen is not as large as or larger than the length needed to hold the object's name.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC | Memory allocation failed.
DXFILEERR_BADVALUE | Parameter is invalid.


IDirectXFileSaveObject Interface

Applications use the methods of the IDirectXFileSaveObject interface to create data objects and to save templates and data objects. Note that templates are not required in every file. For example, you could put all templates into a single Microsoft DirectX file rather than duplicating them in every DirectX file. Deprecated.

IDirectXFileSaveObject Members

CreateDataObject | Creates a data object. Deprecated.
SaveData | Saves a data object and its children to a DirectX file. Deprecated.
SaveTemplates | Saves templates to a DirectX file. Deprecated.

Remarks

The globally unique identifier (GUID) for the IDirectXFileSaveObject interface is IID_IDirectXFileSaveObject.

The IDirectXFileSaveObject interface is obtained by calling the IDirectXFile::CreateSaveObject method.

The LPDIRECTXFILESAVEOBJECT type is defined as a pointer to this interface.

typedef interface IDirectXFileSaveObject *LPDIRECTXFILESAVEOBJECT;

Interface Information

Stock Implementation | d3d9.dll
Custom Implementation | No
Inherits from | IUnknown
Header | dxfile.h
Import library | d3dxof.lib
Minimum operating systems | Windows 98


IDirectXFileSaveObject::CreateDataObject Method

Creates a data object. Deprecated.

Syntax

HRESULT CreateDataObject(

    REFGUID rguidTemplate,
    LPCSTR szName,
    const GUID *pguid,
    DWORD cbSize,
    LPVOID pvData,
    LPDIRECTXFILEDATA *ppDataObj
);

Parameters

rguidTemplate
[in] Globally unique identifier (GUID) representing the data object's template.
szName
[in] Pointer to the name of the data object. Specify NULL if the object does not have a name.
pguid
[in] Pointer to a GUID representing the data object. Specify NULL if the object does not have a GUID.
cbSize
[in] Size of the data object, in bytes.
pvData
[in] Pointer to a buffer containing all required member's data.
ppDataObj
[out, retval] Address of a pointer to an IDirectXFileData interface, representing the created file data object.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC | Memory allocation failed.
DXFILEERR_BADVALUE | Parameter is invalid.

Remarks

If a data reference object will reference the data object, either the szName or pguid parameter must be non-NULL.

Save any templates by using the IDirectXFileSaveObject::SaveTemplates method before saving the data created by this method. Save the created data by using the IDirectXFileSaveObject::SaveData method.

If you need to save optional data, use the IDirectXFileData::AddDataObject method after using this method and before using IDirectXFileSaveObject::SaveData. If the object has child objects, add them before calling IDirectXFileSaveObject::SaveData.

See Also

IDirectXFileData::AddDataObject, IDirectXFileSaveObject::SaveData, IDirectXFileSaveObject::SaveTemplates


IDirectXFileSaveObject::SaveData Method

Saves a data object and its children to a Microsoft DirectX file. Deprecated.

Syntax

HRESULT SaveData(

    LPDIRECTXFILEDATA pDataObj
);

Parameters

pDataObj
[in] Pointer to an IDirectXFileData interface, representing the file data object to save.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADARRAYSIZE | Array size is invalid.
DXFILEERR_BADVALUE | Parameter is invalid.


IDirectXFileSaveObject::SaveTemplates Method

Saves templates to a Microsoft DirectX file. Deprecated.

Syntax

HRESULT SaveTemplates(

    DWORD cTemplates,
    const GUID **ppguidTemplates
);

Parameters

cTemplates
[in] Total number of templates to save.
ppguidTemplates
[in] Address of a pointer to an array of the globally unique identifiers (GUIDs) for all templates to save.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be DXFILEERR_BADVALUE.

Remarks

The following code fragment provides an example call to IDirectXFileSaveObject::SaveTemplates and example contents for the array to which ppguidTemplates points.

IDirectXFileSaveObject * pDXFileSaveObject;

const GUID *aIds[] = {
    &DXFILEOBJ_SimpleData,
    &DXFILEOBJ_ArrayData,
    &DXFILEOBJ_RestrictedData};

hr = pDXFileSaveObject->SaveTemplates(3, aIds);

After using this method to save the templates, use the IDirectXFileSaveObject::CreateDataObject method to create a data object.

See Also

IDirectXFileSaveObject::CreateDataObject


Functions
Microsoft DirectX 9.0 SDK Update (October 2004)

Functions

This section contains reference information for the functions that you need to implement when you work with Microsoft DirectX files. Deprecated.

The following function is implemented.

Functions

  • DirectXFileCreate


DirectXFileCreate Function

Creates an instance of a DirectXFile object. Deprecated.

Syntax

STDAPI DirectXFileCreate(

    LPDIRECTXFILE *lplpDirectXFile
);

Parameters

lplpDirectXFile
Address of a pointer to an IDirectXFile interface, representing the created DirectXFile object.

Return Value

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

DXFILEERR_BADALLOC | Memory allocation failed.
DXFILEERR_BADVALUE | Parameter is invalid.

Remarks

After using this function, use IDirectXFile::RegisterTemplates to register templates, IDirectXFile::CreateEnumObject to create an enumerator object, or IDirectXFile::CreateSaveObject to create a save object.

Function Information

Header | dxfile.h
Import library | d3dxof.lib
Minimum operating systems | Windows 98

See Also

IDirectXFile::CreateEnumObject, IDirectXFile::CreateSaveObject, IDirectXFile::RegisterTemplates


Structures
Microsoft DirectX 9.0 SDK Update (October 2004)

Structures

This section contains information about the structures used with Microsoft DirectX files. Deprecated.

Structures

  • DXFILELOADMEMORY
  • DXFILELOADRESOURCE


DXFILELOADMEMORY Structure

Identifies memory data. Deprecated.

Syntax

typedef struct _DXFILELOADMEMORY {
    LPVOID lpMemory;
    DWORD dSize;
} DXFILELOADMEMORY, *LPDXFILELOADMEMORY;

Members

lpMemory
Pointer to a block of memory to be loaded.
dSize
Size of the block of memory to be loaded, in bytes.

Remarks

This structure identifies a resource to be loaded when an application uses the IDirectXFile::CreateEnumObject method and specifies DXFILELOAD_FROMMEMORY.

Structure Information

Header | dxfile.h
Minimum operating systems | Windows 98

See Also

IDirectXFile::CreateEnumObject, DXFILE


DXFILELOADRESOURCE Structure

Identifies resource data. Deprecated.

Syntax

typedef struct _DXFILELOADRESOURCE {
    HMODULE hModule;
    LPCTSTR lpName;
    LPCTSTR lpType;
} DXFILELOADRESOURCE, *LPDXFILELOADRESOURCE;

Members

hModule
Handle of the module containing the resource to be loaded. If this member is NULL, the resource must be attached to the executable file that will use it.
lpName
Pointer to a string specifying the name of the resource to be loaded. For example, if the resource is a mesh, this member should specify the name of the mesh file.
lpType
Pointer to a string specifying the user-defined type identifying the resource.

Remarks

This structure identifies a resource to be loaded when an application uses the IDirectXFile::CreateEnumObject method and specifies DXFILELOAD_FROMRESOURCE.

Structure Information

Header | dxfile.h
Minimum operating systems | Windows 98

See Also

IDirectXFile::CreateEnumObject, DXFILE


DXFILE
Microsoft DirectX 9.0 SDK Update (October 2004)

DXFILE

The following flags are used to specify which channels in a texture to operate on. Deprecated.

DXFILEFORMAT

#define | Value | Description
DXFILEFORMAT_BINARY | 0 | Binary file.
DXFILEFORMAT_TEXT | 1 | Text file.
DXFILEFORMAT_COMPRESSED | 2 | Compressed file.

These #defines are declared in Dxfile.h.

DXFILELOADOPTIONS

#define | Value | Description
DXFILELOAD_FROMFILE | 0x00L | Load a file from a file.
DXFILELOAD_FROMRESOURCE | 0x01L | Load a file from a resource.
DXFILELOAD_FROMMEMORY | 0x02L | Load a file from memory.
DXFILELOAD_FROMSTREAM | 0x04L | Load a file from a stream.
DXFILELOAD_FROMURL | 0x08L | Load a file from a URL.

These #defines are declared in Dxfile.h.


Return Values Enumerated Type

The methods used to work with Microsoft DirectX .x files can return the following values in addition to the standard Component Object Model (COM) return values. Deprecated.

Syntax

typedef enum {
    DXFILE_OK,
    DXFILEERR_BADALLOC,
    DXFILEERR_BADARRAYSIZE,
    DXFILEERR_BADCACHEFILE,
    DXFILEERR_BADDATAREFERENCE,
    DXFILEERR_BADFILE,
    DXFILEERR_BADFILECOMPRESSIONTYPE,
    DXFILEERR_BADFILEFLOATSIZE,
    DXFILEERR_BADFILETYPE,
    DXFILEERR_BADFILEVERSION,
    DXFILEERR_BADINTRINSICS,
    DXFILEERR_BADOBJECT,
    DXFILEERR_BADRESOURCE,
    DXFILEERR_BADSTREAMHANDLE,
    DXFILEERR_BADTYPE,
    DXFILEERR_BADVALUE,
    DXFILEERR_FILENOTFOUND,
    DXFILEERR_INTERNALERROR,
    DXFILEERR_NOINTERNET,
    DXFILEERR_NOMOREDATA,
    DXFILEERR_NOMOREOBJECTS,
    DXFILEERR_NOMORESTREAMHANDLES,
    DXFILEERR_NOTDONEYET,
    DXFILEERR_NOTFOUND,
    DXFILEERR_PARSEERROR,
    DXFILEERR_RESOURCENOTFOUND,
    DXFILEERR_NOTEMPLATE,
    DXFILEERR_URLNOTFOUND
} Return Values;

Constants

DXFILE_OK

Command completed successfully.

DXFILEERR_BADALLOC

Memory allocation failed.

DXFILEERR_BADARRAYSIZE

Array size is invalid.

DXFILEERR_BADCACHEFILE

The cache file containing the .x file date is invalid. A cache file contains data retrieved from the network, cached on the hard disk, and retrieved in subsequent requests.

DXFILEERR_BADDATAREFERENCE

Data reference is invalid.

DXFILEERR_BADFILE

File is invalid.

DXFILEERR_BADFILECOMPRESSIONTYPE

File compression type is invalid.

DXFILEERR_BADFILEFLOATSIZE

Floating-point size is invalid.

DXFILEERR_BADFILETYPE

File is not a DirectX .x file.

DXFILEERR_BADFILEVERSION

File version is not valid.

DXFILEERR_BADINTRINSICS

Intrinsics are invalid.

DXFILEERR_BADOBJECT

Object is invalid.

DXFILEERR_BADRESOURCE

Resource is invalid.

DXFILEERR_BADSTREAMHANDLE

Stream handle is invalid.

DXFILEERR_BADTYPE

Object type is invalid.

DXFILEERR_BADVALUE

Parameter is invalid.

DXFILEERR_FILENOTFOUND

File could not be found.

DXFILEERR_INTERNALERROR

Internal error occurred.

DXFILEERR_NOINTERNET

Internet connection not found.

DXFILEERR_NOMOREDATA

No further data is available.

DXFILEERR_NOMOREOBJECTS

All objects have been enumerated.

DXFILEERR_NOMORESTREAMHANDLES

No stream handles are available.

DXFILEERR_NOTDONEYET

Operation has not completed.

DXFILEERR_NOTFOUND

Object could not be found.

DXFILEERR_PARSEERROR

File could not be parsed.

DXFILEERR_RESOURCENOTFOUND

Resource could not be found.

DXFILEERR_NOTEMPLATE

No template available.

DXFILEERR_URLNOTFOUND

URL could not be found.

Enumerated Type Information

Minimum operating systems Windows 98, Windows NT 2000, Windows XP


X File Format Reference
Microsoft DirectX 9.0 SDK Update (October 2004)

X File Format Reference

This section contains reference information for the Microsoft DirectX (.x) file format.
  • Binary Encoding
  • Text Encoding
  • X File Templates

Related Topics

  • X Files (Legacy)


Binary Encoding
Microsoft DirectX 9.0 SDK Update (October 2004)

Binary Encoding

This section details the binary version of the Microsoft DirectX (.x) file format as introduced with the release of DirectX 3.0.

The binary format is a tokenized representation of the text format. Tokens can be stand-alone or accompanied by primitive data records. Stand-alone tokens give grammatical structure, and record-bearing tokens supply the necessary data.

Note that all data is stored in little-endian format. A valid binary data stream consists of a header followed by templates and/or data objects.

This section discusses the following components of the binary file format and provides an example template and binary data object.

  • Header
  • Tokens
  • Token Records
  • Templates
  • Data
  • Examples


Header
Microsoft DirectX 9.0 SDK Update (October 2004)

Header

The following definitions should be used when directly reading and writing the binary header.

Note Compressed data streams are not currently supported and are therefore not detailed here.
#define XOFFILE_FORMAT_MAGIC \
  ((long)'x' + ((long)'o' << 8) + ((long)'f' << 16) + ((long)' ' << 24))

#define XOFFILE_FORMAT_VERSION \
  ((long)'0' + ((long)'3' << 8) + ((long)'0' << 16) + ((long)'2' << 24))

#define XOFFILE_FORMAT_BINARY \
  ((long)'b' + ((long)'i' << 8) + ((long)'n' << 16) + ((long)' ' << 24))

#define XOFFILE_FORMAT_TEXT   \
  ((long)'t' + ((long)'x' << 8) + ((long)'t' << 16) + ((long)' ' << 24))

#define XOFFILE_FORMAT_COMPRESSED \
  ((long)'c' + ((long)'m' << 8) + ((long)'p' << 16) + ((long)' ' << 24))

#define XOFFILE_FORMAT_FLOAT_BITS_32 \
  ((long)'0' + ((long)'0' << 8) + ((long)'3' << 16) + ((long)'2' << 24))

#define XOFFILE_FORMAT_FLOAT_BITS_64 \
  ((long)'0' + ((long)'0' << 8) + ((long)'6' << 16) + ((long)'4' << 24))


Tokens
Microsoft DirectX 9.0 SDK Update (October 2004)

Tokens

Tokens are written as little-endian WORDs. The following list of token values is divided into record-bearing and stand-alone tokens.

The record-bearing tokens are defined as follows.

#define TOKEN_NAME         1
#define TOKEN_STRING       2
#define TOKEN_INTEGER      3
#define TOKEN_GUID         5
#define TOKEN_INTEGER_LIST 6
#define TOKEN_FLOAT_LIST   7

The stand-alone tokens are defined as follows.

#define TOKEN_OBRACE      10
#define TOKEN_CBRACE      11
#define TOKEN_OPAREN      12
#define TOKEN_CPAREN      13
#define TOKEN_OBRACKET    14
#define TOKEN_CBRACKET    15
#define TOKEN_OANGLE      16
#define TOKEN_CANGLE      17
#define TOKEN_DOT         18
#define TOKEN_COMMA       19
#define TOKEN_SEMICOLON   20
#define TOKEN_TEMPLATE    31
#define TOKEN_WORD        40
#define TOKEN_DWORD       41
#define TOKEN_FLOAT       42
#define TOKEN_DOUBLE      43
#define TOKEN_CHAR        44
#define TOKEN_UCHAR       45
#define TOKEN_SWORD       46
#define TOKEN_SDWORD      47
#define TOKEN_VOID        48
#define TOKEN_LPSTR       49
#define TOKEN_UNICODE     50
#define TOKEN_CSTRING     51
#define TOKEN_ARRAY       52


Token Records
Microsoft DirectX 9.0 SDK Update (October 2004)

Token Records

This section describes the format of the records for each of the record-bearing tokens. Information is divided into the following sections.

  • TOKEN_NAME
  • TOKEN_STRING
  • TOKEN_INTEGER
  • TOKEN_GUID
  • TOKEN_INTEGER_LIST
  • TOKEN_FLOAT_LIST

TOKEN_NAME

A variable-length record. The token is followed by a count value that specifies the number of bytes that follow in the name field. An ASCII name of length count completes the record.

Field | Type | Size (bytes) | Contents
token | WORD | 2 | TOKEN_NAME
count | DWORD | 4 | Length of name field, in bytes
name | BYTE array | count | ASCII name

TOKEN_STRING

A variable-length record. The token is followed by a count value that specifies the number of bytes that follow in the string field. An ASCII string of length count continues the record, which is completed by a terminating token. The choice of terminator is determined by syntax issues discussed elsewhere.

Field | Type | Size (bytes) | Contents
token | WORD | 2 | TOKEN_STRING
count | DWORD | 4 | Length of string field in bytes
string | BYTE array | count | ASCII string
terminator | DWORD | 4 | TOKEN_SEMICOLON or TOKEN_COMMA

TOKEN_INTEGER

A fixed length record. The token is followed by the integer value required.

Field | Type | Size (bytes) | Contents
token | WORD | 2 | TOKEN_INTEGER
value | DWORD | 4 | Single integer

TOKEN_GUID

A fixed-length record. The token is followed by the four data fields as defined by the OSF DCE standard.

Field | Type | Size (bytes) | Contents
token | WORD | 2 | TOKEN_GUID
data1 | DWORD | 4 | UUID data field 1
data2 | WORD | 2 | UUID data field 2
data3 | WORD | 2 | UUID data field 3
data4 | BYTE array | 8 | UUID data field 4

TOKEN_INTEGER_LIST

A variable-length record. The token is followed by a count value that specifies the number of integers that follow in the list field. For efficiency, consecutive integer lists should be compounded into a single list.

Field | Type | Size (bytes) | Contents
token | WORD | 2 | TOKEN_INTEGER_LIST
count | DWORD | 4 | Number of integers in list field
list | DWORD | 4 נcount | Integer list

TOKEN_FLOAT_LIST

A variable-length record. The token is followed by a count value that specifies the number of floats or doubles that follow in the list field. The size of the floating point value (float or double) is determined by the value of float sizespecified in the file header. For efficiency, consecutive TOKEN_FLOAT_LISTs should be compounded into a single list.

Field | Type | Size (bytes) | Contents
token | WORD | 2 | TOKEN_FLOAT_LIST
count | DWORD | 4 | Number of floats or doubles in list field
list | float/double array | 4 or 8 נcount | Float or double list


Templates
Microsoft DirectX 9.0 SDK Update (October 2004)

Templates

A template has the following syntax definition.

template              : TOKEN_TEMPLATE name TOKEN_OBRACE
                            class_id
                            template_parts
                            TOKEN_CBRACE

template_parts        : template_members_part TOKEN_OBRACKET
                        template_option_info
                        TOKEN_CBRACKET
                      | template_members_list

template_members_part : /* Empty */
                      | template_members_list

template_option_info  : ellipsis
                      | template_option_list

template_members_list :    template_members
                      | template_members_list template_members

template_members      : primitive
                      | array
                      | template_reference

primitive             : primitive_type optional_name TOKEN_SEMICOLON

array                 : TOKEN_ARRAY array_data_type name dimension_list
                        TOKEN_SEMICOLON

template_reference    : name optional_name YT_SEMICOLON

primitive_type        : TOKEN_WORD
                      | TOKEN_DWORD
                      | TOKEN_FLOAT
                      | TOKEN_DOUBLE
                      | TOKEN_CHAR
                      | TOKEN_UCHAR
                      | TOKEN_SWORD
                      | TOKEN_SDWORD
                      | TOKEN_LPSTR
                      | TOKEN_UNICODE
                      | TOKEN_CSTRING

array_data_type       : primitive_type
                      | name

dimension_list        : dimension
                      | dimension_list dimension

dimension             : TOKEN_OBRACKET dimension_size TOKEN_CBRACKET

dimension_size        : TOKEN_INTEGER
                      | name

template_option_list  : template_option_part
                      | template_option_list template_option_part

template_option_part  : name optional_class_id

name                  : TOKEN_NAME

optional_name         : /* Empty */
                      | name

class_id              : TOKEN_GUID

optional_class_id     : /* Empty */
                      | class_id

ellipsis              : TOKEN_DOT TOKEN_DOT TOKEN_DOT


Data
Microsoft DirectX 9.0 SDK Update (October 2004)

Data

A data object has the following syntax definition.

object                : identifier optional_name TOKEN_OBRACE
                            optional_class_id
                            data_parts_list
                            TOKEN_CBRACE

data_parts_list       : data_part
                      | data_parts_list data_part

data_part             : data_reference
                      | object
                      | number_list
                      | float_list
                      | string_list

number_list           : TOKEN_INTEGER_LIST

float_list            : TOKEN_FLOAT_LIST

string_list           : string_list_1 list_separator

string_list_1         : string
                      | string_list_1 list_separator string

list_separator        : comma
                      | semicolon

string                : TOKEN_STRING

identifier            : name
                      | primitive_type

data_reference        : TOKEN_OBRACE name optional_class_id TOKEN_CBRACE

Note that in number_list and float_list data in binary files, TOKEN_COMMA and TOKEN_SEMICOLON are not used. The comma and semicolon are used in string_list data. Also note that you can only use data_reference for optional data members.


Examples
Microsoft DirectX 9.0 SDK Update (October 2004)

Examples

Two example binary template definitions and an example of a binary data object follow.

Note Data is stored in little-endian format, which is not shown in these examples.

The closed template RGB is identified by the UUID {55b6d780-37ec-11d0-ab39-0020af71e433} and has three members—r, g, and b—each of type float.

TOKEN_TEMPLATE, TOKEN_NAME, 3, 'R', 'G', 'B', TOKEN_OBRACE,
TOKEN_GUID, 55b6d780, 37ec, 11d0, ab, 39, 00, 20, af, 71, e4, 33,
TOKEN_FLOAT, TOKEN_NAME, 1, 'r', TOKEN_SEMICOLON,
TOKEN_FLOAT, TOKEN_NAME, 1, 'g', TOKEN_SEMICOLON,
TOKEN_FLOAT, TOKEN_NAME, 1, 'b', TOKEN_SEMICOLON,
TOKEN_CBRACE

The closed template Matrix4x4 is identified by the UUID {55b6d781-37ec-11d0-ab39-0020af71e433} and has one member—a two-dimensional array named matrix—of type float.

TOKEN_TEMPLATE, TOKEN_NAME, 9, 'M', 'a', 't', 'r', 'i', 'x', '4', 'x', '4', TOKEN_OBRACE,
TOKEN_GUID, 55b6d781, 37ec, 11d0, ab, 39, 00, 20, af, 71, e4, 33,
TOKEN_ARRAY, TOKEN_FLOAT, TOKEN_NAME, 6, 'm', 'a', 't', 'r', 'i', 'x',
TOKEN_OBRACKET, TOKEN_INTEGER, 4, TOKEN_CBRACKET,
TOKEN_OBRACKET, TOKEN_INTEGER, 4, TOKEN_CBRACKET,
TOKEN_CBRACE

The binary data object that follows shows an instance of the RGB template defined earlier. The example object is named blue, and its three members—r, g, and b—have the values 0.0, 0.0, and 1.0, respectively.

TOKEN_NAME, 3, 'R', 'G', 'B', TOKEN_NAME, 4, 'b', 'l', 'u', 'e', TOKEN_OBRACE,
TOKEN_FLOAT_LIST, 3, 0.0, 0.0, 1.0, TOKEN_CBRACE


Text Encoding
Microsoft DirectX 9.0 SDK Update (October 2004)

Text Encoding

The Microsoft DirectX .x file format is not specific to any application. It uses templates that don't depend on how the file is used. This allows the .x file format to be used by any client application.

This following sections deal with the content and syntax of the file format, which uses the .x extension in the DirectX software development kit (SDK).

  • Data
  • Reserved Words, Header, and Comments
  • Templates
  • Use of Commas and Semicolons


Data
Microsoft DirectX 9.0 SDK Update (October 2004)

Data

Data objects contain the actual data or a reference to that data. Each data object has a corresponding template that specifies the data type. The following sections discuss the form and parts of data objects.

Form, Identifier, and Name

Data objects have the following form.

<Identifier> [name] { [<UUID>]
<member 1>;
...
<member n>;
}

The identifier is compulsory and must match a previously defined data type or primitive. However, the name is optional.

Data Members

Data members can be one of the following: data object, data reference, integer list, float list, or string list.

A data object is a nested data object. This enables the hierarchical nature of the file format to be expressed. The types of nested data objects allowed in the hierarchy may be restricted. See Templates for more information.

A data reference is a reference to a previously encountered data object as shown in the following example.

{
  name |
  UUID |
  name UUID
}

An integer list is a semicolon-separated list of integers, as shown in the following example.

1; 2; 3;

A float list is a semicolon-separated list of floats, as shown in the following example.

1.0; 2.0; 3.0;

A string list is a semicolon-separated list of strings, as shown in the following example.

"Moose"; "Goats"; "Sheep";


Reserved Words, Header, and Comments
Microsoft DirectX 9.0 SDK Update (October 2004)

Reserved Words, Header, and Comments

The table below shows which words are reserved and must not be used.

ARRAY | DWORD | UCHAR
BINARY | FLOAT | ULONGLONG
BINARY_RESOURCE | SDWORD | UNICODE
CHAR | STRING | WORD
CSTRING | SWORD |
DOUBLE | TEMPLATE |

The variable-length header is compulsory and must be at the beginning of the data stream. The header contains the following data.

Type | Required | Size (in bytes) | Value | Description
Magic Number | x | 4 | "xof " |
Version Number | x | 2 | "03" | Major version 3
 |  |  | "03" | Minor version 3
Format Type | x | 4 | "txt " | Text File
 |  |  | "bin " | Binary file
 |  |  | "tzip" | MSZip compressed text file
 |  |  | "bzip" | MSZip compressed binary file
Float Size | x |  | "0064" | 64-bit floats
 | x |  | "0032" | 32-bit floats

The values in the table are delimited by quotes to call attention to the number of characters in each value. Those with 4 bytes contain four characters, those with 2 bytes contain two characters.

Comments are applicable only in text files. Comments can occur anywhere in the data stream. A comment begins with either C++ style double-slashes (//), or a number sign (#). The comment runs to the next new line. The following example shows valid comments.

#  This is a comment.
// This is another comment.


Templates
Microsoft DirectX 9.0 SDK Update (October 2004)

Templates

Templates define how the data stream is interpreted—the data is modulated by the template definition. This section discusses the following aspects of a template and provides an example template.

There is one special template - the header template. It is recommended that each application define a header template and use it to define application-specific information, such as version information. If present, this header is read by the .x file format application programming interface (API). If a flags member is available, it is used to determine how the following data is interpreted. The flags member, if defined, should be a DWORD. One bit is currently defined - bit 0. If this bit is clear, the following data in the file is binary. If set, the following data is text. You can use multiple header data objects to switch between binary and text within the file.

Template Form, Name, and UUID

A template has the following form.

template <template-name> {
<UUID>
<member 1>;
...
<member n>;
[restrictions]
}

The template name is an alphanumeric name that can include the underscore character (_). It must not begin with a digit. The universally unique identifier (UUID) is a universally unique identifier formatted to the Open Software Foundation's Distributed Computing Environment standard and enclosed by angle brackets (< >). For example: <3D82AB43-62DA-11cf-AB39-0020AF71E433>.

Template Members

Template members consist of a named data type followed by an optional name or an array of a named data type. Valid primitive data types are defined in the following table.

Type | Size
WORD | 16 bits
DWORD | 32 bits
FLOAT | Institute of Electrical and Electronics Engineers (IEEE) float
DOUBLE | 64 bits
CHAR | 8 bits
UCHAR | 8 bits
BYTE | 8 bits
STRING | NULL terminated string
CSTRING | Formatted C string (not supported)
UNICODE | Unicode string (not supported)

Additional data types defined by templates encountered earlier in the data stream can also be referenced within a template definition. No forward references are allowed.

Any valid data type can be expressed as an array in the template definition. The basic syntax is shown in the following example.

array <data-type> <name>[<dimension-size>];

<dimension-size> can either be an integer or a named reference to another template member whose value is then substituted. Arrays can be n-dimensional, where n is determined by the number of paired square brackets trailing the statement, as in the following example.

array DWORD FixedHerd[24];
array DWORD Herd[nCows];
array FLOAT Matrix4x4[4][4];

Template Restrictions

Templates can be open, closed, or restricted. These restrictions determine which data types can appear in the immediate hierarchy of a data object defined by the template. An open template has no restrictions, a closed template rejects all data types, and a restricted template allows a named list of data types.

The syntax for indicating an open template is three periods enclosed by square brackets.

[ ... ]

A comma-separated list of named data types followed optionally by their UUIDs enclosed by square brackets indicates a restricted template.

[ { data-type [ UUID ] , } ... ]

The absence of either of the above indicates a closed template.

Template Example

The following shows an example template.

template Mesh {
<3D82AB44-62DA-11cf-AB39-0020AF71E433>
DWORD nVertices;
array Vector vertices[nVertices];
DWORD nFaces;
array MeshFace faces[nFaces];
 [ ... ]                // An open template
}
template Vector {
<3D82AB5E-62DA-11cf-AB39-0020AF71E433>
FLOAT x;
FLOAT y;
FLOAT z;
}                        // A closed template
template FileSystem {
<UUID>
STRING name;
[ Directory <UUID>, File <UUID> ]    // A restricted template
}


Use of Commas and Semicolons
Microsoft DirectX 9.0 SDK Update (October 2004)

Use of Commas and Semicolons

Using commas and semicolons can be the most complex syntax issue in the file format, and this usage is very strict. Commas are used to separate array members; semicolons terminate each data item.

For example, if a template is defined in the following manner:

template mytemp {
DWORD myvar;
}

Then an instance of this template looks like the following:

mytemp dataTemp {
1;
}

If a template containing another template is defined in the following manner;

template mytemp {
DWORD myvar;
DWORD myvar2;
}
template container {
FLOAT aFloat;
mytemp aTemp;
}

Then an instance of this template looks like the following:

container dataContainer {
1.1;
2; 3;;
}

Note that the second line that represents the mytemp inside container has two semicolons at the end of the line. The first semicolon indicates the end of the data item, aTemp (inside container), and the second semicolon indicates the end of the container.

If an array is defined in the following manner:

Template mytemp {

array DWORD myvar[3];

}

Then an instance of this looks like the following:

mytemp aTemp {
1, 2, 3;
}

In the array example, there is no need for the data items to be separated by semicolons because they are delineated by commas. The semicolon at the end marks the end of the array.

Consider a template that contains an array of data items defined by a template.

template mytemp {
DWORD myvar;
DWORD myvar2;
}
template container {
DWORD count;
array mytemp tempArray[count];
}

An instance of this would look like the following example.

container aContainer {
3;
1;2;,3;4;,5;6;;
}


X File Templates
Microsoft DirectX 9.0 SDK Update (October 2004)

X File Templates

This section lists the .x file templates. Template format is discussed in Templates.

  • Animation
  • AnimationKey
  • AnimationOptions
  • AnimationSet
  • AnimTicksPerSecond
  • Boolean
  • Boolean2d
  • ColorRGB
  • ColorRGBA
  • CompressedAnimationSet
  • Coords2d
  • DeclData
  • EffectDWord
  • EffectFloats
  • EffectInstance
  • EffectParamDWord
  • EffectParamFloats
  • EffectParamString
  • EffectString
  • FaceAdjacency
  • FloatKeys
  • Frame
  • FrameTransformMatrix
  • FVFData
  • Guid
  • IndexedColor
  • Material
  • MaterialWrap
  • Matrix4x4
  • Mesh
  • MeshFace
  • MeshFaceWraps
  • MeshMaterialList
  • MeshNormals
  • MeshTextureCoords
  • MeshVertexColors
  • Patch
  • PatchMesh
  • PatchMesh9
  • PMAttributeRange
  • PMInfo
  • PMVSplitRecord
  • SkinWeights
  • TextureFilename
  • TimedFloatKeys
  • Vector
  • VertexDuplicationIndices
  • VertexElement
  • XSkinMeshHeader


Animation
Microsoft DirectX 9.0 SDK Update (October 2004)

Animation

Contains animations referencing a previous frame. It should contain one reference to a frame and at least one set of AnimationKey templates. It also can contain an AnimationOptions data object.

        template Animation
        {
            < 3D82AB4F-62DA-11cf-AB39-0020AF71E433 >
            [...]
        }

Where:

  • [ ... ] - Any .x file template can be used here. This makes the architecture extensible.


AnimationKey
Microsoft DirectX 9.0 SDK Update (October 2004)

AnimationKey

Defines a set of animation keys. A matrix key is useful for sets of animation data that need to be represented as transformation matrices.

        template AnimationKey
        {
            < 10DD46A8-775B-11CF-8F52-0040333594A3 >
            DWORD keyType;
            DWORD nKeys;
            array TimedFloatKeys keys[nKeys];
        }

Where:

  • keyType - Specifies whether the keys are rotation, scale, position, or matrix keys (using the integers 0, 1, 2, or 3, respectively).
  • nKeys - Number of keys.
  • keys - An array of keys. See TimedFloatKeys.


AnimationOptions
Microsoft DirectX 9.0 SDK Update (October 2004)

AnimationOptions

Enables you to set animation options.

        template AnimationOptions
        {
            < E2BF56C0-840F-11cf-8F52-0040333594A3 >
            DWORD openclosed;
            DWORD positionquality;
        }

Where:

  • openclosed - Use 0 for a closed animation, or 1 for an open animation. By default, an animation is closed.
  • positionquality - Set the position quality for any position keys specified. Use 0 for spline positions or 1 for linear positions.


AnimationSet
Microsoft DirectX 9.0 SDK Update (October 2004)

AnimationSet

Contains one or more Animation objects. Each animation within an animation set has the same time at any given point. Increasing the animation set's time increases the time for all the animations it contains.

        template AnimationSet
        {
            < 3D82AB50-62DA-11cf-AB39-0020AF71E433 >
            [ Animation < 3D82AB4F-62DA-11cf-AB39-0020AF71E433 > ]
        }

Where:

  • [ Animation < 3D82AB4F-62DA-11cf-AB39-0020AF71E433 > ] - Optional animation template.


AnimTicksPerSecond
Microsoft DirectX 9.0 SDK Update (October 2004)

AnimTicksPerSecond

Describes an animation scale factor.

        template AnimTicksPerSecond
        {
            < 9E415A43-7BA6-4a73-8743-B73D47E88476 >
            DWORD AnimTicksPerSecond;
        }

Where:

  • AnimTicksPerSecond - A scale factor to convert animation time stamps to global time. Its value divides the animation time by either 30, 60, 24 or 25.


Boolean
Microsoft DirectX 9.0 SDK Update (October 2004)

Boolean

Defines a simple Boolean type.

        template Boolean
        {
            < 537da6a0-ca37-11d0-941c-0080c80cfa7b >
            DWORD truefalse;
        }

Where:

  • truefalse - True for a Boolean, false otherwise.


Boolean2d
Microsoft DirectX 9.0 SDK Update (October 2004)

Boolean2d

Defines a set of two Boolean values used in the MeshFaceWraps template to define the texture topology of an individual face.

        template Boolean2d
        {
            < 4885AE63-78E8-11cf-8F52-0040333594A3 >
            Boolean u;
            Boolean v;
        }

Where:

  • u - Boolean value. See Boolean.
  • v - Boolean value. See Boolean.


ColorRGB
Microsoft DirectX 9.0 SDK Update (October 2004)

ColorRGB

Defines the basic RGB color object.

        template ColorRGB
        {
            < D3E16E81-7835-11cf-8F52-0040333594A3 >
            float red;
            float green;
            float blue;
        }


ColorRGBA
Microsoft DirectX 9.0 SDK Update (October 2004)

ColorRGBA

Defines a color object with an alpha component. This is used for the face color in the material template definition.

        template ColorRGBA
        {
            < 35FF44E0-6C7C-11cf-8F52-0040333594A3 >
            float red;
            float green;
            float blue;
            float alpha;
        }


CompressedAnimationSet
Microsoft DirectX 9.0 SDK Update (October 2004)

CompressedAnimationSet

Contains animation set data.

template CompressedAnimationSet
{
    <7F9B00B3-F125-4890-876E-1C42BF697C4D>
    DWORD CompressedBlockSize;
    FLOAT TicksPerSec;
    DWORD PlaybackType;
    DWORD BufferLength;
    array DWORD CompressedData[BufferLength];
}

Where:

  • CompressedBlockSize - Total size, in bytes, of the compressed data in the compressed key frame animation data buffer.
  • TicksPerSec - Number of animation key frame ticks that occur per second.
  • PlaybackType - Type of the animation set playback loop. See D3DXPLAYBACK_TYPE.
  • BufferLength - Minimum buffer size, in bytes, required to hold compressed key frame animation data. Value is equal to ( ( CompressedBlockSize + 3 ) / 4 ).
  • CompressedData[BufferLength] - An array of compressed data values.

Related Topics

  • XFILECOMPRESSEDANIMATIONSET


Coords2d
Microsoft DirectX 9.0 SDK Update (October 2004)

Coords2d

Defines a two dimensional vector used to define a mesh's (u, v) texture coordinates.

        template Coords2d
        {
            < F6F23F44-7686-11cf-8F52-0040333594A3 >
            float u;
            float v;
        }
  • u - u coordinate value.
  • v - v coordinate value.


DeclData
Microsoft DirectX 9.0 SDK Update (October 2004)

DeclData

Describes a vertex declaration.

        template DeclData
        {
            < BF22E553-292C-4781-9FEA-62BD554BDD93 >
            DWORD nElements;
            array VertexElement Elements[nElements];
            DWORD nDWords;
            array DWORD data[nDWords];
        }

Where:

  • nElements - Number of vertex declaration elements.
  • Elements[nElements] - Array of vertex declaration elements.
  • nDWords - Number of DWORDS.
  • data[nDWords] - Array of DWORDS that contain the data in each vertex element.


EffectDWord
Microsoft DirectX 9.0 SDK Update (October 2004)

EffectDWord

Defines a legacy effect DWORD. This template has been replaced by the EffectParamDWord template.

        template EffectDWord
        {
            < 622C0ED0-956E-4da9-908A-2AF94F3CE716 >
            DWORD Value;
        }


EffectFloats
Microsoft DirectX 9.0 SDK Update (October 2004)

EffectFloats

Defines a legacy effect FLOAT. This template has been replaced by the EffectParamFloats template.

        template EffectFloats
        {
            < F1CFE2B3-0DE3-4e28-AFA1-155A750A282D >
            DWORD nFloats;
            array float Floats[nFloats];
        }

Where:

  • nFloats - Number of floats.
  • Floats[nFloats] - Array of float values.


EffectInstance
Microsoft DirectX 9.0 SDK Update (October 2004)

EffectInstance

Defines an effect instance.

        template EffectInstance
        {
            < E331F7E4-0559-4cc2-8E99-1CEC1657928F >
            STRING EffectFilename;
            [ ... ]
        }

Where:

  • EffectFilename - Effect filename.
  • [ ... ] - Any .x file template can be used here. This makes the architecture extensible.


EffectParamDWord
Microsoft DirectX 9.0 SDK Update (October 2004)

EffectParamDWord

Defines an effect DWORD. This template replaced the EffectDWord template.

        template EffectParamDWord
        {
            < E13963BC-AE51-4c5d-B00F-CFA3A9D97CE5 >
            STRING ParamName;
            DWORD Value;
        }

Where:

  • ParamName - Parameter name.
  • Value - Parameter value.


EffectParamFloats
Microsoft DirectX 9.0 SDK Update (October 2004)

EffectParamFloats

Defines effect floating-point numbers. This template replaces the EffectFloats template.

        template EffectParamFloats
        {
            < 3014B9A0-62F5-478c-9B86-E4AC9F4E418B >
            STRING ParamName;
            DWORD nFloats;
            array float Floats[nFloats];
        }

Where:

  • ParamName - Name of the array of floats.
  • nFloats - Number of floating-point values in the array.
  • Floats[nFloats] - Array of floating-point values.


EffectParamString
Microsoft DirectX 9.0 SDK Update (October 2004)

EffectParamString

Assigns a value to a parameter in an effects file.

        template EffectParamString
        {
            < 1DBC4C88-94C1-46ee-9076-2C28818C9481 >
            STRING ParamName;
            STRING Value;
        }
  • ParamName - Parameter name in the effects file.
  • Value - Value assigned to the parameter.

This template replaces the former EffectString template.


EffectString
Microsoft DirectX 9.0 SDK Update (October 2004)

EffectString

Legacy template used to assign a value in an effects file. This template has been replaced by the EffectParamString template.

        template EffectString
        {
            < D55B097E-BDB6-4c52-B03D-6051C89D0E42 >
            STRING Value;
        }


FaceAdjacency
Microsoft DirectX 9.0 SDK Update (October 2004)

FaceAdjacency

This template is instantiated on a per-mesh basis, holding information about which vertices in the mesh are duplicates of each other. Duplicates result when a vertex sits on a smoothing group or material boundary. The purpose of this template is to allow the loader to determine which vertices exhibiting different peripheral parameters are actually the same vertexes in the model. Certain applications (mesh simplification, for example) can make use of this information.

        template FaceAdjacency
        {
            < A64C844A-E282-4756-8B80-250CDE04398C >
            DWORD nIndices;
            array DWORD indices[nIndices];
        }

Where:

  • nIndices - Number of indices in the mesh.
  • indices[nIndices] - Array of indices.


FloatKeys
Microsoft DirectX 9.0 SDK Update (October 2004)

FloatKeys

Defines an array of floating-point numbers (floats) and the number of floats in that array. This is used for defining sets of animation keys.

        template FloatKeys
        {
            < 10DD46A9-775B-11cf-8F52-0040333594A3 >
            DWORD nValues;
            array float values[nValues];
        }
  • nValues - Number of floats.
  • values[nValues] - Array of float values.


Frame
Microsoft DirectX 9.0 SDK Update (October 2004)

Frame

Defines a coordinate frame, or "frame of reference." The Frame template is open and can contain any object. The D3DX mesh-loading functions recognize Mesh, FrameTransformMatrix, and Frame template instances as child objects when loading a Frame instance.

        template Frame
        {
            < 3D82AB46-62DA-11CF-AB39-0020AF71E433 >
            [...]
        }

The frame template recognizes child Frame and Mesh nodes inside a frame and can recognize user-defined templates through a callback function.


FrameTransformMatrix
Microsoft DirectX 9.0 SDK Update (October 2004)

FrameTransformMatrix

Defines a local transform for a frame (and all its child objects).

        template FrameTransformMatrix
        {
            < F6F23F41-7686-11cf-8F52-0040333594A3 >
            Matrix4x4 frameMatrix;
        }

Where:

  • frameMatrix - A Matrix4x4 template. See Matrix4x4.


FVFData
Microsoft DirectX 9.0 SDK Update (October 2004)

FVFData

Specifies the mesh data minus the position data.

        template FVFData
        {
            < B6E70A0E-8EF9-4e83-94AD-ECC8B0C04897 >
            DWORD dwFVF;
            DWORD nDWords;
            array DWORD data[nDWords];
        }

Where:

  • dwFVF - A flexible vertex format (FVF) code.
  • nDWords - Binary data. The number of DWORDS.
  • data[nDWords] - Array of DWORDS that contain the data in each vertex element.


Guid
Microsoft DirectX 9.0 SDK Update (October 2004)

Guid

Defines a globally unique identifier (GUID) that can be used in other templates.

        template Guid
        {
            < a42790e0-7810-11cf-8f52-0040333594a3 >
            DWORD data1;
            WORD data2;
            WORD data3;
            array UCHAR data4[8];
        }

Where the parameters together form the binary storage format for a GUID:

  • data1 - 32-bit unsigned integer data value
  • data2 - 16-bit unsigned integer data value
  • data3 - 16-bit unsigned integer data value
  • data4 - An array of unsigned characters


IndexedColor
Microsoft DirectX 9.0 SDK Update (October 2004)

IndexedColor

Consists of an index parameter and an RGBA color and is used for defining mesh vertex colors. The index defines the vertex to which the color is applied.

        template IndexedColor
        {
            < 1630B820-7842-11cf-8F52-0040333594A3 >
            DWORD index;
            ColorRGBA indexColor;
        }

Where:

  • index - A DWORD. See the description above.
  • indexColor - A ColorRGBA template. See ColorRGBA.


Material
Microsoft DirectX 9.0 SDK Update (October 2004)

Material

Defines a basic material color that can be applied to either a complete mesh or a mesh's individual faces. The power is the specular exponent of the material.

Note The ambient color requires an alpha component.

TextureFilename is an optional data object. If this object is not present, the face is untextured.

        template Material
        {
            < 3D82AB4D-62DA-11CF-AB39-0020AF71E433 >
            ColorRGBA faceColor;
            FLOAT power;
            ColorRGB specularColor;
            ColorRGB emissiveColor;
            [...]
        }

Where:

  • faceColor - Face color. A ColorRGBA template. See ColorRGBA.
  • power - Material specular color exponent.
  • specularColor - Material specular color. A ColorRGB template. See ColorRGB.
  • emissiveColor - Material emissive color. A ColorRGB template. See ColorRGB.


MaterialWrap
Microsoft DirectX 9.0 SDK Update (October 2004)

MaterialWrap

Defines a set of two Boolean values used in the MeshFaceWraps template to define the texture topology of an individual face. Use instead of Boolean2d when the texture coordinates (u, v) span the range of 0 to 2 instead of 0 to 1.

        template MaterialWrap
        {
            < 4885ae60-78e8-11cf-8f52-0040333594a3 >
            Boolean u;
            Boolean v;
        }

Where:

  • u - Boolean value. See Boolean.
  • v - Boolean value. See Boolean.
Note The MeshFaceWraps template is no longer used.


Matrix4x4
Microsoft DirectX 9.0 SDK Update (October 2004)

Matrix4x4

Defines a 4×4 matrix. This is used as a frame transformation matrix.

        template Matrix4x4
        {
            < F6F23F45-7686-11cf-8F52-0040333594A3 >
            array float matrix[16];
        }

Where:

  • array float matrix[16] - Array of 16 floats.


Mesh
Microsoft DirectX 9.0 SDK Update (October 2004)

Mesh

Defines a simple mesh. The first array is a list of vertices, and the second array defines the faces of the mesh by indexing into the vertex array.

    template Mesh
    {
        <3D82AB44-62DA-11CF-AB39-0020AF71E433>
        DWORD nVertices;
        array Vector vertices[nVertices];
        DWORD nFaces;
        array MeshFace faces[nFaces];
        [...]
    }

Where:

  • nVertices - Number of vertices.
  • array Vector vertices[nVertices] - Array of vertices, each of type Vector. See Vector.
  • nFaces - Number of faces.
  • array MeshFace faces[nFaces] - Array of faces, each of type MeshFace. See MeshFace.
  • [ ... ] - Any .x file template can be used here. This makes the architecture extensible. Material and TextureFilename templates are typically used.


MeshFace
Microsoft DirectX 9.0 SDK Update (October 2004)

MeshFace

Used by the Mesh template to define a mesh's faces. Each element of the nFaceVertexIndices array references a mesh vertex used to build the face.

        template MeshFace
        {
            < 3D82AB5F-62DA-11cf-AB39-0020AF71E433 >
            DWORD nFaceVertexIndices;
            array DWORD faceVertexIndices[nFaceVertexIndices];
        }

Where:

  • nFaceVertexIndices - Number of indices.
  • array DWORD faceVertexIndices[nFaceVertexIndices] - Array of indices.


MeshFaceWraps
Microsoft DirectX 9.0 SDK Update (October 2004)

MeshFaceWraps

Used to define the texture topology of each face in a wrap. The value of the nFaceWrapValues member should be equal to the number of faces in a mesh.

        template MeshFaceWraps
        {
            < ED1EC5C0-C0A8-11D0-941C-0080C80CFA7B >
            DWORD nFaceWrapValues;
            array Boolean2d faceWrapValues[nFaceWrapValues];
        }

This template is no longer used.


MeshMaterialList
Microsoft DirectX 9.0 SDK Update (October 2004)

MeshMaterialList

Used in a mesh object to specify which material applies to which faces. The nMaterials member specifies how many materials are present, and materials specify which material to apply.

        template MeshMaterialList
        {
            < F6F23F42-7686-11CF-8F52-0040333594A3 >
            DWORD nMaterials;
            DWORD nFaceIndexes;
            array DWORD faceIndexes[nFaceIndexes];
            [Material <3D82AB4D-62DA-11CF-AB39-0020AF71E433>]
        }

Where:

  • nMaterials - A DWORD. The number of materials.
  • nFaceIndexes - A DWORD. The number of indices.
  • faceIndexes[nFaceIndexes] - An arrray of DWORDs containing the face indices.


MeshNormals
Microsoft DirectX 9.0 SDK Update (October 2004)

MeshNormals

Defines normals for a mesh. The first array of vectors is the normal vectors themselves, and the second array is an array of indexes specifying which normals should be applied to a given face. The value of the nFaceNormals member should be equal to the number of faces in a mesh.

        template MeshNormals
        {
            < F6F23F43-7686-11cf-8F52-0040333594A3 >
            DWORD nNormals;
            array Vector normals[nNormals];
            DWORD nFaceNormals;
            array MeshFace faceNormals[nFaceNormals];
        }

Where:

  • nNormals - Number of normals.
  • array Vector normals[nNormals] - Array of normals. See Vector.
  • nFaceNormals - Number of face normals.
  • array MeshFace faceNormals[nFaceNormals] - Array of mesh face normals. See MeshFace.


MeshTextureCoords
Microsoft DirectX 9.0 SDK Update (October 2004)

MeshTextureCoords

Defines a mesh's texture coordinates.

        template MeshTextureCoords
        {
            < F6F23F40-7686-11cf-8F52-0040333594A3 >
            DWORD nTextureCoords;
            array Coords2d textureCoords[nTextureCoords] ;
        }

Where:

  • nTextureCoords - Number of texture coordinates.
  • array Coords2d textureCoords[nTextureCoords] - Array of 2-D texture coordinates. See Coords2d.


MeshVertexColors
Microsoft DirectX 9.0 SDK Update (October 2004)

MeshVertexColors

Specifies vertex colors for a mesh, instead of applying a material per face or per mesh.

        template MeshVertexColors
        {
            <1630B821-7842-11cf-8F52-0040333594A3>
            DWORD nVertexColors;
            array IndexColor vertexColors[nVertexColors];
        }

Where:

  • nVertexColors - Number of colors. This matches the number of vertices in the mesh.
  • array IndexColor vertexColors[nVertexColors] - Array of indexed colors. See IndexedColor.


Patch
Microsoft DirectX 9.0 SDK Update (October 2004)

Patch

Defines a Bézier control patch. The array defines the control points for the patch.

        template Patch
        {
            < A3EB5D44-FC22-429D-9AFB-3221CB9719A6 >
            DWORD nControlIndices;
            array DWORD controlIndices[nControlIndices];
        }

Where:

  • nControlIndices - Number of control point indices.
  • array DWORD controlIndices[nControlIndices] - Array of control point indices.

The type of patch is defined by the number of control points, as shown in the following table.

Number of control points | Type
10 | Cubic Bézier triangular patch
15 | Quartic Bézier triangular patch
16 | Cubic Bézier quad rectangle patch

The order of the control points are given in a spiral pattern, as shown in the following diagrams for triangular and rectangular patches.

Triangular patches used the following pattern.

Rectangular patches use the following pattern.


PatchMesh
Microsoft DirectX 9.0 SDK Update (October 2004)

PatchMesh

Defines a mesh defined by Bézier patches. The first array is a list of vertices, and the second array defines the patches for the mesh by indexing into the vertex array.

        template PatchMesh
        {
            < D02C95CC-EDBA-4305-9B5D-1820D7704BBF >
            DWORD nVertices;
            array Vector vertices[nVertices];
            DWORD nPatches;
            array Patch patches[nPatches];
            [ ... ]
        }

Where:

  • nVertices - Number of vertices.
  • vertices[nVertices] - Array of vertices. See Vector.
  • nPatches - Number of patches.
  • patches[nPatches] - Array of patches. See Patch.
  • [ ... ] - Any .x file template can be used here. This makes the architecture extensible.

The patches use the vertices in the array of vertices as the control points for each patch. This is a legacy template. The latest patch mesh template is PatchMesh9.


PatchMesh9
Microsoft DirectX 9.0 SDK Update (October 2004)

PatchMesh9

Defines a mesh defined by Bézier patches. The first array is a list of vertices, and the second array defines the patches for the mesh by indexing into the vertex array.

        template PatchMesh9
        {
            < B9EC94E1-B9A6-4251-BA18-94893F02C0EA >
            DWORD Type;
            DWORD Degree;
            DWORD Basis;
            DWORD nVertices;
            array Vector vertices[nVertices];
            DWORD nPatches;
            array Patch patches[nPatches];
            [ ... ]
        }

Where:

  • Type - Patch mesh type: rectangle, triangle, or N-patch.
  • Degree - Degree of the variables in the curve equation.
  • Basis - Basis type of a high-order patch surface.
  • nVertices - Number of vertices.
  • vertices[nVertices] - Array of vertices. See Vector.
  • nPatches - Number of patches.
  • patches[nPatches] - Array of patches. See Patch.
  • [ ... ] - Any .x file template can be used here. This makes the architecture extensible.

The patches use the vertices in the array of vertices as the control points for each patch.


PMAttributeRange
Microsoft DirectX 9.0 SDK Update (October 2004)

PMAttributeRange

Not supported. Used internally by Microsoft DirectX to represent and save a progressive mesh. This template should be used only with D3DX functions to read and write .x files.

        template PMAttributeRange
        {
            < 917E0427-C61E-4a14-9C64-AFE65F9E9844 >
            DWORD iFaceOffset;
            DWORD nFacesMin;
            DWORD nFacesMax;
            DWORD iVertexOffset;
            DWORD nVerticesMin;
            DWORD nVerticesMax;
        }


PMInfo
Microsoft DirectX 9.0 SDK Update (October 2004)

PMInfo

Not supported. Used internally by Microsoft DirectX.

        template PMInfo
        {
            < B6C3E656-EC8B-4b92-9B62-681659522947 >
            DWORD nAttributes;
            array PMAttributeRange attributeRanges[nAttributes];
            DWORD nMaxValence;
            DWORD nMinLogicalVertices;
            DWORD nMaxLogicalVertices;
            DWORD nVSplits;
            array PMVSplitRecord splitRecords[nVSplits];
            DWORD nAttributeMispredicts;
            array DWORD attributeMispredicts[nAttributeMispredicts];
        }


PMVSplitRecord
Microsoft DirectX 9.0 SDK Update (October 2004)

PMVSplitRecord

Not supported. Used internally by Microsoft DirectX.

        template PMVSplitRecord
        {
            < 574CCC14-F0B3-4333-822D-93E8A8A08E4C >
            DWORD iFaceCLW;
            DWORD iVlrOffset;
            DWORD iCode;
        }


SkinWeights
Microsoft DirectX 9.0 SDK Update (October 2004)

SkinWeights

This template is instantiated on a per-mesh basis. Within a mesh, a sequence of n instances of this template will appear, where n is the number of bones (X file frames) that influence the vertices in the mesh. Each instance of the template basically defines the influence of a particular bone on the mesh. There is a list of vertex indices, and a corresponding list of weights.

        template SkinWeights
        {
            < 6F0D123B-BAD2-4167-A0D0-80224F25FABB >
            STRING transformNodeName;
            DWORD nWeights;
            array DWORD vertexIndices[nWeights];
            array float weights[nWeights];
            Matrix4x4 matrixOffset;
        }

Where:

  • The name of the bone whose influence is being defined is transformNodeName, and nWeights is the number of vertices affected by this bone.
  • The vertices influenced by this bone are contained in vertexIndices, and the weights for each of the vertices influenced by this bone are contained in weights.
  • The matrix matrixOffset transforms the mesh vertices to the space of the bone. When concatenated to the bone's transform, this provides the world space coordinates of the mesh as affected by the bone. See Matrix4x4.


TextureFilename
Microsoft DirectX 9.0 SDK Update (October 2004)

TextureFilename

Enables you to specify the file name of a texture to apply to a mesh or a face. This template should appear within a material object.

        template TextureFilename
        {
            < A42790E1-7810-11cf-8F52-0040333594A3 >
            string filename;
        }


TimedFloatKeys
Microsoft DirectX 9.0 SDK Update (October 2004)

TimedFloatKeys

Defines a set of floats and a positive time used in animations.

        template TimedFloatKeys
        {
            < F406B180-7B3B-11cf-8F52-0040333594A3 >
            DWORD time;
            FloatKeys tfkeys;
        }

Where:

  • tfkeys - See FloatKeys.


Vector
Microsoft DirectX 9.0 SDK Update (October 2004)

Vector

Defines a vector.

        template Vector
        {
            < 3D82AB5E-62DA-11cf-AB39-0020AF71E433 >
            float x;
            float y;
            float z;
        }


VertexDuplicationIndices
Microsoft DirectX 9.0 SDK Update (October 2004)

VertexDuplicationIndices

This template is instantiated on a per-mesh basis, holding information about which vertices in the mesh are duplicates of each other. Duplicates result when a vertex sits on a smoothing group or material boundary. The purpose of this template is to allow the loader to determine which vertices exhibiting different peripheral parameters are actually the same vertexes in the model. Certain applications (mesh simplification, for example) can make use of this information.

        template VertexDuplicationIndices
        {
            < B8D65549-D7C9-4995-89CF-53A9A8B031E3 >
            DWORD nIndices;
            DWORD nOriginalVertices;
            array DWORD indices[nIndices];
        }

Where:

  • nIndices - Number of vertex indices. This is the number of vertices in the mesh.
  • nOriginalVertices - Number of vertices in the mesh before any duplication occurs.
  • The value indices[n] holds the vertex index that vertex[n] in the vertex array for the mesh would have had if no duplication had occurred. Indices in this array that are the same, therefore, indicate duplicate vertices.


VertexElement
Microsoft DirectX 9.0 SDK Update (October 2004)

VertexElement

Describes an individual vertex element in a vertex declaration.

        template VertexElement
        {
            < F752461C-1E23-48f6-B9F8-8350850F336F >
            DWORD Type;
            DWORD Method;
            DWORD Usage;
            DWORD UsageIndex;
        }

Where:

  • Type - Vertex data type. See D3DDECLTYPE.
  • Method - Tessellator processing method. See D3DDECLMETHOD.
  • Usage - Intended use of the vertex data. See D3DDECLUSAGE.
  • UsageIndex - Modifies the usage data. See D3DDECLUSAGE.

Related Topics

  • D3DVERTEXELEMENT9


XSkinMeshHeader
Microsoft DirectX 9.0 SDK Update (October 2004)

XSkinMeshHeader

This template is instantiated on a per-mesh basis only in meshes that contain exported skinning information. The purpose of this template is to provide information about the nature of the skinning information that was exported.

        template XSkinMeshHeader
        {
            < 3CF169CE-FF7C-44ab-93C0-F78F62D172E2 >
            WORD nMaxSkinWeightsPerVertex;
            WORD nMaxSkinWeightsPerFace;
            WORD nBones;
        }

Where:

  • nMaxSkinWeightsPerVertex - Maximum number of transforms that affect a vertex in the mesh.
  • nMaxSkinWeightsPerFace - Maximum number of unique transforms that affect the three vertices of any face.
  • nBones - Number of bones that affect vertices in this mesh.


DDS File Reference
Microsoft DirectX 9.0 SDK Update (October 2004)

DDS File Reference

The Microsoft DirectDraw Surface (.dds) file format is used to store textures and cubic environment maps, both with and without mipmap levels. This format can store uncompressed and compressed pixel formats, and is the preferred file format for storing DXTn compressed data. This file format is supported by the Microsoft DirectX Texture tool (DXTex), as well as some non-Microsoft tools, and by the D3DX library.

This format was introduced with DirectX 7.0. In DirectX 8.0, support for volume textures was added.

  • File Layout
  • Surface Format Header

File Layout

The basic structure of a .dds file is a header, and one or more surfaces written to a binary file. The header consists of a four-character code (FOURCC) and a DDSURFACEDESC2 structure. This header contains all the information needed to determine the contents of the entire file. The image below shows the layout of a .dds file.

DDS file format layout

Surface Format Header

The DDSURFACEDESC2 structure describes the file contents using the standard flags and values defined in the DirectDraw documentation, but files should use a restricted set of values to ensure full compatibility. A robust reader should verify key values and a robust writer should ensure all required flags are set for the different fields and options to ensure easy loading by the application or other tool. Also, a robust reader should not use a field unless the corresponding flag is set, and a robust writer should set all undefined fields to 0.

The table below shows the members of the DDSURFACEDESC2 structure.

Member | Description
DWORD dwSize | Size of structure. This member must be set to 124.
DWORD dwFlags | Flags to indicate valid fields. Always include DDSD_CAPS, DDSD_PIXELFORMAT, DDSD_WIDTH, DDSD_HEIGHT.
DWORD dwHeight | Height of the main image in pixels
DWORD dwWidth | Width of the main image in pixels
DWORD dwPitchOrLinearSize | For uncompressed formats, this is the number of bytes per scan line (DWORD> aligned) for the main image. dwFlags should include DDSD_PITCH in this case. For compressed formats, this is the total number of bytes for the main image. dwFlags should be include DDSD_LINEARSIZE in this case.
DWORD dwDepth | For volume textures, this is the depth of the volume. dwFlags should include DDSD_DEPTH in this case.
DWORD dwMipMapCount | For items with mipmap levels, this is the total number of levels in the mipmap chain of the main image. dwFlags should include DDSD_MIPMAPCOUNT in this case.
DWORD dwReserved1[11] | Unused
DDPIXELFORMAT ddpfPixelFormat | 32-byte value that specifies the pixel format structure.
DDCAPS2 ddsCaps | 16-byte value that specifies the capabilities structure.
DWORD dwReserved2 | Unused

Note that the field names used in this description do not correspond exactly with the DDSURFACEDESC2 fields due to the restrictions placed on the .dds file format, but a standard DDSURFACEDESC2 structure can and should be used. Use the magic DDS value and the header dwSize value to validate the file.

The pixel format of the image is given in the ddpfPixelFormat field of the header, and can describe all the formats supported by Microsoft Direct3D. DDS files are usually restricted to either RGB or FOURCC formats, and the use of other formats is not generally supported. Restrict usage to RGB formats A8R8G8B8, A1R5G5B5, A4R4G4B4, R8G8B8, R5G6B5; and FOURCC formats DXT1, DXT2, DXT3, DXT4, and DXT5 to ensure the best support. A well-written reader should handle more formats, if possible.

The following table shows the layout of the DDPIXELFORMAT structure.

Member | Description
DWORD dwSize | Size of structure. This member must be set to 32.
DWORD dwFlags | Flags to indicate valid fields. Uncompressed formats will usually use DDPF_RGB to indicate an RGB format, while compressed formats will use DDPF_FOURCC with a four-character code.
DWORD dwFourCC | This is the four-character code for compressed formats. dwFlags should include DDPF_FOURCC in this case. For DXTn compression, this is set to "DXT1", "DXT2", "DXT3", "DXT4", or "DXT5".
DWORD dwRGBBitCount | For RGB formats, this is the total number of bits in the format. dwFlags should include DDPF_RGB in this case. This value is usually 16, 24, or 32. For A8R8G8B8, this value would be 32.
DWORD dwRBitMask DWORD dwGBitMask DWORD dwBBitMask | For RGB formats, these three fields contain the masks for the red, green, and blue channels. For A8R8G8B8, these values would be 0x00ff0000, 0x0000ff00, and 0x000000ff respectively.
DWORD dwRGBAlphaBitMask | For RGB formats, this contains the mask for the alpha channel, if any. dwFlags should include DDPF_ALPHAPIXELS in this case. For A8R8G8B8, this value would be 0xff000000.

The final details of the format are inferred from the capabilities bits set in the ddsCaps field of the header. The layout of the ddsCaps structure is shown in the table below.

Member | Description
DWORD dwCaps1 | DDS files should always include DDSCAPS_TEXTURE. If the file contains mipmaps, DDSCAPS_MIPMAP should be set. For any .dds file with more than one main surface, such as a mipmaps, cubic environment map, or volume texture, DDSCAPS_COMPLEX should also be set.
DWORD dwCaps2 | For cubic environment maps, DDSCAPS2_CUBEMAP should be included as well as one or more faces of the map (DDSCAPS2_CUBEMAP_POSITIVEX, DDSCAPS2_CUBEMAP_NEGATIVEX, DDSCAPS2_CUBEMAP_POSITIVEY, DDSCAPS2_CUBEMAP_NEGATIVEY, DDSCAPS2_CUBEMAP_POSITIVEZ, DDSCAPS2_CUBEMAP_NEGATIVEZ). For volume textures, DDSCAPS2_VOLUME should be included.
DWORD Reserved[2] | Unused

Note that as of DirectX 8.0, cubic environment maps are always written with all faces defined.

  • DDS File Layout for Textures
  • DDS File Layout for Cubic Environment Maps
  • DDS File Layout for Volume Textures
  • DDS Bit Flag Values


DDS File Layout for Textures
Microsoft DirectX 9.0 SDK Update (October 2004)

DDS File Layout for Textures

For simple uncompressed textures, the file should contain DDSD_PITCH and a DDPF_RGB pixel format surface. The pitch value should be DWORD-aligned. In this case, the main image should be (dwPitchOrLinearSize-by-dwHeight) bytes total.

If the file also contains mipmaps, the DDSD_MIPMAPCOUNT, DDSCAPS_MIPMAP, and DDSCAPS_COMPLEX flags should be set, and the dwMipMapCount field should contain the total number of levels defined in the file (for a 256-by-256 image, this field would be 9). The pitch for each mipmap-level image is computed from dwWidth and the pixel format, which is then DWORD-aligned. For example, a 256-by-256 main image, with a pixel format of R8G8B8 (three bytes per pixel) and all mipmap levels, would contain the following:

Texture Size/Type | # Bytes
"DDS", 256x256, pitch=768, R8G8B8, 24 bits, mipmapcount = 9, (TEXTURE, PITCH, COMPLEX, MIPMAP, RGB) | 128
256-by-256 main image | 196608
128-by-128 mipmap image | 49152
64-by-64 mipmap image | 12288
32-by-32 mipmap image | 3072
16-by-16 mipmap image | 768
8-by-8 mipmap image | 192
4-by-4 mipmap image | 48
2-by-2 mipmap image | 12
1-by-1 mipmap image | 4

For simple compressed textures, the file should contain DDSD_LINEARSIZE and a DDPF_FOURCC pixel format surface. In this case, the image should be dwPitchOrLinearSize bytes total. If the file contains mipmaps, the DDSD_MIPMAPCOUNT, DDSCAPS_COMPLEX, DDSCAPS_MIPMAP, and dwMipMapCount fields should be set.

For DXTn compressed formats, the size of each mipmap level image is one-fourth the size of the previous, with a minimum of 8 (DXT1) or 16 (DXT2-5) bytes (this is true only for square textures). For example, a 256-by-256 main image, with a pixel format of DXT1 and all mipmap levels, would contain the following:

Texture Size/Type | # Bytes
DDS, 256x256, linearsize = 32768, 128 bytes DXT1, mipmapcount = 9, (TEXTURE, LINEARSIZE, COMPLEX, MIPMAP, FOURCC) | 128
256-by-256 main image | 32768
128-by-128 mipmap image | 8192
64-by-64 mipmap image | 2048
32-by-32 mipmap image | 512
16-by-16 mipmap image | 128
8-by-8 mipmap image | 32
4-by-4 mipmap image | 8
2-by-2 mipmap image | 8
1-by-1 mipmap image | 8

If mipmaps are generated, all levels down to 1-by-1 are usually written. Some tools may not support partial mipmap chains.

When computing DXTn compressed sizes for non-square textures, the following formula should be used at each mipmap level:

max(1, width ÷ 4) x max(1, height ÷ 4) x 8(DXT1) or 16(DXT2-5)

A 256-by-64 main image, with a pixel format of DXT1 and all mipmap levels, would contain the following:

Texture Size/Type | # Bytes
"DDS ", 256x64, linearsize = 8192, DXT1, mipmapcount = 9, (TEXTURE, LINEARSIZE, COMPLEX, MIPMAP, FOURCC) | 128 bytes
256-by-64 main image | 8192
128-by-32 mipmap image | 2048
64-by-16 mipmap image | 512
32-by-8 mipmap image | 128
16-by-4 mipmap image | 32
8-by-2 mipmap image | 16
4-by-1 mipmap image | 8
2-by-1 mipmap image | 8
1-by-1 mipmap image | 8


DDS File Layout for Cubic Environment Maps
Microsoft DirectX 9.0 SDK Update (October 2004)

DDS File Layout for Cubic Environment Maps

For cubic environment maps, one or more faces of a cube are written to the file, using either uncompressed or compressed formats, and all faces must be the same size. Each face can have mipmaps defined, although all faces must have the same number of mipmap levels. If a file contains a cube map, DDSCAPS_COMPLEX, DDSCAPS2_CUBEMAP, and one or more of DSCAPS2_CUBEMAP_POSITIVEX/Y/Z and/or DDSCAPS2_CUBEMAP_NEGATIVEX/Y/Z should be set. The faces are written in the order: positive x, negative x, positive y, negative y, positive z, negative z, with any missing faces omitted. Each face is written with its main image, followed by any mipmap levels.

For example, a 256-by-256 cube map with positive x, negative y, and positive z faces, a pixel format of DXT1, and all mipmap levels would contain the following:

Texture Size/Type | # Bytes
"DDS ", 256x256, linearsize = 32768, DXT1, 128, (TEXTURE, LINEARSIZE, COMPLEX, MIPMAP, CUBEMAP, POSITIVEX, NEGATIVEY, POSITIVEZ, FOURCC) |
256-by-256 positive x main image | 32768
128-by-128 positive x mipmap image | 8192
64-by-64 positive x mipmap image | 2048
32-by-32 positive x mipmap image | 512
16-by-16 positive x mipmap image | 128
8-by-8 positive x mipmap image | 32
4-by-4 positive x mipmap image | 8
2-by-2 positive x mipmap image | 8
1-by-1 positive x mipmap image | 8
256-by-256 negative y main image | 32768
128-by-128 negative y mipmap image | 8192
64-by-64 negative y mipmap image | 2048
32-by-32 negative y mipmap image | 512
16-by-16 negative y mipmap image | 128
8-by-8 negative y mipmap image | 32
4-by-4 negative y mipmap image | 8
2-by-2 negative y mipmap image | 8
1-by-1 negative y mipmap image | 8
256-by-256 positive z main image | 32768
128-by-128 positive z mipmap image | 8192
64-by-64 positive z mipmap image | 2048
32-by-32 positive z mipmap image | 512
16-by-16 positive z mipmap image | 128
8-by-8 positive z mipmap image | 32
4-by-4 positive z mipmap image | 8
2-by-2 positive z mipmap image | 8
1-by-1 positive z mipmap image | 8

Note As of Microsoft DirectX 8.0, cube maps are always written with all faces defined.


DDS File Layout for Volume Textures
Microsoft DirectX 9.0 SDK Update (October 2004)

DDS File Layout for Volume Textures

A volume texture is an extension of the standard texture for Microsoft DirectX 9.0.x, and can be defined with or without mipmaps. If a file contains a volume texture, DDSCAPS_COMPLEX, DDSCAPS2_VOLUME, DDSD_DEPTH, and dwDepth should be set. For volumes without mipmaps, each depth slice is written to the file in order. If mipmaps are included, all depth slices for a given mipmap level are written together, with each level containing half as many slices as the previous level with a minimum of 1. Volume textures do not support DXTn compression as of DirectX 9.0.

For example, a 64-by-64-by-4 volume map, a pixel format of R8G8B8 (3 bytes per pixel), and all mipmap levels would contain the following:

Texture Size/Type | # Bytes
"DDS ", 64x64x4, pitch=768, pixel format=R8G8B8, bitcount=24, mipmapcount=7, (DEPTH, TEXTURE, PITCH, COMPLEX, MIPMAP, VOLUME, RGB) | 128 bytes
64-by-64 slice 1 of 4 main image. | 12288 bytes
64-by-64 slice 2 of 4 main image. | 12288 bytes
64-by-64 slice 3 of 4 main image. | 12288 bytes
64-by-64 slice 4 of 4 main image. | 12288 bytes
32-by-32 slice 1 of 2 mipmap image. | 3072 bytes
32-by-32 slice 2 of 2 mipmap image. | 3072 bytes
16-by-16 slice 1 of 1 mipmap image. | 768 bytes
8-by-8 slice 1 of 1 mipmap image. | 192 bytes
4-by-4 slice 1 of 1 mipmap image. | 48 bytes
2-by-2 slice 1 of 1 mipmap image. | 12 bytes
1-by-1 slice 1 of 1 mipmap image. | 4 bytes


DDS Bit Flag Values
Microsoft DirectX 9.0 SDK Update (October 2004)

DDS Bit Flag Values

A number of fields make use of the standard Microsoft DirectDraw bit flags. Those that are used for DirectDraw surface (DDS) files are included here for reference.

The dwFlags member of the original DDSURFACEDESC2 structure can be set to one or more of the following values:

Flag | Value
DDSD_CAPS | 0x00000001
DDSD_HEIGHT | 0x00000002
DDSD_WIDTH | 0x00000004
DDSD_PITCH | 0x00000008
DDSD_PIXELFORMAT | 0x00001000
DDSD_MIPMAPCOUNT | 0x00020000
DDSD_LINEARSIZE | 0x00080000
DDSD_DEPTH | 0x00800000

The ddpfPixelFormat member of the DDSURFACEDESC2 structure can be set to one or more of the following values:

Flag | Value
DDPF_ALPHAPIXELS | 0x00000001
DDPF_FOURCC | 0x00000004
DDPF_RGB | 0x00000040

The dwCaps1 member of the DDSCAPS2 structure can be set to one or more of the following values:

Flag | Value
DDSCAPS_COMPLEX | 0x00000008
DDSCAPS_TEXTURE | 0x00001000
DDSCAPS_MIPMAP | 0x00400000

The dwCaps2 member of the DDSCAPS2 structure can be set to one or more of the following values:

Flag | Value
DDSCAPS2_CUBEMAP | 0x00000200
DDSCAPS2_CUBEMAP_POSITIVEX | 0x00000400
DDSCAPS2_CUBEMAP_NEGATIVEX | 0x00000800
DDSCAPS2_CUBEMAP_POSITIVEY | 0x00001000
DDSCAPS2_CUBEMAP_NEGATIVEY | 0x00002000
DDSCAPS2_CUBEMAP_POSITIVEZ | 0x00004000
DDSCAPS2_CUBEMAP_NEGATIVEZ | 0x00008000
DDSCAPS2_VOLUME | 0x00200000


DirectInput
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectInput

This section provides information about the Microsoft DirectInput component of the Microsoft DirectX application programming interface (API). The DirectInput API is used to process data from a keyboard, mouse, joystick, or other game controller.

Roadmap

Information on using DirectInput is presented in the following sections. Use this page to guide you through the documentation based on your level of experience as a DirectInput developer.

What's New in DirectInput. Summary of features new to this version of DirectX. Read this section if you've used DirectInput before but want to take advantage of the new capabilities.

Introduction to DirectInput. High-level overview of the capabilities of DirectInput and the steps you'll take to implement it. Start with this section if you're new to DirectInput.

Understanding DirectInput. Introduction to the objects and interfaces of DirectInput and how they are related to the Microsoft Windows message system. Read this section if you're new to DirectInput.

Using DirectInput. Guide to the API. This section contains more detailed conceptual information than the previous two sections, as well as information about the API elements you'll use for setting up devices, retrieving data, and implementing force-feedback effects. If you're a novice, at least familiarize yourself with the contents of this section. Later, you can refer to topics as you need them. Use this section in conjunction with the DirectInput C/C++ Reference.

Programming Tips and Tools. Advanced programming topics and a guide to the DirectInput tools provided with the DirectX software development kit (SDK).

DirectInput C/C++ Tutorials. Step-by-step tutorials, often based on samples in the SDK. If you learn best from sample code, this is a good place to start after reading Introduction to DirectInput and Understanding DirectInput.

DirectInput C/C++ Samples. A guide to the DirectInput C/C++ samples included in the SDK, illustrating the use and capabilities of DirectInput.

DirectInput C/C++ Reference. Reference information for the API. Use this section when you need to know the details of an interface, method, structure, macro, or other element.


What's New in DirectInput
Microsoft DirectX 9.0 SDK Update (October 2004)

What's New in DirectInput

Version 9.0 primarily includes compatibility improvements for Microsoft DirectInput. There are no application programming interface (API) changes.

To learn more about new features in Microsoft DirectX, see What's New in DirectX 9.0 SDK Update (October 2004).

Note For important information about using IDirectInput8::ConfigureDevices within a Microsoft Direct3D 9.0 environment, see the IDirectInput8::ConfigureDevices Remarks.


Introduction to DirectInput
Microsoft DirectX 9.0 SDK Update (October 2004)

Introduction to DirectInput

Microsoft DirectInput is an application programming interface (API) for input devices including the mouse, keyboard, joystick, and other game controllers, as well as for force-feedback (input/output) devices.

This topic provides a brief overview of the capabilities of DirectInput and how to set it up in an application. It includes the following:

  • The Power of DirectInput
  • Getting Started with DirectInput

For a more comprehensive view of how DirectInput works, see Understanding DirectInput.

For a step-by-step guide to using the DirectInput API, see the following topics.

  • Using DirectInput
  • DirectInput C/C++ Tutorials

The Power of DirectInput

Apart from providing services for devices not supported by the Microsoft Win32 API, DirectInput gives faster access to input data by communicating directly with the hardware drivers rather than relying on Microsoft Windows messages.

DirectInput enables an application to retrieve data from input devices even when the application is in the background. It also provides full support for any type of input device, as well as for force feedback.

Through action mapping, applications can retrieve input data without needing to know what kind of device is being used to generate it.

The extended services and improved performance of DirectInput make it a valuable tool for games, simulations, and other real-time interactive applications running under Windows.

DirectInput does not provide any advantages for applications that use the keyboard for text entry or the mouse for navigation. For more information, see Interaction with Windows.

Getting Started with DirectInput

This topic is an overview of what is involved in setting up and using DirectInput in a simple application.

For details and examples of these steps, see Using DirectInput and DirectInput C/C++ Tutorials.

Note To understand DirectInput, it is essential to understand the following terms.
  • DirectInput object: The root DirectInput interface.
  • Device: A keyboard, mouse, joystick, or other input device.
  • DirectInputDevice object: Code representing a keyboard, mouse, joystick, or other input device.
  • Device object: Code representing a key, button, trigger, and so on found on a DirectInput device object. Also called device object instance.

The following steps represent a simple implementation of DirectInput in which the application takes responsibility for ascertaining what device object (button, axis, and so on) generated each item of data.

  1. Create the DirectInput object. You use methods of this object to enumerate devices and create DirectInput device objects.
  2. Enumerate devices. This is not an essential step if you intend to use only the system mouse or keyboard. To ascertain what other input devices are available on the user's system, have DirectInput enumerate them. Each time DirectInput finds a device that matches the criteria you set, it gives you the opportunity to examine the device's capabilities. It also retrieves a unique identifier that you can use to create a DirectInput device object representing the device.
  3. Create a DirectInputDevice object for each device you want to use. To do this, you need the unique identifier retrieved during enumeration. For the system mouse or keyboard, you can use a standard globally unique identifier (GUID).
  4. Set up the device. For each device, first set the cooperative level, which determines the way the device is shared with other applications or the system. You must also set the data format used for identifying device objects, such as buttons and axes, within data packets. If you intend to retrieve buffered data—that is, events rather than states—you also need to set a buffer size. Optionally, at this stage you can retrieve information about the device and tailor the application's behavior accordingly. You can also set properties such as the range of values returned by joystick axes.
  5. Acquire the device. At this stage you tell DirectInput that you are ready to receive data from the device.
  6. Retrieve data. At regular intervals, typically on each pass through the message loop or rendering loop, get either the current state of each device or a record of events that have taken place since the last retrieval. If you prefer, you can have DirectInput notify you whenever an event occurs.
  7. Act on the data. The application can respond either to the state of buttons and axes or to events such as a key being pressed or released.
  8. Close DirectInput. Before exiting, your application should unacquire all devices and release them, then release the DirectInput object.

This is not the only approach to implementing DirectInput. To take advantage of the great variety of input devices available now and later, and to simplify configuration for the user, you can use action mapping.

By setting an action map for a device, you let DirectInput decide which device object to use for each application action. For example, instead of specifying that the throttle in your racing game must always be controlled by the y-axis, you can create an action called AXIS_THROTTLE and have DirectInput assign that action to the most appropriate axis available on the device. When you retrieve events, you identify them by their associated actions rather than by the device objects that generated them.

For more information, see Action Mapping.


Understanding DirectInput
Microsoft DirectX 9.0 SDK Update (October 2004)

Understanding DirectInput

This topic covers the underlying structure of Microsoft DirectInput and its relationship to the Microsoft Windows message system.

  • DirectInput Objects
  • Interaction with Windows

For practical information about how to implement the elements of DirectInput introduced here, see Using DirectInput.

DirectInput Objects

An input-only DirectInput implementation consists of the DirectInput object, which supports the IDirectInput8 Component Object Model (COM) interface, and a DirectInputDevice object for each input device that provides data. Each DirectInputDevice object in turn has device objects, which are individual controls or switches such as keys, buttons, or axes. Device objects are also called device object instances.

Each DirectInputDevice object represents one input device, such as a mouse, keyboard, or joystick. In the DirectInput application programming interface (API), the word joystick means any type of input device other than a mouse or keyboard. A piece of hardware that is really a combination of different types of input devices, such as a keyboard with a touchpad, can be represented by two or more DirectInputDevice objects. A force-feedback device is represented by a single joystick object that handles both input and output.

DirectInputDevice objects instantiate the IDirectInputDevice8 interface. The application ascertains the number and type of device objects available by using the IDirectInputDevice8::EnumObjects method. Individual device objects are not encapsulated as code objects, but are described in DIDEVICEOBJECTINSTANCE structures.

Force-feedback effects are represented by the IDirectInputEffect interface. Methods of this interface are used to create, modify, start, and stop effects.

All DirectInput interfaces are available in ANSI and Unicode versions. If "UNICODE" is defined during compilation, the Unicode versions are used.

Interaction with Windows

Because DirectInput works directly with the device drivers, it either suppresses or ignores Windows mouse and keyboard messages. It also ignores mouse and keyboard settings made by the user in Control Panel. It does, however, use the calibrations set for a joystick or other game controller.

DirectInput does not recognize keyboard character repeat settings. When using buffered data, DirectInput interprets each press and release as a single event with no repetition. When using immediate data, DirectInput is concerned only with the present physical state of the keys, not with keyboard events as interpreted by Windows.

DirectInput does not perform any character conversion or translation. For example, the SHIFT key is treated like any other key, not as a modifier of another keypress. Keys return the same identifiers regardless of the user's system language settings.

Under Windows 2000, acquiring the keyboard in exclusive mode prevents any applications that are subsequently launched from receiving keyboard data.

Because DirectInput works directly with the mouse driver, it bypasses the subsystem of Windows that interprets mouse data for windowed applications. Applications that rely on the Windows cursor for navigation should continue to use the standard Windows mouse messages and Microsoft Win32 functions.

When using the system mouse in exclusive mode, DirectInput suppresses mouse messages, and therefore Windows is unable to show the standard cursor.

DirectInput ignores Control Panel settings such as acceleration and swapped buttons. However, DirectInput recognizes settings in the driver itself. For example, if the user has a three-button mouse and uses the driver-utility software to make the middle button a double-click shortcut, DirectInput reports a click of the middle button as two clicks of the primary button.


Using DirectInput
Microsoft DirectX 9.0 SDK Update (October 2004)

Using DirectInput

This topic is a guide to implementing Microsoft DirectX. It includes information about the following:

  • Creating DirectInput
  • DirectInput Device Enumeration

For a broader overview, see Understanding DirectInput.

For related information, see the following:

  • DirectInput Devices
  • DirectInput Device Data
  • Action Mapping
  • Force Feedback

Creating DirectInput

The first step in any Microsoft DirectInput application is obtaining the IDirectInput8 interface. You can do this most easily by calling the DirectInput8Create function.

You should create a single DirectInput object and not release it until the application terminates.

DirectInput Device Enumeration

DirectInput can query the system for all available input devices, determine whether they are connected, and return information about them. This process is called enumeration.

If your application is using only the standard keyboard or mouse, or both, you do not need to enumerate the available input devices. As explained under Creating a DirectInput Device, you can use predefined global variables when calling the IDirectInput8::CreateDevice method.

For all other input devices, and for systems with multiple keyboards or mouse devices, call IDirectInput8::EnumDevices or IDirectInput8::EnumDevicesBySemantics to enumerate available devices and find one that is suitable. You might also want to enumerate in order to give the user a choice of available devices.

The following is a sample implementation of the IDirectInput8::EnumDevices method:

/* lpdi is a valid IDirectInput8 interface pointer. */

GUID KeyboardGUID = GUID_SysKeyboard;

lpdi->EnumDevices(DIDEVTYPE_KEYBOARD,
                  DIEnumDevicesCallback,
                  &KeyboardGUID,
                  DIEDFL_ATTACHEDONLY);

The first parameter determines what types of devices are to be enumerated. It is NULL if you want to enumerate all devices, regardless of type; otherwise it is one of the DIDEVTYPE_* values described in DIDEVICEINSTANCE.

The second parameter is a pointer to a callback function to be called once for each device enumerated. This function can be declared by any name; the documentation uses the placeholder name DIEnumDevicesCallback.

The third parameter to the IDirectInput8::EnumDevices method is any 32-bit value that you want to pass into the callback function. In this example, it is a pointer to a variable of type globally unique identifier (GUID), passed in so that the callback can assign a keyboard instance identifier to this variable.

The fourth parameter is a flag to request enumeration of either all devices or only those that are attached to the user's computer (DIEDFL_ALLDEVICES or DIEDFL_ATTACHEDONLY).

If your application is using more than one input device, the callback function is a good place to initialize each device as it is enumerated. (For an example, see Tutorial 3: Using the Joystick.) You obtain the instance GUID of the device from the callback function. You can also perform other processing here, such as looking for particular subtypes of devices or adding the device name to a list box.

The following sample callback function checks for the presence of an enhanced keyboard and stops the enumeration as soon as it finds one. It assigns the instance GUID of the last keyboard found to the KeyboardGUID variable (the address of which was passed in the pvRef variable by the call to IDirectInput8::EnumDevices in the previous example), which can then be passed to IDirectInput8::CreateDevice.

BOOL  hasEnhanced;

BOOL CALLBACK DIEnumKbdCallback(LPCDIDEVICEINSTANCE lpddi,
                                LPVOID pvRef)
{
  *(GUID*) pvRef = lpddi->guidInstance;
  if (GET_DIDEVICE_SUBTYPE(lpddi->dwDevType) ==
                       DIDEVTYPEKEYBOARD_PCENH)
  {
    hasEnhanced = TRUE;
    return DIENUM_STOP;
  }
  return DIENUM_CONTINUE;
} // End of callback

The first parameter points to a DIDEVICEINSTANCE structure containing information about the device. This structure is created by DirectInput.

The second parameter points to data passed in from IDirectInput8::EnumDevices. In this case, it is a pointer to the variable KeyboardGUID. This variable was assigned a default value earlier, but it is given a new value each time a device is enumerated. It is not important what instance GUID you use for a single keyboard, but the code does illustrate a technique for retrieving an instance GUID from the callback.

Rather than saving the instance GUID so that you can create the DirectInputDevice later, you can save the device created by DirectInput during enumeration. For more information, see Creating a DirectInput Device.

The return value in the example indicates that enumeration is to stop if the sought-for device has been found, or continue otherwise. Enumeration automatically stops as soon as all devices have been enumerated.

For more information about enumerating devices by using IDirectInput8::EnumDevicesBySemantics, see Action Mapping.


DirectInput Devices
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectInput Devices

This section contains information about the code objects that represent devices such as a mouse, keyboards, or joysticks. The following topics are covered:

  • Acquiring Devices
  • Cooperative Levels
  • Creating a DirectInput Device
  • Device Capabilities
  • Device Data Formats
  • Device Object Enumeration
  • Device Properties
  • Device Setup

For information about how to retrieve and interpret data from devices, see DirectInput Device Data.


Acquiring Devices
Microsoft DirectX 9.0 SDK Update (October 2004)

Acquiring Devices

Acquiring a Microsoft DirectInput device means giving your application access to it. As long as a device is acquired, DirectInput is making its data available to your application. If the device is not acquired, you can manipulate its characteristics but not obtain any data.

Acquisition is not permanent. Your application might acquire and unacquire a device many times.

In certain cases, depending on the cooperative level, a device is unacquired automatically whenever the application moves to the background. The mouse is automatically unacquired when the user clicks a menu, because at this point Microsoft Windows assumes control of the device.

You must unacquire a device before changing its properties. The only exception is that you can change the gain for a force-feedback device while it is in an acquired state.

The acquisition mechanism is needed for two reasons:

First, DirectInput must be able to tell the application when the flow of data from the device has been interrupted by the system. For instance, if the user has switched to another application with ALT+TAB and has used the input device in that application, your application needs to know that the input no longer belongs to it and that the state of the buffers might have changed. Or consider an application with the DISCL_FOREGROUND cooperative level. The user holds down the SHIFT key and switches to another application. Then the user releases the key and switches back to the first application. As far as the first application is concerned, the SHIFT key is still down. The acquisition mechanism, by telling the application that input was lost, enables it to recover from these conditions.

Second, because your application can alter the properties of the device, without safeguards DirectInput would have to check the properties each time you wanted to retrieve data. This would be very inefficient. Even worse, a potential disaster could happen such as a hardware interrupt accessing a data buffer just as you were changing the buffer size. Therefore DirectInput requires your application to unacquire the device before changing properties. When you reacquire it, DirectInput checks the properties and decides on the optimal way of transferring data from the device to the application. This is done only once, so the data retrieval methods can be very fast.

Since the most common cause of losing a device is that your application moves to the background, you may want to reacquire devices whenever your application is activated. Be careful, though, about relying on a WM_ACTIVATE handler at startup time. The first WM_ACTIVATE message will likely arrive when your window is being initialized before DirectInput has been set up. To ensure that the device is acquired at startup, call IDirectInputDevice8::Acquire as soon as the device has been initialized.

Even acquiring the device on activation of your program window might not cover all cases in which a device is unacquired, especially for devices other than the standard mouse or keyboard. Because your application might unacquire a device unexpectedly, you need a mechanism for checking the acquisition state before attempting to get data from the device. The Scrawl Sample does this in the OnMouseInput function, in which a DIERR_INPUTLOST error triggers a message to reacquire the mouse. (See also Tutorial 2: Using the Mouse.)

Attempting to reacquire a device that is already acquired does no harm. Redundant calls to IDirectInputDevice8::Acquire are ignored, and the device can always be unacquired with a single call to IDirectInputDevice8::Unacquire.

Windows does not have access to the mouse when your application is using it in exclusive mode. If you want Windows to acquire the mouse, you must release it. The Scrawl Sample responds to a right-click by unacquiring the mouse, putting the Windows cursor in the same spot as its own, displaying a shortcut menu, and letting Windows handle the input until a menu choice is made.


Cooperative Levels
Microsoft DirectX 9.0 SDK Update (October 2004)

Cooperative Levels

The cooperative level of a device determines how the input is shared with other applications and with the Microsoft Windows system. You set it by using the IDirectInputDevice8::SetCooperativeLevel method, as in the following code example:

/* hwnd is the top-level window handle. */
lpdiDevice->SetCooperativeLevel(hwnd,
        DISCL_NONEXCLUSIVE | DISCL_FOREGROUND)

The parameters are the handle to the top-level window associated with the device (generally the application window) and one or more flags.

Although Microsoft DirectInput provides a default setting, you should still explicitly set the cooperative level because this is the only way to give DirectInput the window handle. Without this handle, DirectInput cannot react to situations that involve window messages, such as joystick recalibration.

The valid flag combinations are shown in the following table.

Flags | Notes
DISCL_NONEXCLUSIVE DISCL_BACKGROUND | The default setting
DISCL_NONEXCLUSIVE DISCL_FOREGROUND |
DISCL_EXCLUSIVE DISCL_FOREGROUND |
DISCL_EXCLUSIVE DISCL_BACKGROUND | Not valid for keyboard or mouse

For the keyboard, you can also include DISCL_NOWINKEY in combination with DISCL_NONEXCLUSIVE. This flag disables the Windows logo key so that users cannot inadvertently break out of the application. In exclusive mode, the Windows logo key is always disabled.

Note Even if the cooperative level for the application is disabling the Windows logo key passively through an exclusive cooperative level or actively through use of the DISCL_NOWINKEY flag, that key will be active while the default action mapping UI is displayed.

The cooperative level has two main components: whether the device is being used in the foreground or the background, and whether it is being used exclusively or nonexclusively.

Foreground vs. Background

A foreground cooperative level means that the input device is available only when the application is in the foreground or, in other words, has the input focus. If the application moves to the background, the device is automatically unacquired, or made unavailable.

A background cooperative level really means foreground and background. A device with a background cooperative level can be acquired and used by an application at any time.

You will usually want to have foreground access only, since most applications are not designed to respond to input that takes place when another program is in the foreground.

While developing an application, it is useful to employ conditional compilation so that the background cooperative level is always set for debugging. This prevents your application from losing access to the device every time it moves to the background as you switch to the debugging environment.

Exclusive vs. Nonexclusive

In most cases, the fact that your application is using a device at the exclusive level does not mean that other applications cannot get data from the device. Also, an application that requests background exclusive mode might lose access if another application requests exclusive access. The application can regain access to the device by manually unacquiring the device, and then reaquiring it.

Consider the example of a music player that accepts input from a hand-held remote-control device, even when the application is running in the background. Now suppose you run a similar application that plays movies in response to signals from the same remote control. What happens when the user presses Play? Both programs start playing, which is probably not what the user wants. To prevent this from happening, each application should have the DISCL_EXCLUSIVE flag set so that only one of them can be running at a time.

To use force-feedback effects, an application must have exclusive access to the device.

Windows itself requires exclusive access to the system mouse. The reason is that system mouse events, such as a click on an inactive window, could force an application to unacquire the device, with potentially harmful results such as a loss of data from the input buffer. So when an application has exclusive access to the system mouse, created by passing GUID_SysMouse to IDirectInput8::CreateDevice, Windows is not allowed any access and no mouse messages are generated. A further side effect is that the cursor disappears.


Creating a DirectInput Device
Microsoft DirectX 9.0 SDK Update (October 2004)

Creating a DirectInput Device

To get input data from a device, you first have to create an object to represent that device.

The IDirectInput8::CreateDevice method is used to obtain a pointer to the IDirectInputDevice8 interface. Methods of this interface are then used to manipulate the device and obtain data.

The following code example, where lpdi is a pointer to the IDirectInput8 interface, creates a keyboard device:

LPDIRECTINPUTDEVICE8  lpdiKeyboard;

lpdi->CreateDevice(GUID_SysKeyboard, &lpdiKeyboard, NULL);

The first parameter in IDirectInput8::CreateDevice is an instance globally unique identifier (GUID) that identifies the instance of the device for which the interface is to be created. Microsoft DirectInput has two predefined GUIDs, GUID_SysMouse and GUID_SysKeyboard, which represent the system mouse and keyboard. You can pass one of these identifiers into the IDirectInput8::CreateDevice method. The global variable GUID_Joystick should not be used as a parameter for IDirectInput8::CreateDevice because it is a product GUID, not an instance GUID.

Note If the computer has more than one mouse, input from all of them is combined to form the system device. The same is true for multiple keyboards.

DirectInput provides four other predefined GUIDs primarily for testing.

  • GUID_SysKeyboardEm

  • GUID_SysKeyboardEm2

  • GUID_SysMouseEm

  • GUID_SysMouseEm2.

Passing one of these GUIDs to IDirectInput8::CreateDevice grants access to the system keyboard or mouse through an emulation layer, at either level 1 or level 2. These GUIDs always represent the system mouse or keyboard. They are aliases for GUID_SysKeyboard and GUID_SysMouse, so they are not enumerated by IDirectInput8::EnumDevices or IDirectInput8::EnumDevicesBySemantics unless the DIEDFL_INCLUDEALIASES flag is passed.

For devices other than the system mouse or keyboard, use the instance GUID for the device returned by IDirectInput8::EnumDevices or IDirectInput8::EnumDevicesBySemantics. The instance GUID for a device is always the same. You can allow the user to select a device from a list of those enumerated, then save the GUID to a configuration file and use it again in later sessions.


Device Capabilities
Microsoft DirectX 9.0 SDK Update (October 2004)

Device Capabilities

Before you begin asking for input from a device, you need to know something about its capabilities. Does the joystick have a point-of-view hat? Is the mouse currently attached to the user's computer?

Such questions are answered with a call to the IDirectInputDevice8::GetCapabilities method, which returns the data in a DIDEVCAPS structure. As with other such structures in Microsoft DirectX, you must initialize the dwSize member before passing this structure to the method.

Note To optimize speed or memory usage, you can use the smaller DIDEVCAPS_DX3 structure instead. For structure details, see Dinput.h.

The following code example checks whether the mouse is attached and whether it has a third axis (presumably a wheel). Assume that lpdiMouse is a valid Microsoft DirectInput device.

DIDEVCAPS  DIMouseCaps;
HRESULT    hr;
BOOLEAN    WheelAvailable;

DIMouseCaps.dwSize = sizeof(DIDEVCAPS);
hr = lpdiMouse->GetCapabilities(&DIMouseCaps);
WheelAvailable = ((DIMouseCaps.dwFlags & DIDC_ATTACHED)
        && (DIMouseCaps.dwAxes > 2));

Another way to check for a button or axis is to call IDirectInputDevice8::GetObjectInfo for that object. If the call returns DIERR_OBJECTNOTFOUND, the object is not present. The following code determines whether there is a z-axis, even if it is not the third axis:

DIDEVICEOBJECTINSTANCE  didoi;

didoi.dwSize = sizeof(DIDEVICEOBJECTINSTANCE);
hr = lpdiMouse->GetObjectInfo(&didoi, DIMOFS_Z, DIPH_BYOFFSET);
WheelAvailable = SUCCEEDED(hr);


Device Data Formats
Microsoft DirectX 9.0 SDK Update (October 2004)

Device Data Formats

If you are not using Action Mapping, setting the data format for a device is an essential step before you can acquire and begin using the device. This is true even if you do not intend to retrieve immediate (state) data from the device. Microsoft DirectInput uses the data format in many methods to identify particular device objects.

The IDirectInputDevice8::SetDataFormat method tells DirectInput what device objects will be used and how the data will be arranged.

The examples in the reference for the DIDATAFORMAT and DIOBJECTDATAFORMAT structures show how to set up custom data formats for nonstandard devices. Fortunately, this step is not necessary for the joystick, keyboard, and mouse. DirectInput provides five global variables, c_dfDIJoystick, c_dfDIJoystick2, c_dfDIKeyboard, c_dfDIMouse, and c_dfDIMouse2, which can be passed in to IDirectInputDevice8::SetDataFormat to create a standard data format for these devices.

In the following code example, lpdiMouse is an initialized pointer to a DirectInputDevice object:

lpdiMouse->SetDataFormat(&c_dfDIMouse);
Note You cannot change the dwFlags member in the predefined DIDATAFORMAT global variables (for example, to change the property of an axis), because they are const variables. To change properties, use the IDirectInputDevice8::SetProperty method after setting the data format, but before acquiring the device.


Device Object Enumeration
Microsoft DirectX 9.0 SDK Update (October 2004)

Device Object Enumeration

It might be necessary for your application to determine what buttons or axes are available on a given device. To do this, you enumerate the device objects in much the same way as you enumerate devices.

Note Because of limitations imposed by device drivers, enumeration of keyboard keys and indicator lights is not reliable. Objects might falsely be reported as present. You can get basic information about available keys from the device subtype, but there is no way to determine whether extra objects such as the menu key are available, other than asking the user for input.

To some extent, IDirectInputDevice8::EnumObjects overlaps the functionality of IDirectInputDevice8::GetCapabilities. Either method can be used to determine how many buttons or axes are available. However, IDirectInputDevice8::EnumObjects is intended for cataloging all the available objects rather than checking for a particular one.

Like IDirectInput8::EnumDevices, the IDirectInputDevice8::EnumObjects method has a callback function that enables you to do other processing on each object—for example, adding it to a list or creating a corresponding element on a user interface.

The following sample callback extracts the name of each object so that it can be added to a string list or array. This standard callback is documented under the placeholder name DIEnumDeviceObjectsCallback, but you can give it any name you like. Remember, this function is called once for each object enumerated.

char  szName[MAX_PATH];

BOOL CALLBACK DIEnumDeviceObjectsCallback(
                      LPCDIDEVICEOBJECTINSTANCE lpddoi,
                      LPVOID pvRef)
{
  HRESULT hr = StringCchCopy(szName, MAX_PATH, lpddoi->tszName);
  if(SUCCEEDED(hr))
  {
     // Now add szName to a list or array.
     .
     .
     .
  }
  else
     // Handle errors.

  return DIENUM_CONTINUE;
}

The first parameter points to a structure containing information about the object. This structure is created for you by Microsoft DirectInput.

The second parameter is an application-defined pointer to data, equivalent to the second parameter to IDirectInputDevice8::EnumObjects. In the example, this parameter is not used.

The return value in this case indicates that enumeration is to continue as long as there are objects to be enumerated.

Now here's the call to the IDirectInputDevice8::EnumObjects method, which puts the callback function to work.

lpdiMouse->EnumObjects(DIEnumDeviceObjectsCallback,
                       NULL, DIDFT_ALL);

The first parameter is the address of the callback function. The second parameter can be a pointer to any data you want to use or modify in the callback. The example does not use this parameter and so passes NULL. The third parameter is a flag to indicate which type or types of objects are to be included in the enumeration. In the example, all objects are to be enumerated. To restrict the enumeration, you can use one or more of the other DIDFT_* flags listed at IDirectInputDevice8::EnumObjects.

Note Some of the DIDFT_* flags are combinations of others; for example, DIDFT_AXIS is equivalent to DIDFT_ABSAXIS | DIDFT_RELAXIS.

When an application has exclusive access to the keyboard, DirectInput suppresses all keyboard messages except CTRL+ALT+DEL and, on Microsoft Windows 95 and Windows 98, ALT+TAB. Under Windows 2000, no application launched subsequently to the exclusive-mode DirectInput application can get keyboard data.


Device Properties
Microsoft DirectX 9.0 SDK Update (October 2004)

Device Properties

Properties of Microsoft DirectInput devices include the size of the data buffer, the range and granularity of values returned from an axis, whether axis data is relative or absolute, and the dead zone and saturation values for a joystick axis. Specialized devices can have other properties as well. For a list of properties defined by DirectInput, see IDirectInputDevice8::GetProperty.

With one exception—the gain property of a force-feedback device—properties can be changed only when the device is in an unacquired state.

Before calling the IDirectInputDevice8::SetProperty or the IDirectInputDevice8::GetProperty method you must set up a property structure that consists of a DIPROPHEADER structure and one or more elements for data. There is potentially a great variety of properties for input devices, and IDirectInputDevice8::SetProperty must be able to work with all sorts of structures defining those properties. The purpose of the DIPROPHEADER structure is to define the size of the property structure and how the data is to be interpreted.

DirectInput includes the following predefined property structures:

  • DIPROPDWORD defines a structure containing a DIPROPHEADER and a DWORD data member for properties that require a single value, such as a buffer size.
  • DIPROPRANGE is for range properties, which require two values (maximum and minimum). It consists of a DIPROPHEADER and two LONG data members.
  • DIPROPGUIDANDPATH is a specialized property structure that enables applications to perform operations on a Human Interface Device (HID) that is not supported by DirectInput. The structure consists of a DIPROPHEADER, a globally unique identifier (GUID), and a Unicode string for the path.
  • DIPROPSTRING is for Unicode string properties. The structure comprises a DIPROPHEADER and a Unicode string.

For IDirectInputDevice8::SetProperty, the data members of the property structure are the values that you want to set. For IDirectInputDevice8::GetProperty, the current value is returned in these members.

Before the call to IDirectInputDevice8::GetProperty or IDirectInputDevice8::SetProperty, the DIPROPHEADER structure must be initialized with the following:

  • The size of the property structure.
  • The size of the DIPROPHEADER structure itself.
  • An object identifier.
  • A value indicating how the object identifier should be interpreted.

When getting or setting properties for a whole device, the object identifier dwObj is 0, and the dwHow member is DIPH_DEVICE. If you want to get or set properties for a device object (for example, a particular axis), the combination of dwObj and dwHow values identifies the object. For details, see DIPROPHEADER.

After setting up the property structure, pass the address of its header into IDirectInputDevice8::GetProperty or IDirectInputDevice8::SetProperty, along with an identifier for the property that you want to obtain or change.

The following values are used to identify the property passed to IDirectInputDevice8::SetProperty and IDirectInputDevice8::GetProperty.

  • DIPROP_BUFFERSIZE. See also Buffered and Immediate Data. The buffer size can also be set by using the IDirectInputDevice8::SetActionMap method.
  • DIPROP_AXISMODE. See also Relative and Absolute Axis Coordinates.
  • DIPROP_CALIBRATIONMODE
  • DIPROP_GRANULARITY
  • DIPROP_FFGAIN
  • DIPROP_FFLOAD
  • DIPROP_AUTOCENTER
  • DIPROP_RANGE
  • DIPROP_DEADZONE
  • DIPROP_SATURATION

For more information about the last three properties, see also Interpreting Joystick Axis Data.

The following code example sets the buffer size for a device to hold up to 10 data items:

DIPROPDWORD  dipdw;
HRESULT      hr;
dipdw.diph.dwSize = sizeof(DIPROPDWORD);
dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
dipdw.diph.dwObj = 0;
dipdw.diph.dwHow = DIPH_DEVICE;
dipdw.dwData = 10;
hr = lpdiDevice->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph);


Device Setup
Microsoft DirectX 9.0 SDK Update (October 2004)

Device Setup

Your application must obtain a Microsoft DirectInput device object for each device from which it expects input. It must also prepare each device for use, which requires, at the very least, setting the data format and acquiring the device. You might also want to carry out other preparatory tasks such as getting information about the devices and changing their properties.

The following tasks are part of the setup process. Certain steps are always required. Other steps may be necessary if you need further information about devices or need to change default values.

  1. Create the DirectInput device (required). See Creating a DirectInput Device.
  2. Get the device capabilities (optional).
  3. Enumerate the keys, buttons, and axes on the device (optional). See Device Object Enumeration.
  4. Set the cooperative level (highly recommended).
  5. Set the data format (required).
  6. Set the device properties (you must at least set the buffer size if you intend to get buffered data).
  7. When ready to read data, acquire the device (required). See Acquiring Devices.


DirectInput Device Data
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectInput Device Data

This section covers the following basic concepts of getting data from Microsoft DirectInput devices.

Overviews

  • Buffered and Immediate Data
  • Polling and Event Notification
  • Relative and Absolute Axis Coordinates
  • Time Stamps and Sequence Numbers

The following topics describe specific details about output data and mouse, keyboard, and joystick input data.

  • Joystick Data
  • Keyboard Data
  • Mouse Data
  • Output Data

DirectInput provides two mechanisms for identifying data retrieved from devices. Using the traditional mechanism, the application identifies the data as coming from a particular device object, such as a the x-axis on a mouse or the F1 key on a keyboard. With the newer system, available for the first time in Microsoft DirectX 8.0, DirectInput associates application-defined values (for instance, identifiers for particular game actions such as moving or shooting) with the most suitable device objects available. When data is retrieved, the application does not concern itself with the actual device or device object from which the data comes. It acts only on the meaning of that data.

Most of the information in this section applies to both mechanisms. For more information about the newer way of identifying device data, see Action Mapping.


Buffered and Immediate Data
Microsoft DirectX 9.0 SDK Update (October 2004)

Buffered and Immediate Data

Microsoft DirectInput supplies two types of data: buffered and immediate. Buffered data is a record of events that are stored until an application retrieves them. Immediate data is a snapshot of the current state of a device.

You might use immediate data in an application that is concerned only with the current state of a device—for example, a flight combat simulation that responds to the current position of the joystick and the state of one or more buttons. Buffered data might be the better choice where events are more important than states—for example, in an application that responds to movement of the mouse and button clicks. You can also use both types of data, as you might, for example, if you wanted to get immediate data for joystick axes but buffered data for the buttons.

Note If you are using Action Mapping, you will want to retrieve buffered data because the buffered data packets contain the application-defined data associated with the input. Doing so means that you are responsible for tracking the position of absolute axes, since events but not states are reported in buffered data packets.

An application retrieves immediate data by calling the IDirectInputDevice8::GetDeviceState method. As the name implies, this method returns the current state of the device—for example, whether each button is up or down. The method provides no data about what has happened with the device since the last call, apart from implicit information that you can derive by comparing the current state with the last one. For example, if a user presses and releases a button between two calls to IDirectInputDevice8::GetDeviceState, your application will never be given this input. On the other hand, if the user is holding a button down, IDirectInputDevice8::GetDeviceState continues reporting that fact until the user releases it.

This way of reporting the device state is different from the way Microsoft Windows reports events with one-time messages such as WM_LBUTTONDOWN. It is more like the results from the Microsoft Win32 GetKeyboardState function. If you are polling a device with IDirectInputDevice8::GetDeviceState, you are responsible for determining what constitutes a button click, a double-click, a single keystroke, and so on, and for ensuring that your application does not keep responding to a button-down or key-down state when it's not appropriate to do so.

With buffered data, events are stored until you are ready to deal with them. Every time a button or key is pressed or an axis is moved, information about the event is placed in a DIDEVICEOBJECTDATA structure in the buffer. If the buffer overflows, new data is lost. Your application reads the buffer with a call to IDirectInputDevice8::GetDeviceData. You can read any number of items at a time.

Reading an item normally deletes it from the buffer, but you also have the choice of peeking without deleting.

To get buffered data, you must first set the buffer size with the IDirectInputDevice8::SetProperty or IDirectInputDevice8::SetActionMap method. (See the example under Device Properties.) Set the buffer size before acquiring the device for the first time. For reasons of efficiency, the default size of the buffer is 0, and you cannot obtain buffered data unless you change this value. The size of the buffer is measured in items of data for that type of device, not in bytes.

Check the value of the pdwInOut parameter after a call to the IDirectInputDevice8::GetDeviceData method. The number of items retrieved from the buffer is returned in this variable.

Note For devices that do not generate interrupts, such as analog joysticks, DirectInput does not obtain any data until you call the IDirectInputDevice8::Poll method. For more information, see Polling and Event Notification.

For examples of retrieving buffered data, see IDirectInputDevice8::GetDeviceData.

See also:

  • Time Stamps and Sequence Numbers
  • Mouse Data
  • Keyboard Data
  • Joystick Data


Polling and Event Notification
Microsoft DirectX 9.0 SDK Update (October 2004)

Polling and Event Notification

There are two ways to find out whether input data is available: polling and event notification.

Polling a device means regularly getting the current state of the device objects or checking the contents of the event buffer. Polling is typically used by real-time games that are never idle, but instead are constantly updating and rendering the game world.

Polling

In a C++ application, polling would typically be done within the message loop.

Some joysticks and other game devices, or particular objects on them, do not generate hardware interrupts and do not return any data or signal any events until you call the IDirectInputDevice8::Poll method. (This behind-the-scenes polling is not to be confused with the kind of application polling just discussed. IDirectInputDevice8::Poll does not retrieve any data, but merely makes data available.)

To find out whether it is necessary to call IDirectInputDevice8::Poll each time you want to retrieve data, first set the data format for the device, then call the IDirectInputDevice8::GetCapabilities method and check for the DIDC_POLLEDDATAFORMAT flag in the DIDEVCAPS structure.

Do not confuse the DIDC_POLLEDDATAFORMAT flag with the DIDC_POLLEDDEVICE flag. The latter is set if any object on the device requires polling, regardless of data format. You can then find out whether this is the case for a particular object by calling the IDirectInputDevice8::GetObjectInfo method and checking for the DIDOI_POLLED flag in the DIDEVICEOBJECTINSTANCE structure.

The DIDC_POLLEDDEVICE flag describes the worst case for the device, not the actual situation. For example, a Human Interface Device (HID) mouse with software-controllable resolution might be marked as DIDC_POLLEDDEVICE because reading the resolution information requires polling. If you want to retrieve only the standard button and axis data, polling the device under these conditions is not necessary. However, there is no harm in calling the IDirectInputDevice8::Poll method for any input device. If the call is unnecessary, it has no effect and is very fast.

Event Notification

Event notification is suitable for applications such as the Scrawl Sample that wait for input before doing anything.

To use event notification, set up a thread-synchronization object with the Microsoft Win32 CreateEvent function, and then associate this event with the device by passing its handle to the IDirectInputDevice8::SetEventNotification method. The event is then signaled by Microsoft DirectInput whenever the state of the device changes. Your application can receive notification of the event with a Win32 function such as WaitForSingleObject, and then respond by checking the input buffer to find out what the event was. For code examples, see the Scrawl Sample and IDirectInputDevice8::SetEventNotification.


Relative and Absolute Axis Coordinates
Microsoft DirectX 9.0 SDK Update (October 2004)

Relative and Absolute Axis Coordinates

Axis coordinates can be returned as relative values—that is, the amount by which they have changed since the application last retrieved the device state or, in the case of buffered input, since the last item was put in the buffer.

Absolute axis coordinates are a running total of all the relative coordinates returned by the system since the device was acquired. In other words, they show the position of the axis in relation to a fixed point.

By default, mouse axes are reported as relative coordinates and joystick axes as absolute coordinates. You can change the coordinate system for a device by setting a property. For more information, see Device Properties.


Time Stamps and Sequence Numbers
Microsoft DirectX 9.0 SDK Update (October 2004)

Time Stamps and Sequence Numbers

When Microsoft DirectInput input data is buffered (see Buffered and Immediate Data), each DIDEVICEOBJECTDATA structure contains not only information about the type of event and the device object associated with it. It also contains a time stamp and a sequence number.

The dwTimeStamp member contains the system time, in milliseconds, at which the event took place. This is equivalent to the value that would have been returned by the Microsoft Win32 GetTickCount function, but at a higher resolution.

The dwSequence member contains a sequence number assigned by DirectInput. The DirectInput system keeps a single sequence counter, which is incremented by each buffered event from any device. (Simultaneous events on the same device, such as diagonal mouse movements, increment the count only once.) Use this number to compare events from different devices and see which came first. The DISEQUENCE_COMPARE macro, used for comparing DirectInput sequence numbers, takes wraparound into account.

Note Events are always placed in the buffer in chronological order, so you don't need to check the sequence numbers to sort the events from a single device.


Joystick Data
Microsoft DirectX 9.0 SDK Update (October 2004)

Joystick Data

To set up the joystick device for data retrieval, first call the IDirectInputDevice8::SetDataFormat method with the c_dfDIJoystick or the c_dfDIJoystick2 global variable as the parameter value. (See Device Data Formats.)

Because some device drivers do not notify Microsoft DirectInput of changes in state until explicitly asked to do so, you should always call the IDirectInputDevice8::Poll method before attempting to retrieve data from the joystick. For more information, see Polling and Event Notification.

The following sections cover retrieval and interpretation of data from a joystick or other similar input device such as a game pad or steering wheel:

  • Buffered Joystick Data
  • Checking for Lost Joystick Input
  • Immediate Joystick Data
  • Interpreting Joystick Axis Data
  • Using CPOINTs


Buffered Joystick Data
Microsoft DirectX 9.0 SDK Update (October 2004)

Buffered Joystick Data

To retrieve buffered data from the joystick, first set the buffer size (see Device Properties) and declare an array of DIDEVICEOBJECTDATA structures. This array can have up to the same number of elements as the buffer size. You do not have to retrieve the entire contents of the buffer with a single call. You can have just one element in the array and retrieve events one at a time until the buffer is empty.

After acquiring the device, you can examine and flush the buffer at any time with the IDirectInputDevice8::GetDeviceData method.(See Buffered and Immediate Data.)

Each element in the DIDEVICEOBJECTDATA array represents a change in state for a single object on the joystick. For instance, if the user presses button 0 and moves the stick diagonally, the array passed to IDirectInputDevice8::GetDeviceData (if it has at least three elements, and pdwInOut is at least 3) will have three elements filled in—an element for button 0 being pressed, an element for the change in the x-axis, and an element for the change in the y-axis—and the value of pdwInOut will be set to 3.

You can determine which object an element in the array refers to by checking the dwOfs member of the DIDEVICEOBJECTDATA structure against the following values:

  • DIJOFS_X
  • DIJOFS_Y
  • DIJOFS_Z
  • DIJOFS_Rx
  • DIJOFS_Ry
  • DIJOFS_Rz
  • DIJOFS_BUTTON0 to DIJOFS_BUTTON31 or DIJOFS_BUTTON(n)
  • DIJOFS_POV(n)
  • DIJOFS_SLIDER(n)

Each of these values is equivalent to the offset of the data for the object in a DIJOYSTATE structure. For example, DIJOFS_BUTTON0 is equivalent to the offset of rgbButtons[0] in the DIJOYSTATE structure. You can use simple comparisons to determine which device object is associated with an item in the buffer. For example:

DIDEVICEOBJECTDATA  *lpdidod;
int                 n;
.
.
.
/* JoyBuffer is an array of DIDEVICEOBJECTDATA structures
   that has been set by a call to GetDeviceData.
   n is incremented in a loop that examines all filled elements
   in the array. */
lpdidod = &JoyBuffer[n];
if (( (int) lpdidod->dwOfs == DIJOFS_BUTTON0)
   && (lpdidod->dwData & 0x80))
{
 ;  // Do something in response to press of primary button.
}

If the data format was set with c_dfDIJoystick2, you can use the predefined offsets for all the device objects that exist in DIJOYSTATE, but you must supply your own offsets for device objects represented in the extra members of DIJOYSTATE2.

If you are using Action Mapping, ignore the value in dwOfs and instead retrieve the application-defined data associated with the event from the uAppData member.

The data for the change of state of the device object is located in the dwData member of the DIDEVICEOBJECTDATA structure. For axes, the coordinate value is returned in this member. For button objects, only the low byte of dwData is significant. The high bit of this byte is set if the button is pressed, and it is clear if the button is released.

For the other members, see Time Stamps and Sequence Numbers.


Checking for Lost Joystick Input
Microsoft DirectX 9.0 SDK Update (October 2004)

Checking for Lost Joystick Input

If your application is using the joystick in foreground mode (see Cooperative Levels), it will lose the device when the focus shifts to another application.

Check for the DIERR_INPUTLOST return value from the IDirectInputDevice8::GetDeviceData or the IDirectInputDevice8::GetDeviceState method and attempt to reacquire the joystick, if necessary. (See Acquiring Devices.)

Note You should not attempt to reacquire the joystick on getting a DIERR_NOTACQUIRED error. If you do, you could get caught in an infinite loop: acquisition would fail again, you would get another DIERR_NOTACQUIRED error, and so on.

Because access to the joystick is not lost except when your application moves to the background—unlike the mouse and keyboard, the joystick is never used by the Microsoft Windows system—an alternative method is to reacquire the device in response to a WM_ACTIVATE message.


Immediate Joystick Data
Microsoft DirectX 9.0 SDK Update (October 2004)

Immediate Joystick Data

To retrieve the current state of the joystick, call the IDirectInputDevice8::GetDeviceState method with a pointer to a DIJOYSTATE or a DIJOYSTATE2 structure, depending on whether the data format was set with c_dfDIJoystick or c_dfDIJoystick2. (See Device Data Formats.) The joystick state returned in the structure includes the coordinates of the axes, the state of the buttons, and the state of the point-of-view controllers.

The first seven members of the DIJOYSTATE structure hold the axis coordinates. The last of these seven, rglSlider, is an array of two values. (See Interpreting Joystick Axis Data.)

The rgdwPOV member contains the position of up to four point-of-view controllers in hundredths of a degree clockwise from north (or forward). The center (neutral) position is reported as —1. For controllers that have only five positions, the position is one of the following values:

  • —1
  • 0
  • 90 * DI_DEGREES
  • 180 * DI_DEGREES
  • 270 * DI_DEGREES.

Some drivers report a value of 65,535, instead of —1, for the center position. You should check for a centered POV indicator as follows:

BOOL POVCentered = (LOWORD(dwPOV) == 0xFFFF);

The rgbButtons member is an array of bytes, one for each of 32 or 128 buttons, depending on the data format. For each button, the high bit is set if the button is down and it is clear if the button is up or not present.

The DIJOYSTATE2 structure has additional members for information about the velocity, acceleration, force, and torque of the axes.

See also

Buffered and Immediate Data


Interpreting Joystick Axis Data
Microsoft DirectX 9.0 SDK Update (October 2004)

Interpreting Joystick Axis Data

Axis values for the joystick are like those for the mouse. The value returned for the x-axis is greater as the stick moves to the right, and the value for the y-axis increases as the stick moves toward the user.

Data is in arbitrary units determined by the range property of the axis. For example, if the range for the stick's x-axis is from 0 through 10,000, a unit is one ten-thousandth of the stick's left-right travel, and the center position is 5,000. For some axes, the granularity property might be greater than 1. In this case, values are rounded off. For example, if the granularity is 10, values are reported as 0, 10, 20, and so on.

Axis data is also affected by the dead zone, a region around the center position in which motion is ignored. The dead zone provides tolerance for a slight deviation from the true center position for either or both axes of the stick. An axis value within the range of the dead zone is reported as true center.

The saturation property of an axis is a zone of tolerance at the minimum and maximum of the range. An axis value within this zone is reported as the minimum or maximum value. The purpose of the saturation property is to allow for slight differences between, for example, the minimum x-axis value reported at the top-left and bottom-left positions of the stick.

The following illustration shows the effect of the dead zone and the saturation zones. The vertical axis represents the returned axis values, where min and max are the lower and upper limits of the reported range and ctr is the reported center. The horizontal axis shows the physical position of the stick, where pmin and pmax are the extremes of the physical range, pctr is neutral position of the axis, dmin and dmax are the limits of the dead zone, and smin and smax are the boundaries of the lower and upper saturation zones. The lower saturation zone lies between pmin and smin, the upper saturation zone lies between smax and pmax, and the dead zone lies between dmin and dmax.

Graph of dead zone and saturation zones

For more information about joystick properties, see the following:

  • IDirectInputDevice8::GetProperty
  • IDirectInputDevice8::SetProperty
  • DIPROPRANGE
  • DIACTIONFORMAT

Axis coordinates from the joystick can be either relative or absolute. (See Relative and Absolute Axis Coordinates.) Because a joystick is an absolute device—unlike a mouse, it cannot travel infinitely far along any axis—absolute data is returned by default. When the axis mode for the joystick is set to relative, the axis coordinate represents the number of units of movement along the axis since the last value was returned.

The axis mode, which specifies whether relative or absolute data should be returned, is a property that can be changed before the device is acquired. (See Device Properties.) To set the axis mode to relative, call the IDirectInputDevice8::SetProperty method with the DIPROP_AXISMODE value in the rguidProp parameter and with DIPROPAXISMODE_REL in the dwData member of the DIPROPDWORD structure.


Using CPOINTs
Microsoft DirectX 9.0 SDK Update (October 2004)

Using CPOINTs

The CPOINT structure is used to calibrate segments of the response curve of a device axis. Up to eight CPOINTs can be set through the DIPROPCPOINTS structure. Each CPOINT structure contains a raw data value representing the position of the joystick along the axis, and a logical value. When your application receives the raw value, the logical value is used to calculate the returned value that is actually used. Raw values that fall between specific CPOINT raw data values are interpolated to logical values based on a line drawn between the CPOINTs to either side of the value.

The following is an example of the effect of five CPOINTs applied to the response curve of a joystick's x-axis. Before application of the DIPROPCPOINTS structure, the response graph for the example axis would appear as shown below, including saturation and dead zones.

Graph of CPOINTs before applying DIPROPCPOINTS

A DIPROPCPOINTS structure is initialized as follows, assuming the physical range to be -500 to 500.

DIPROPCPOINTS dipcp;

dipcp.diph.dwSize = sizeof(DIPROPCPOINTS);
dipcp.diph.dwHeaderSize = sizeof(DIPROPHEADER);
dipcp.diph.dwObj = GUID_XAxis;
dipcp.diph.dwHow = DIPH_BYID;
dipcp.dwCPointsNum = 5;
dipcp.cp[0].lP = -500;
dipcp.cp[0].dwLog = 0;
dipcp.cp[1].lP = -300;
dipcp.cp[1].dwLog = 1000;
dipcp.cp[2].lP = -100;
dipcp.cp[2].dwLog = 5000;
dipcp.cp[3].lP = 200;
dipcp.cp[3].dwLog = 9000;
dipcp.cp[4].lP = 500;
dipcp.cp[4].dwLog = 10000;

Note that you do not need to know the actual maximum returned value as the values in the dwLog member of the CPOINT structure are expressed as a percentage of the total, multiplied by 10000 (the number of discrete divisions in the total range). For instance, the example sets the curve so that 10% of the maximum value is returned at the -300 point in the joystick's range. 0.10 * 10000 = 1000, so that value is given to the dwLog member while -300 is assigned to the corresponding lP member.

After applying this DIPROPCPOINTS structure through IDirectInputDevice8::SetProperty, the curve responds as seen below.

Graph of CPOINTs after applying DIPROPCPOINTS


Keyboard Data
Microsoft DirectX 9.0 SDK Update (October 2004)

Keyboard Data

When using Microsoft DirectInput, consider the keyboard not as a text input device but as a game pad with many buttons. When your application requires text input, do not use DirectInput methods. It is far easier to retrieve the data from the normal Microsoft Windows messages, which enable you take advantage of services such as character repeat and translation of physical keys to virtual keys. This is particularly important for languages other than English, which can require special translations of key presses.

To set up the keyboard device for data retrieval, you must first call the IDirectInputDevice8::SetDataFormat method with the c_dfDIKeyboard global variable as the parameter. (See Device Data Formats.)

The following sections give more information about obtaining and interpreting keyboard data:

  • Buffered Keyboard Data
  • Checking for Lost Keyboard Input
  • Immediate Keyboard Data
  • Interpreting Keyboard Data


Buffered Keyboard Data
Microsoft DirectX 9.0 SDK Update (October 2004)

Buffered Keyboard Data

To retrieve buffered data from the keyboard, you must first set the buffer size (see Device Properties). This step is essential because the default size of the buffer is 0.

You must also declare an array of DIDEVICEOBJECTDATA structures. This array can have up to the same number of elements as the buffer size. You do not have to retrieve the entire contents of the buffer with a single call. You can have just one element in the array and retrieve events one at a time until the buffer is empty.

After acquiring the keyboard device, you can examine and flush the buffer at any time by using the IDirectInputDevice8::GetDeviceData method. (See Buffered and Immediate Data.)

Each element in the DIDEVICEOBJECTDATA array represents a change in state for a single key—that is, a press or release. Because Microsoft DirectInput gets the data directly from the keyboard, any settings for character repeat in Control Panel are ignored. This means that a keystroke is counted only once, no matter how long the key is held down.

You can determine which key an element in the array refers to by checking the dwOfs member of the DIDEVICEOBJECTDATA structure against the DirectInput Keyboard Device. (See also Interpreting Keyboard Data.)

If you are using Action Mapping, ignore the value in dwOfs and instead retrieve the application-defined data associated with the key event from the uAppData member.

The data for the change of state of the key is located in the dwData member of the DIDEVICEOBJECTDATA structure. Only the low byte of dwData is significant. The high bit of this byte is set if the key was pressed, and it is clear if it was released. In other words, the key was pressed if (dwData & 0x80) is nonzero.


Checking for Lost Keyboard Input
Microsoft DirectX 9.0 SDK Update (October 2004)

Checking for Lost Keyboard Input

When you have set the cooperative level to DISCL_FOREGROUND and the focus switches to another application, Microsoft Windows might force your application to unacquire the keyboard. For this reason, you should check for the DIERR_INPUTLOST return value from the IDirectInputDevice8::GetDeviceData or IDirectInputDevice8::GetDeviceState methods and attempt to reacquire the keyboard, if necessary. (See Acquiring Devices.)

Note You should not attempt to reacquire the keyboard on getting a DIERR_NOTACQUIRED error. If you do, you could get caught in an infinite loop: acquisition would again fail, you would get another DIERR_NOTACQUIRED error, and so on.


Immediate Keyboard Data
Microsoft DirectX 9.0 SDK Update (October 2004)

Immediate Keyboard Data

To retrieve the current state of the keyboard, call the IDirectInputDevice8::GetDeviceState method with a pointer to an array of 256 bytes that will hold the returned data.

The IDirectInputDevice8::GetDeviceState method behaves in the same way as the Microsoft Win32 GetKeyboardState function. It returns a snapshot of the current state of the keyboard. Each key is represented by a byte in the array of 256 bytes whose address was passed as the lpvData parameter. If the high bit of the byte is set, the key is down. The array is most conveniently indexed with the Microsoft DirectInput Keyboard Device. (See also Interpreting Keyboard Data.)

The following code example calls a function in response to the ESC key being down. Assume that lpdiKeyboard is an acquired DirectInput device.

BYTE  diKeys[256];
if (lpdiKeyboard->GetDeviceState(256, diKeys) == DI_OK)
{
  if (diKeys[DIK_ESCAPE] & 0x80) DoSomething();
}


Interpreting Keyboard Data
Microsoft DirectX 9.0 SDK Update (October 2004)

Interpreting Keyboard Data

This topic covers the identification of keys for which data is reported by the IDirectInputDevice8::GetDeviceState and IDirectInputDevice8::GetDeviceData methods. For more information about interpreting the data from IDirectInputDevice8::GetDeviceData, see Time Stamps and Sequence Numbers.

In one important respect, Microsoft DirectInput applications read the keyboard differently from the way Microsoft Windows does. For DirectInput applications, keyboard data refers not to virtual keys but to the actual physical keys—that is, the scan codes. DIK_ENTER, for example, refers only to the ENTER key on the main keyboard, not to the ENTER key on the numerical keypad.

Additionally, differences among keyboards can affect the way DirectInput applications interpret keyboard data. For example, DirectInput defines a constant for each key on the enhanced keyboard, as well as the additional keys on international keyboards. Because NEC keyboards support different scan codes than the PC-enhanced keyboards, DirectInput translates NEC key-scan codes into PC-enhanced scan codes where possible.

Other keyboard differences to consider are:

  • Not all PC-enhanced keyboards have the Windows logo keys (DIK_LWIN, DIK_RWIN, and DIK_APPS), there is no way to determine whether the keys are physically available.
  • Laptops and other small computers often do not implement a full set of keys. Instead, some keys (typically numeric keypad keys) are multiplexed with other keys, which are selected by an auxiliary mode key that does not generate a separate scan code.
  • If the keyboard subtype indicates a PC XT or PC AT keyboard, the following keys are not available: DIK_F11, DIK_F12, and all the extended keys (DIK_* values greater than 0x7F). Furthermore, the PC XT keyboard lacks DIK_SYSRQ.

  • Japanese keyboards, particularly the NEC PC-98 keyboards, contain a substantially different set of keys than U.S. keyboards. For more information, see DirectInput and Japanese Keyboards.


Mouse Data
Microsoft DirectX 9.0 SDK Update (October 2004)

Mouse Data

To set up the mouse device for data retrieval, first call the IDirectInputDevice8::SetDataFormat method with the c_dfDIMouse or c_dfDIMouse2 global variable as the parameter value. Use c_dfDIMouse2 if you want to support more than four mouse buttons.

For maximum performance in a full-screen application, set the cooperative level to DISCL_EXCLUSIVE | DISCL_FOREGROUND. Note that the exclusive setting causes the Microsoft Windows cursor to disappear. The DISCL_FOREGROUND setting causes the application to lose access to the mouse when you switch to a debugging window. Changing to DISCL_BACKGROUND enables you to debug the application more easily, but at a cost in performance.

The following sections give more information about retrieval and interpretation of immediate and buffered mouse data.

  • Buffered Mouse Data
  • Checking for Lost Mouse Input
  • Immediate Mouse Data
  • Interpreting Mouse Axis Data

See Also

Device Data Formats, Cooperative Levels


Buffered Mouse Data
Microsoft DirectX 9.0 SDK Update (October 2004)

Buffered Mouse Data

To retrieve buffered data from the mouse, you must first set the buffer size (see Device Properties). The default size of the buffer is 0, so this step is essential.

You must also declare an array of DIDEVICEOBJECTDATA structures. This array can have up to the same number of elements as the buffer size. You do not have to retrieve the entire contents of the buffer with a single call. You can have just one element in the array and retrieve events one at a time until the buffer is empty.

After acquiring the device, you can examine and flush events in the buffer at any time by using the IDirectInputDevice8::GetDeviceData method. (See Buffered and Immediate Data.) On return, each element in the DIDEVICEOBJECTDATA array represents a change in state for a single object on the mouse. For example, if the user presses button 0 and moves the mouse diagonally, the array passed to IDirectInputDevice8::GetDeviceData (if it has at least three elements, and pdwInOut is at least 3) will have three elements filled in—an element for button 0 being pressed, an element for the change in the x-axis, and an element for the change in the y-axis—and the value of pdwInOut will be set to 3.

You can determine which object an element in the array refers to by checking the dwOfs member of the DIDEVICEOBJECTDATA structure against the values returned by the following macros:

  • DIMOFS_BUTTON0 to DIMOFS_BUTTON7
  • DIMOFS_X
  • DIMOFS_Y
  • DIMOFS_Z

Each of these values is derived from the offset of the data for the object in a DIMOUSESTATE or DIMOUSESTATE2 structure. For example, DIMOFS_BUTTON0 is equivalent to the offset of rgbButtons[0] in the DIMOUSESTATE structure. DIMOFS_BUTTON4 to DIMOFS_BUTTON7 are supported only for DIMOUSESTATE2. With the macros you can use simple comparisons to determine which device object is associated with an item in the buffer. For example:

DIDEVICEOBJECTDATA  *lpdidod;
int                 n;
.
.
.
/* MouseBuffer is an array of DIDEVICEOBJECTDATA structures
   that has been set by a call to GetDeviceData.
   n is incremented in a loop that examines all filled elements
   in the array. */
lpdidod = &MouseBuffer[n];
if (( (int) lpdidod->dwOfs == DIMOFS_BUTTON0)
      && (lpdidod->dwData & 0x80))
{
 ;  // Do something in response to left button press.
}

The data for the change of state of the device object is located in the dwData member of the DIDEVICEOBJECTDATA structure. For axes, the coordinate value is returned in this member. For button objects, only the low byte of dwData is significant. The high bit of this byte is set if the button was pressed, and it is clear if the button was released. In other words, the button was pressed if (dwData & 0x80) is nonzero.

If you are using Action Mapping, ignore the value in dwOfs and instead retrieve the application-defined data associated with the event from the uAppData member.

For more information about the other members of the DIDEVICEOBJECTDATA structure, see Time Stamps and Sequence Numbers.


Checking for Lost Mouse Input
Microsoft DirectX 9.0 SDK Update (October 2004)

Checking for Lost Mouse Input

When you have set the cooperative level to DISCL_FOREGROUND and the focus switches to another application (or even to the menu in your own application), Microsoft Windows might force your application to unacquire the mouse. For this reason, you should check for the DIERR_INPUTLOST return value from the IDirectInputDevice8::GetDeviceData or the IDirectInputDevice8::GetDeviceState method, and attempt to reacquire the mouse if necessary. (See Acquiring Devices.)

Note You should not attempt to reacquire the mouse on getting a DIERR_NOTACQUIRED error. If you do, you could get caught in an infinite loop—acquisition would again fail, you would get another DIERR_NOTACQUIRED error, and so on.


Immediate Mouse Data
Microsoft DirectX 9.0 SDK Update (October 2004)

Immediate Mouse Data

To retrieve the current state of the mouse, call IDirectInputDevice8::GetDeviceState with a pointer to a DIMOUSESTATE or a DIMOUSESTATE2 structure, depending on the data format. The mouse state returned in the structure includes axis data and the state of each of the buttons.

The first three members of the structure hold the axis coordinates. (See Interpreting Mouse Axis Data.)

The rgbButtons member is an array of bytes, one for each of four or eight buttons. For a traditional mouse, the first element in the array is generally the left button, the second is the right button, and the third is the middle button. The high bit is set if the button is down, and it is clear if the button is up or not present.

See also

Buffered and Immediate Data


Interpreting Mouse Axis Data
Microsoft DirectX 9.0 SDK Update (October 2004)

Interpreting Mouse Axis Data

The data returned for the x-axis and y-axis of a mouse indicates the movement of the mouse itself, not the cursor. The units of measurement are based on the values returned by the mouse hardware and have nothing to do with pixels or any other form of screen measurement. Because Microsoft DirectInput communicates directly with the mouse driver, the values for mouse speed and acceleration set by the user in Control Panel do not affect this data.

Axis data returned from the mouse can be either relative or absolute. (See Relative and Absolute Axis Coordinates.) Because a mouse is a relative device—unlike a joystick, it does not have a home position—relative data is returned by default.

The axis mode, which specifies whether relative or absolute data should be returned, is a property that can be changed before the device is acquired. (See Device Properties.) To set the axis mode to absolute, call IDirectInputDevice8::SetProperty with the DIPROP_AXISMODE value in the rguidProp parameter and with DIPROPAXISMODE_ABS in the dwData member of the DIPROPDWORD structure.

When the axis mode for the mouse is set to relative, the axis coordinate represents the number of units that the device has been moved along the axis since the last value was returned. A negative value indicates that the mouse was moved to the left for the x-axis, or away from the user for the y-axis, or that the z-axis (the wheel) was rotated toward the user. Positive values indicate movement in the opposite direction.

When the axis mode is set to absolute, the coordinates are a running total of all relative motions received by DirectInput. The axis coordinates are not initialized to any particular value when the device is acquired, so your application should treat absolute values as relative to an unknown origin. You can record the current absolute position whenever the device is acquired and save it as the virtual origin. This virtual origin can then be subtracted from subsequent absolute coordinates retrieved from the device to compute the relative distance that the mouse has moved from the point of acquisition.

The data returned for the axis coordinates is also affected by the granularity property of the device. For the x-axis and y-axis of the mouse, granularity is normally 1. In other words, the minimum change in value is 1. For the wheel axis, it might be larger.


Output Data
Microsoft DirectX 9.0 SDK Update (October 2004)

Output Data

Some Human Interface Devices both generate input and accept output. The IDirectInputDevice8::SendDeviceData method is used to send packets of data to such devices.

IDirectInputDevice8::SendDeviceData may be viewed as IDirectInputDevice8::GetDeviceData in reverse. As with that method, it uses the DIDEVICEOBJECTDATA structure as the basic unit of data. In this case, however, the dwOfs member contains the instance ID of the device object associated with the data rather than its offset in the data format for the device. (Because offset identifiers exist only for device objects that provide input in the selected data format, an object that accepts only output might not even have an offset.) The dwData member contains whatever data is appropriate for the object. The dwTimeStamp and dwSequence members are not used and must be set to 0.

To send data to the device, set up an array of DIDEVICEOBJECTDATA structures, fill the required number of elements with data, and then pass the array address and the number of elements used to IDirectInputDevice8::SendDeviceData. Data for different device objects is combined into a single packet that is then sent to the device.

The form of the data packet is specific to the device, as is the treatment of unused fields in the packet. Some devices may treat fields as optional. In other words, if no data is supplied, the state of the object remains unchanged. More commonly, all fields are significant, even when you do not specifically supply data for them. For example, if you send data to a single keyboard LED, it is assumed that the data for the other two LEDs is 0 and that they are turned off. However, you can override this behavior by using the DISDD_CONTINUE flag. In this case, the data for the other two LEDs is the value you most recently sent them.

The device object type identifiers are obtained from the dwType member of the DIDEVICEOBJECTINSTANCE structure after passing the HID usage page and usage code to IDirectInputDevice8::GetObjectInfo. For example, the type identifier of the Scroll Lock LED can be obtained by using the following code, where pdev is an IDirectInputDevice8 interface pointer representing the keyboard.

DIDEVICEOBJECTINSTANCE didoi;
DWORD NumLockID;

HRESULT hr = pdev->GetObjectInfo(&didoi,
        DIMAKEUSAGEDWORD(0x07,0x53), DIPH_BYUSAGE);
NumLockID = didoi.dwType;

The following sample function, when called repeatedly, causes the LEDs on the keyboard to flash in a recurring pattern. It is assumed that the high bit of the data byte determines the state of the LED. The DWORDs NumLockID, CapsLockID, and ScrollLockID have all been obtained as shown above.

#define ARRAYSIZE 4
void FlashLEDs(void)
    {
    static int         rgiBits[] = { 1, 2, 4, 2 };
    static int         iLooper = 0;
    DWORD              cdod = 3;                  // Number of items
    DIDEVICEOBJECTDATA rgdod[ARRAYSIZE-1];
    HRESULT            hres;

    // Must clear dwTimeStamp and dwSequence
    ZeroMemory(rgdod, sizeof(rgdod));

    rgdod[0].dwOfs = NumLockID;
    rgdod[1].dwOfs = CapsLockID;
    rgdod[2].dwOfs = ScrollLockID;

    rgdod[0].dwData = (rgiBits[iLooper] & 1) ? 0x80 : 0;
                                           // NumLock light on/off
    rgdod[1].dwData = (rgiBits[iLooper] & 2) ? 0x80 : 0;
                                           // CapsLock light on/off
    rgdod[2].dwData = (rgiBits[iLooper] & 4) ? 0x80 : 0;
                                           // ScrollLock light on/off

    iLooper = (iLooper + 1) % ARRAYSIZE; // Loops from 0 to 3

    hres = pdev->SendDeviceData(sizeof(DIDEVICEOBJECTDATA),
            rgdod, &cdod, 0);
    }


Action Mapping
Microsoft DirectX 9.0 SDK Update (October 2004)

Action Mapping

Traditionally, applications have done their own mapping of events to particular buttons and axes. A car-racing game, for example, might assume that the x-axis on the user's joystick or mouse was the most suitable control for steering the car. The only way to accommodate new or unusual devices was to provide configuration options so that the user could specify some other axis, such as a rotational axis, to use for steering. Moreover, the application had no way of knowing which installed device was the best fit for the game, so the user typically had to choose a device from a menu or make sure only the preferred device was attached.

Using action mapping, you no longer need to make assumptions about the best use of devices and device objects. Instead, your application binds actions to virtual controls wherever possible. Rather than getting data from the x-axis and steering the car to the left or the right accordingly, the application might get data from a virtual control called DIAXIS_DRIVINGR_STEER. Microsoft DirectInput assigns the virtual control to a physical control—that is, a device object. It does so by taking into account the application genre, user preferences, information from the device manufacturer, and the user's configuration of the device.

Action mapping also simplifies the input loop by returning data for all devices in a form independent of the particular device. A single action can be mapped to more than one device, and the input loop can respond to the action the same way regardless of which device is being read.

The following topics contain more information about the steps required to implement action mapping.

  • Configuring the Action Map
  • Finding Matching Devices
  • Maintaining Files During Development
  • Preparing the Action Map
  • Retrieving Action Data
  • User Configuration of the Device


Configuring the Action Map
Microsoft DirectX 9.0 SDK Update (October 2004)

Configuring the Action Map

As each device is enumerated, you can obtain a pointer to it, retrieve the default action map, make changes in the default map, and apply the final mappings.

1. Obtaining the Device

Obtain the IDirectInputDevice8 interface pointer for each enumerated device from the lpdid parameter of the enumeration callback. See DIEnumDevicesBySemanticsCallback. If you want to save the device interface for use in your application, call AddRef on the pointer and assign it to a global variable.

2. Obtaining the Default Action Map

To obtain the default action map for the device, call IDirectInputDevice8::BuildActionMap. Microsoft DirectInput takes the list of virtual controls specified in your DIACTIONFORMAT structure and attempts to map these to physical device objects, returning the results in the same structure. You should examine the dwHow member of each DIACTION element to determine whether the control was successfully mapped. If it was, you can also ascertain what criterion was used in choosing the object—for example, configuration by the user or by the device manufacturer.

3. Making Changes to the Action Map

You now have the option of changing the default mappings, although it is not recommended that you do so. After examining the dwSemantic member of the DIACTION structure to determine which device object was mapped to an action, you can change that value. For example, if an action is mapped to DIJOFS_BUTTON9, but you want that action to be mapped to the trigger button instead, change the value to DIJOFS_BUTTON0 before applying the action map.

4. Applying the Action Map

When you are satisfied that the DIACTIONFORMAT structure contains suitable mappings for the device, call IDirectInputDevice8::SetActionMap. The value you assigned to the uAppData member of each DIACTION structure now becomes bound to the control specified in the dwSemantic member, which in turn is bound to a particular device object.

5. Mapping More than One Device

Repeat steps 1 though 4 for each device you want to use in your application. Suppose you want to map actions to both a joystick and the keyboard. In the racing-game example, the action defined in the game as eB_DRIVERVIEW was mapped to a keyboard key in the following element of the DIACTION array.

{eB_DRIVERVIEW, DIKEYBOARD_1, "Driver View", },

In that example, when BuildActionMap is called on any device that is not a keyboard, the dwHow member of the DIACTION structure for that element is set to DIAH_UNMAPPED. Continue examining the dwHow member as each device in turn is enumerated, until a value other than DIAH_UNMAPPED is returned. This indicates that the device being currently mapped is a keyboard and the action has been successfully mapped to the requested key.

Even actions that have been successfully mapped can be mapped to another device. In the example, eB_UPSHIFT is given two DIACTION structures, as follows:

{eB_UPSHIFT, DIBUTTON_DRIVINGR_SHIFTUP, 0, "Upshift", },
...
{eB_UPSHIFT, DIKEYBOARD_PRIOR,          0, "Upshift", },

As devices are successively enumerated, the eB_UPSHIFT action is mapped to a suitable button on one or more joysticks or other game controllers, and then again to the keyboard.

6. Displaying the Configuration

To show the user how actions have been mapped to devices, pass the DICD_DEFAULT flag to IDirectInput8::ConfigureDevices. The property sheet for the device, containing a graphical representation of mappings, is displayed in view-only mode as in the following diagram. For more information about the mechanics of displaying the image, refer to the Using Action Mapping tutorial.

Graphical user interface for configuring the action map

If the device manufacturer has not provided a device image, the mapping will be presented in text mode as in the following diagram.

Text user interface for configuring the action map

Note Even if the cooperative level for the application is disabling the Microsoft Windows logo key passively through an exclusive cooperative level or actively through use of the DISCL_NOWINKEY flag, that key will be active while the default action mapping user interface (UI) is displayed.

For more information about this property sheet, see User Configuration of the Device.


Finding Matching Devices
Microsoft DirectX 9.0 SDK Update (October 2004)

Finding Matching Devices

After you define the application actions and the virtual controls or device objects to which these actions are to be mapped, the next step is to enumerate devices on the system to find those that best support the desired virtual controls.

To do so, pass the DIACTIONFORMAT structure to IDirectInput8::EnumDevicesBySemantics. This method works in much the same way as IDirectInput8::EnumDevices and takes a similar callback function.

Devices that have been configured by the user to match certain controls are always enumerated first. For example, if a user has configured a wheel as the primary steering device for driving games, then the wheel is enumerated first whenever devices that support DIAXIS_DRIVINGR_STEER are requested, taking precedence over other capable devices such as joysticks that have not been configured by the user. Otherwise, the order in which available devices are enumerated is determined by the degree to which they match the requested controls. However, the order in which devices are enumerated by Microsoft DirectInput is not guaranteed.

In the enumeration callback, you can retrieve the default action mapping for each device, change any mappings you don't like, give the user an opportunity to reconfigure the device, and apply the action map. These steps are covered in Configuring the Action Map. Flags returned in the DIEnumDevicesBySemanticsCallback will provide information about why a particular device was enumerated. These flags will indicate whether a device has been used recently, is newly installed, or will accept mappings of priority 1 or priority 2 controls.


Maintaining Files During Development
Microsoft DirectX 9.0 SDK Update (October 2004)

Maintaining Files During Development

During a development cycle, unused and out of date .ini files may accumulate due to frequent action map changes, Microsoft DirectInput reinstallations, multiple users, and other normal development situations. These files could possibly cause unexpected mappings or reports of "recent" (DIEDBS_RECENTDEVICE) for devices that would not be expected to return that value. For this reason, it is good practice to occasionally delete any unused .ini files. These files can be found in C:\Program Files\Common Files\DirectX\DirectInput\User Maps.

Note The procedure suggested above is meant to be performed only manually during a development cycle to ensure that the development environment is in a cleaner state. A shipping application should never delete user maps as this could result in the loss of a user's preferred settings.


Preparing the Action Map
Microsoft DirectX 9.0 SDK Update (October 2004)

Preparing the Action Map

The action map is a DIACTIONFORMAT structure containing information about application actions and their mapping to virtual controls or device objects. The structure is passed back and forth between the application and Microsoft DirectInput to establish the final mapping. This section explains how to initialize the map.

1. Define Application Actions

The first step in implementing DirectInput action mapping is to determine what input-driven actions in your application need to be mapped to device objects. For actions that can be performed either by an axis or by a button, you must define separate actions for both input types. It is recommended that you define button actions for all important functions, in case the device does not have the appropriate axes.

The following sample enumeration of action values might be defined by a car-racing game. Axis actions begin with "eA" and button actions with "eB".

enum eGameActions
{
    eA_STEER,       // Steering
    eB_STEER_LEFT,  // Steer left
    eB_STEER_RIGHT, // Steer right
    eA_ACCELERATE,  // Change speed
    eB_ACCELERATE,  // Speed up
    eB_DECELERATE,  // Slow down
    eA_BRAKE,       // Brake
    eB_BRAKE,       // Brake
    eB_UPSHIFT,     // Shift to higher gear
    eB_DOWNSHIFT,   // Shift to lower gear
    eB_CYCLEVIEW,   // Cycle to next view
    eB_COURSEVIEW,  // Toggle course view
    eB_DRIVERVIEW,  // View from driver's seat
    eB_BRAKEBIAS,   // Brake bias
    eA_VOLUME,      // Sound volume
    eB_MUTE         // Toggle sound
};

#define NUM_MY_ACTIONS 16

In the example, actions are defined as enumerated values. However, they could be other 32-bit data types, such as pointers to functions. When you retrieve device data, you get whatever action value you have defined, and you can handle it in any way you like.

2. Define the Genre

The next step is to decide what genre your application belongs to. A genre defines a set of virtual controls. By selecting the proper genre, you can obtain the best possible fit of virtual controls to application actions. Manufacturers who choose to supply default mappings for their devices must support one or more of the genres defined by DirectInput. See Action Mapping Constants for a list of these genres.

For the game in the example, the obvious choice is the DIVIRTUAL_DRIVING_RACE genre, which contains the following virtual controls.

Priority 1 Controls

DIAXIS_DRIVINGR_STEER

DIAXIS_DRIVINGR_ACCELERATE

DIAXIS_DRIVINGR_BRAKE

DIBUTTON_DRIVINGR_SHIFTUP

DIBUTTON_DRIVINGR_SHIFTDOWN

DIBUTTON_DRIVINGR_VIEW

DIBUTTON_DRIVINGR_MENU

Priority 2 Controls

DIAXIS_DRIVINGR_ACCEL_AND_BRAKE

DIHATSWITCH_DRIVINGR_GLANCE

DIBUTTON_DRIVINGR_ACCELERATE_LINK

DIBUTTON_DRIVINGR_AIDS

DIBUTTON_DRIVINGR_BOOST

DIBUTTON_DRIVINGR_BRAKE

DIBUTTON_DRIVINGR_DASHBOARD

DIBUTTON_DRIVINGR_DEVICE

DIBUTTON_DRIVINGR_GLANCE_LEFT_LINK

DIBUTTON_DRIVINGR_GLANCE_RIGHT_LINK

DIBUTTON_DRIVINGR_MAP

DIBUTTON_DRIVINGR_PAUSE

DIBUTTON_DRIVINGR_PIT

DIBUTTON_DRIVINGR_STEER_LEFT_LINK

DIBUTTON_DRIVINGR_STEER_RIGHT_LINK

There is no difference in functionality between Priority 1 and Priority 2 controls. Priority 1 controls are those most likely to be supported by device manufacturers in their default mappings. However, there is no guarantee that any virtual control will be supported by a device.

3. Assign Actions to Controls or Device Objects

The next step in creating the action map is to associate each application action with one or more of the virtual controls defined for the genre. You do this by declaring and initializing an array of DIACTION structures. Each structure in the array specifies the action value, the virtual control to associate with it, and a friendly name that describes the action. Leave other members as zero; they will be filled in later by DirectInput.

You can also use elements of the DIACTION array to map actions to particular keys or buttons on the keyboard or mouse or to channels on a Microsoft DirectPlay voice device. By doing so, you can take advantage of the simplified input loop for all input, not just that from virtual controls. For example, suppose you map the application-defined action eB_UPSHIFT to both the DIBUTTON_DRIVINGR_SHIFTUP virtual control and to the Page Up key. When retrieving data, you get back eB_UPSHIFT whether the input came from a joystick button or the keyboard.

The following example declares an action map for the car-racing game.

DIACTION rgActions[]=
{
//Genre-defined virtual axes

  {eA_STEER,       DIAXIS_DRIVINGR_STEER,        0, "Steer",      },
  {eA_ACCELERATE,  DIAXIS_DRIVINGR_ACCELERATE,   0, "Accelerate", },
  {eA_BRAKE,       DIAXIS_DRIVINGR_BRAKE,        0, "Brake",      },

//Genre-defined virtual buttons

  {eB_UPSHIFT,     DIBUTTON_DRIVINGR_SHIFTUP,    0, "Upshift",    },
  {eB_DOWNSHIFT,   DIBUTTON_DRIVINGR_SHIFTDOWN,  0, "DownShift",  },
  {eB_CYCLEVIEW,   DIBUTTON_DRIVINGR_VIEW,       0, "Change View",},

// Actions not defined in the genre that can be assigned to any
// button or axis

  {eA_VOLUME,      DIAXIS_ANY_1,                 0, "Volume",      },
  {eB_MUTE,        DIBUTTON_ANY(0),              0, "Toggle Sound",},

// Actions not defined in the genre that must be assigned to
// particular keys

  {eB_DRIVERVIEW,  DIKEYBOARD_1,                 0, "Driver View",},
  {eB_COURSEVIEW,  DIKEYBOARD_C,                 0, "Course View",},
  {eB_BRAKEBIAS,   DIKEYBOARD_B,                 0, "Brake Bias", },

// Actions mapped to keys as well as to virtual controls

  {eB_UPSHIFT,     DIKEYBOARD_PRIOR,              0, "Upshift",    },
  {eB_DOWNSHIFT,   DIKEYBOARD_NEXT,               0, "Downshift",  },
  {eB_STEER_LEFT,  DIKEYBOARD_LEFT,               0, "Steer Left", },
  {eB_STEER_RIGHT, DIKEYBOARD_RIGHT,              0, "Steer Right",},
  {eB_ACCELERATE,  DIKEYBOARD_UP,                 0, "Accelerate", },
  {eB_DECELERATE,  DIKEYBOARD_DOWN,               0, "Decelerate", },
  {eB_BRAKE,       DIKEYBOARD_END,                0, "Brake",      },

// Actions mapped to buttons as well as to virtual controls and keys

  {eB_UPSHIFT,     DIMOUSE_BUTTON0,              0, "Upshift",   },
  {eB_DOWNSHIFT,   DIMOUSE_BUTTON1,              0, "Downshift", },
};

In the example, some actions are mapped to actual keys by using Keyboard Mapping. Similar mappings to the mouse buttons and axes can be made by using Mouse Mapping.

The DIACTION array is contained within a DIACTIONFORMAT structure that also contains information about the genre, the application, and the desired scaling of axis data. Use the same instance of this structure throughout the action mapping process. Some members will not be used immediately, but you can fill in the entire structure before the next step, Finding Matching Devices.


Retrieving Action Data
Microsoft DirectX 9.0 SDK Update (October 2004)

Retrieving Action Data

You retrieve buffered data from action-mapped devices just as you would from unmapped devices: by calling IDirectInputDevice8::GetDeviceData. However, instead of identifying device objects by examining the dwOfs member of the DIDEVICEOBJECTDATA structure, you obtain the action associated with the object from the uAppData member. This is the same value you passed to the device in the DIACTION structure. It can be a simple identifier or a pointer to a function designed to handle the action.

Remember that an action can be associated with more than one device. You still have to obtain data from both devices independently, but you can use the same routine to handle the data regardless of where it comes from.

The following sample code, which might be part of the game loop in a driving simulation, retrieves data from all devices in the g_lpIdiDevices array. This array contains g_nDevices elements.

for (int iDevice = 0x0; iDevice < g_nDevices; iDevice++)
{
    DIDEVICEOBJECTDATA didod;
    DWORD dwObjCount = 1;

    // Poll the device for data.
    g_lpDiDevices[iDevice]->Poll();

    // Retrieve the data.
    g_lpDiDevices[iDevice]->GetDeviceData( sizeof(didod),
                                           &didod,
                                           &dwObjCount, 0 );

    // Handle the actions regardless of what device returned them.
    switch(didod.uAppData)
    {
        case eA_STEER:
            SteerCar(didod.dwData);
            break;
        case eB_UPSHIFT
            if (didod.dwData & 0x80) ShiftGears(UPSHIFT);
            break;
        .
        .
        .

        default:
            break;
    }
}
Note Axis constants for specific genres, such as DIAXIS_DRIVINGR_STEER or DIAXIS_SPACESIM_LATERAL, are used for absolute joystick data. The action mapper attempts to map this virtual control to a device object that returns absolute data. The data returned from that device should be processed accordingly in the application. Device constants such as DIMOUSE_XAXIS, however, are expected to return relative data.

When retrieving data, each potential source of data should be processed separately to keep one device object from possibly overwriting the data from another. For instance, the following DIACTION structures are used in an action map to control direction.

{INPUT_LEFTRIGHT_ABS_AXIS, DIAXIS_SPACESIM_LATERAL, 0,   _T("Turn"),},
{INPUT_LEFTRIGHT_REL_AXIS, DIMOUSE_XAXIS,           0,   _T("Turn"),},
{INPUT_TURNLEFT,           DIKEYBOARD_LEFT,     0,  _T("Turn left"),},
{INPUT_TURNRIGHT,          DIKEYBOARD_RIGHT,    0, _T("Turn right"),},

The application's input loop processes data from these actions in the following case statement.

switch (adod[j].uAppData)
{
    case INPUT_LEFTRIGHT_ABS_AXIS:
        g_dwAbsLR = adod[j].dwData
        break;
    case INPUT_LEFTRIGHT_REL_AXIS:
        g_dwRelLR = adod[j].dwData;
        break;
    case INPUT_TURNLEFT:
        g_bLeft = (adod[j].dwData != 0);
        break;
    case INPUT_TURNRIGHT:
        g_bRight = (adod[j].dwData != 0)
        break;
}

Note that each data source is assigned to a separate variable rather than all data sources being assigned a generic "turn" variable. If they were to share a generic variable, holding down the LEFT ARROW key and then moving the joystick would cause the keyboard information to be lost. This is because the joystick data would overwrite the variable.

In addition to individual variables, there are many ways to process the data. Whatever method is used, care should be taken in the processing of data to avoid unexpectedly lost information.


User Configuration of the Device
Microsoft DirectX 9.0 SDK Update (October 2004)

User Configuration of the Device

Microsoft DirectInput provides a property sheet that can be called from an application, enabling the user to configure devices for the application and view the current configuration. This property sheet can display various views of the device as provided by the manufacturer.

To enable user configuration, pass a DICONFIGUREDEVICESPARAMS structure containing a pointer to the DIACTIONFORMAT structure describing the desired mapping, along with the DICD_EDIT flag, to the IDirectInput8::ConfigureDevices method. Normally you would do this after calling IDirectInputDevice8::BuildActionMap on all devices that will be used in the application.

The following illustration shows a typical property sheet in edit mode.

Graphical user interface for configuring the action map

If the device manufacturer has not provided a device image, the mapping will be presented in text mode as in the following diagram.

Text user interface for configuring the action map

Note Even if the cooperative level for the application is disabling the Microsoft Windows logo key passively through an exclusive cooperative level or actively through use of the DISCL_NOWINKEY flag, that key will be active while the default action mapping UI is displayed.

The property page for a device lists the friendly names that were provided by you in the lptszActionName member of each DIACTION structure. If you have already called IDirectInputDevice8::BuildActionMap for a device, the page also shows these names as callouts on the image of the device, with lines pointing to the device objects to which the actions have been mapped.

The user now has the opportunity to reassign game actions by first choosing a control then choosing an action from the menu. When the user closes the property sheet, the method returns and the modifications are stored in the DIACTIONFORMAT structure that you passed in. You can now pass the same structure to IDirectInputDevice8::SetActionMap in order to implement the new mapping scheme.


Force Feedback
Microsoft DirectX 9.0 SDK Update (October 2004)

Force Feedback

Force feedback is the generation of push or resistance in an input/output device—for example, by motors mounted in the base of a joystick. Microsoft DirectInput enables you to generate force-feedback effects for devices that have compatible drivers.

The following sections introduce the elements of force feedback:

  • Basic Concepts of Force Feedback
  • Changing an Effect
  • Creating an Effect
  • Downloading and Unloading Effects
  • Effect Direction
  • Effect Enumeration
  • Effect Object Enumeration
  • Effect Playback
  • Envelopes and Offsets
  • Force-Feedback State
  • Gain
  • Information About a Supported Effect
  • Loading Effects from a File

  • Effect Types


Basic Concepts of Force Feedback
Microsoft DirectX 9.0 SDK Update (October 2004)

Basic Concepts of Force Feedback

A particular instance of force feedback is called an effect, and the push or resistance is called the force. Most effects fall into one of the following categories:

  • Constant force. A steady force in a single direction.
  • Ramp force. A force that steadily increases or decreases in magnitude.
  • Periodic effect. A force that pulsates according to a defined wave pattern.
  • Condition. A reaction to motion or position along an axis. Two examples are a friction effect that generates resistance to movement of the joystick, and a spring effect that pushes the stick back toward a certain position after it has been moved from that position.

The strength of the force is called its magnitude. Magnitude is measured in units ranging from 0 (no force) through 10,000 (maximum force for the device, defined for C/C++ and Microsoft Visual Basic as DI_FFNOMINALMAX). A negative value indicates force in the opposite direction. Magnitudes are linear: a force of 10,000 is twice as great as one of 5,000.

Ramp forces have a beginning and ending magnitude. For a periodic effect, the basic magnitude is the force at the peak of the wave.

The direction of a force is the direction from which it comes. A positive force on a given axis pushes from the positive toward the negative.

Effects also have duration, measured in microseconds. Periodic effects have a period, or the duration of one cycle, also measured in microseconds. The phase of a periodic effect is the point along the wave at which playback begins.

The following illustration represents a sawtooth periodic effect with a magnitude of 5,000, or half the maximum force for the device. The horizontal axis represents the duration of the effect, and the vertical axis represents the magnitude. Points above the center line represent positive force in the direction defined for the effect, and points below the center line represent negative force, or force in the opposite direction.

Graph of sawtooth force feedback

A force may be further shaped by an envelope. An envelope defines an attack value and a fade value, which modify the beginning and ending magnitude of the effect. Attack and fade also have duration, which determines how long the magnitude takes to reach or fall away from the sustain value, the magnitude in the middle portion of the effect.

The following diagram shows an envelope. The attack level is set to 8,000 and the fade level to 1,000. The sustain level is defined by the basic magnitude of the force to which the envelope is being applied; in the example, it is 5,000. In this case, the attack is greater than the sustain, giving the effect an initial strong kick. Both the attack and the fade level can be either greater or less than the sustain level.

Graph of envelope force feedback

The next diagram shows the result of the envelope being applied to the periodic effect in the first diagram. The envelope is mirrored on the negative side of the magnitude. An attack value of 8,000 means that the initial magnitude of the force in either direction is 80 percent of the maximum possible.

Graph of sawtooth and envelope force feedback

Periodic effects and conditions can also be modified by the addition of an offset, which defines the amount by which the waveform is shifted up or down from the base level. The practical effect of applying a positive offset to the sawtooth example would be to strengthen the positive force and weaken the negative one—in other words, the force would peak more strongly in one direction than in the other.

Finally, the overall magnitude of an effect can be scaled by gain, which is analogous to a volume control in audio. A single gain value can be applied to all effects for a device. You might want to do this to compensate for stronger or weaker forces on different hardware or to accommodate the user's preferences.


Changing an Effect
Microsoft DirectX 9.0 SDK Update (October 2004)

Changing an Effect

You can modify the parameters of an effect, in some cases even while the effect is playing. Do this by using the IDirectInputEffect::SetParameters method.

The dwDynamicParams member of the DIEFFECTINFO structure tells you which effect parameters can be changed while an effect is playing. If you attempt to modify an effect parameter that cannot be modified while the effect is playing, and the effect is still playing, Microsoft DirectInput normally stops the effect, updates the parameters, and restarts the effect. You can override this default behavior by passing the DIEP_NORESTART flag.

The following code example changes the magnitude of the constant force that was set in the example under Creating an Effect.

DIEFFECT        diEffect;           // Parameters for effect
DICONSTANTFORCE diConstantForce;    // Type-specific parameters

diConstantForce.lMagnitude = 5000;
diEffect.dwSize = sizeof(DIEFFECT);
diEffect.cbTypeSpecificParams = sizeof(DICONSTANTFORCE);
diEffect.lpvTypeSpecificParams = &diConstantForce;
hr = lpdiEffect->SetParameters(&diEffect, DIEP_TYPESPECIFICPARAMS);

The DIEP_TYPESPECIFICPARAMS flag ensures that the transfer of data from the DIEFFECT structure is restricted to the relevant members, so that you do not have to initialize the entire structure and so that the minimum possible amount of data needs to be sent to the device.


Creating an Effect
Microsoft DirectX 9.0 SDK Update (October 2004)

Creating an Effect

Create an effect object by using the IDirectInputDevice8::CreateEffect method, as in the following code example, where g_lpdid points to an instance of the interface. This example creates a very simple effect that pulls the joystick away from the user at full force for half a second.

HRESULT  hr;
LPDIRECTINPUTEFFECT lpdiEffect;  // receives pointer to created effect
DIEFFECT diEffect;               // parameters for created effect

DWORD    dwAxes[2] = { DIJOFS_X, DIJOFS_Y };
LONG     lDirection[2] = { 18000, 0 };

DICONSTANTFORCE diConstantForce;

diConstantForce.lMagnitude = DI_FFNOMINALMAX;   // Full force

diEffect.dwSize          = sizeof(DIEFFECT);
diEffect.dwFlags         = DIEFF_POLAR | DIEFF_OBJECTOFFSETS;
diEffect.dwDuration      = (DWORD)(0.5 * DI_SECONDS);
diEffect.dwSamplePeriod  = 0;                 // = default
diEffect.dwGain          = DI_FFNOMINALMAX;   // No scaling
diEffect.dwTriggerButton = DIEB_NOTRIGGER;    // Not a button response
diEffect.dwTriggerRepeatInterval = 0;         // Not applicable
diEffect.cAxes                   = 2;
diEffect.rgdwAxes                = &dwAxes[0];
diEffect.rglDirection            = &lDirection[0];
diEffect.lpEnvelope              = NULL;
diEffect.cbTypeSpecificParams    = sizeof(DICONSTANTFORCE);
diEffect.lpvTypeSpecificParams   = &diConstantForce;

hr = g_lpdid->CreateEffect(GUID_ConstantForce,
                           &diEffect,
                           &lpdiEffect,
                           NULL);

In the method call, the first parameter identifies the supported effect with which the created effect is to be associated. The example uses one of the predefined globally unique identifier (GUID)s found in Dinput.h. If you use a predefined GUID, the call fails if the device does not support the effect.

The second parameter sets the parameters as specified in the DIEFFECT structure.

The third parameter receives a pointer to the effect object if the call is successful.

The DIEFF_POLAR flag specifies the type of coordinates used for the direction of the force. (See Effect Direction.) It is combined with DIEFF_OBJECTOFFSETS, which indicates that any buttons or axes used in other members are identified by their offsets within the DIDATAFORMAT structure for the device. The alternative is to use the DIEFF_OBJECTIDS flag, signifying that buttons and axes are identified by the dwType member of the DIDEVICEOBJECTINSTANCE structure returned for the object when it was enumerated with the IDirectInputDevice8::EnumObjects method.

For more information about the members of the DIEFFECT structure, see Effect Direction.


Downloading and Unloading Effects
Microsoft DirectX 9.0 SDK Update (October 2004)

Downloading and Unloading Effects

Before an effect can be played, it must be downloaded to the device. Downloading an effect means telling the driver to prepare the effect for playback. It is entirely up to the driver to determine how this is done. Generally, the driver places the parameters of the effect in hardware memory to minimize the subsequent transfer of data between the device and the system. The consequent reduction in latency is particularly important for conditions and for effects played in response to a trigger, such as a fire button. Ideally the device does not have to communicate with the system at all in order to respond to axis movements and button presses.

Downloading is done automatically when you create an effect, provided the device is not full and is acquired at the exclusive cooperative level. By default, it is also done when you start the effect or change its parameters.

If you specify the DIEP_NODOWNLOAD flag when changing parameters, you must subsequently use the IDirectInputEffect::Download method to download or update the effect.

When the device is unacquired—for example, when it has been acquired with the exclusive foreground cooperative level and the application moves to the background—effects are unloaded and must be downloaded again when the application regains the foreground. This is done automatically when you call the IDirectInputEffect::Start method, but you can choose to download all effects immediately on reacquiring the device. You always have to download effects associated with a trigger button, since the IDirectInputEffect::Start method is not normally called for such effects.

If your application gets the DIERR_DEVICEFULL error when downloading an effect, you must make room for the new effect by unloading an old one. You can remove an effect from the device by calling the IDirectInputEffect::Unload method. You can also remove all effects by resetting the device through a call to the IDirectInputDevice8::SendForceFeedbackCommand method.


Effect Direction
Microsoft DirectX 9.0 SDK Update (October 2004)

Effect Direction

Directions can be defined for one or more axes. As with the mouse and joystick, the x-axis increases from left to right, and the y-axis increases from far to near. For three-dimensional devices, the z-axis increases from up to down.

The direction of an effect is the direction from which it comes. An effect with a direction along the negative y-axis tends to push the stick along the positive y-axis (toward the user). If the user must push the stick toward the left to counteract an effect, the effect has a left direction; that is, it lies on the negative x-axis.

Direction can be expressed in polar, spherical, or Cartesian coordinates.

Polar coordinates are expressed as a single angle, in hundredths of a degree clockwise from whatever zero-point, or true north, has been established for the effect. Normally this is the negative y-axis; that is, away from the user. Thus an effect with a polar coordinate of 9,000 has a direction of east, or to the user's right, and the user must exert force to the right to counteract it.

Spherical coordinates are also in hundredths of a degree but can contain two or more angles For each angle, the direction is rotated in the positive direction of the next axis. For a 3-D device, the first angle would normally be rotated from the positive x-axis toward the positive y-axis (clockwise from east), and the second angle would be rotated toward the positive z-axis (down). Thus a force with a direction of (0, 0) would be to the user's right and parallel to the tabletop. A direction of 27,000 for the first angle and 4,500 for the second would be directly away from the user (270 degrees clockwise from east) and angling toward the floor (45 degrees downward from the tabletop); to counteract a force with this direction, the user would have to push forward and down.

Cartesian coordinates are similar to 3-D vectors. If you draw a straight line on graph paper with an origin of (0, 0) at the center of the page, the direction of the line can be defined by the coordinates of any intersection that it crosses, regardless of the distance from the origin. A direction of (1, —2) and a direction of (5, —10) are exactly the same.

Note The coordinates used in creating force-feedback effects define only direction, not magnitude or distance.

When an effect is created or modified, the cAxes, rgdwAxes, and rglDirection members of the DIEFFECT structure are used to specify the direction of the force.

The cAxes member specifies the number of axes involved in the effect. This will also be the number of elements in each of the arrays pointed to by the next two members.

The array pointed to by rgdwAxes identifies the axes to which the effects will be applied. If the DIEFF_OBJECTOFFSETS flag has been set, the axes are identified by the offsets within the data format structure. These offsets are most readily identified by using the DIJOFS_* defines. (For a list of these values, see Joystick Device Constants.)

Finally, the rglDirection member specifies the direction of the force.

Note The cAxes and rgdwAxes members cannot be modified once they have been set. An effect always has the same axis list.

Regardless of whether you are using Cartesian, polar, or spherical coordinates, you must provide exactly as many elements in rglDirection as there are axes in the array pointed to by rgdwAxes.

In the polar coordinate system, north (0 degrees) lies along the vector (0, —1), where the elements of the vector correspond to the elements in the axis list pointed to by rgdwAxes. Normally those axes are x and y, so north is directly along the negative y-axis; that is, away from the user. The last element of rglDirection must be 0.

In the example in Creating an Effect, the direction of a two-dimensional force is defined in polar coordinates. The force has a south direction—it comes from the direction of the user, so the user has to pull the stick to counteract it. The direction is 180 degrees clockwise from north, and can be assigned as follows:

LONG  lDirection[2] = { 18000, 0 };

For greater clarity, the assignment could also be expressed this way:

LONG  lDirection[2] = { 180 * DI_DEGREES, 0 };

For spherical coordinates, presuming that you are working with a three-axis device, the same direction is assigned as follows:

LONG  lDirection[3] = { 90 * DI_DEGREES, 0, 0 }

The first angle is measured in hundredths of a degree from the (1, 0) direction, rotated in the direction of (0, 1); the second angle is measured in hundredths of a degree toward (0, 0, 1). The elements of the vector notation again correspond to elements in the array pointed to by the rgdwAxes member. Assume that the elements of this array represent the x, y, and z axes, in that order. The point of origin is at x = 1 and y = 0; that is, to the user's right. The direction of rotation is toward the positive y-axis (0, 1); that is, toward the user, or clockwise. The force in the example is 90 degrees clockwise from the right; that is, south. Because the second element of lDirection is 0, there is no rotation on the third axis.

How do you accomplish the same thing with Cartesian coordinates? Presuming that you have used the DIEFF_CARTESIAN flag in the dwFlags member, you would specify the direction like this:

LONG  lDirection[2] = { 0, 1 };

Here again, the elements of the array correspond to the axes listed in the array pointed to by rgdwAxes. The example sets the x-axis to 0 and the y-axis to 1; that is, the direction lies directly along the positive y-axis, or to the south.

The theory of effect directions can be difficult to grasp, but the practice is fairly straightforward.

Examples of Setting Effect Direction

Single-Axis Effects

Setting up the direction for a single-axis effect is easy because there is nothing to specify. Put the DIEFF_CARTESIAN flag in the dwFlags member of the DIEFFECT structure and set rglDirection to point to a single LONG containing the value 0.

The following code example sets up the direction and axis parameters for an x-axis effect:

DIEFFECT eff;
LONG     lZero  = 0;                       // No direction
DWORD    dwAxis = DIJOFS_X;                // X-axis effect

ZeroMemory(&eff, sizeof(eff));
eff.cAxes        = 1;                                     // One axis
eff.dwFlags      = DIEFF_CARTESIAN | DIEFF_OBJECTOFFSETS; // Flags
eff.rglDirection = &lZero;                                // Direction
eff.rgdwAxes     = &dwAxis;                         // Axis for effect

Two-Axis Effects with Polar Coordinates

Setting up the direction for a polar two-axis effect is only a little more complicated. Set the DIEFF_POLAR flag in dwFlags and set rglDirection to point to an array of two LONGs. The first element in this array is the direction from which you want the effect to come. The second element in the array must be 0.

The following example sets up the direction and axis parameters for a two-axis effect coming from the east:

DIEFFECT eff;
LONG     rglDirection[2] = { 90 * DI_DEGREES, 0 };
DWORD    rgdwAxes[2]     = { DIJOFS_X, DIJOFS_Y };   // X- and y-axis

ZeroMemory(&eff, sizeof(eff));
eff.cAxes        = 2;                                  // Two axes
eff.dwFlags      = DIEFF_POLAR | DIEFF_OBJECTOFFSETS;  // Flags
eff.rglDirection = rglDirection;                       // Direction
eff.rgdwAxes     = rgdwAxes;                     // Axis for effect

Two-Axis Effects with Cartesian Coordinates

Setting up the direction for a Cartesian two-axis effect is a bit trickier. Set the DIEFF_CARTESIAN flag in dwFlags, and again set rglDirection to point to an array of two LONGs. This time the first element in the array is the x-coordinate of the direction vector, and the second is the y-coordinate.

The following code example sets up the direction and axis parameters for a two-axis effect coming from the east:

DIEFFECT eff;
LONG     rglDirection[2] = { 1, 0 };            // Positive x = east
DWORD    rgdwAxes[2]     = { DIJOFS_X, DIJOFS_Y };  // X- and y-axis

ZeroMemory(&eff, sizeof(eff));
eff.cAxes = 2;                                       // Two axes
eff.dwFlags = DIEFF_CARTESIAN | DIEFF_OBJECTOFFSETS; // Flags
eff.rglDirection = rglDirection;                     // Direction
eff.rgdwAxes = rgdwAxes;                       // Axis for effect


Effect Enumeration
Microsoft DirectX 9.0 SDK Update (October 2004)

Effect Enumeration

The IDirectInputDevice8::EnumEffects method returns information about the support offered by the device for various kinds of effects.

It is important to distinguish between supported effectsand created effects, or effect objects. A supported effect is a basic type which a device is capable of playing, such as a constant force. However, a constant force by itself has no properties such as magnitude, direction, duration, attack, or fade. These properties are set when you create a specific effect object in your application by shaping the raw effect type with an envelope or setting the values of a DIEFFECT structure. A supported effect can be represented by many effect objects, each with different parameters—for example, several constant forces, each with different duration, magnitude, and direction.

For information about enumerating created effects, see Effect Object Enumeration.

Like other Microsoft DirectInput enumerations, the IDirectInputDevice8::EnumEffects method requires a callback function. This is documented with the placeholder name DIEnumEffectsCallback, but you can use a different name if you prefer. This function is called for each effect enumerated. Within the function you can obtain the globally unique identifier (GUID) for each effect, get information about the extent of hardware support, and create one or more effect objects whose methods you can use to manipulate the effect.

The following code example sets the enumeration in motion. Assume that g_lpdid is an initialized pointer to the IDirectInputDevice8 interface of the device.

HRESULT hr = g_lpdid->EnumEffects(&DIEnumEffectsCallback,
        g_lpdid, DIEFT_ALL);

A skeletal callback is shown in the following code. The pvRef parameter of the callback could be any 32-bit value, but in this case it is a pointer to the device interface (the global g_lpdid in the previous example), which is used for getting information about effects supported by the device and for creating effect objects.

BOOL CALLBACK DIEnumEffectsCallback(LPCDIEFFECTINFO pdei,
                                LPVOID pvRef)
{
    HRESULT              hr;
    LPDIRECTINPUTDEVICE8 lpdid = (LPDIRECTINPUTDEVICE8)pvRef;
// Pointer to calling device
    LPDIRECTINPUTEFFECT  lpdiEffect;      // Pointer to created effect
    DIEFFECT             diEffect;        // Params for created effect
    DICONSTANTFORCE      diConstantForce; // Type-specific parameters

    if (DIEFT_GETTYPE(pdei->dwEffType) == DIEFT_CONSTANTFORCE)
    {
       /* Here you can extract information about support for the
          effect type (from pdei), and tailor your effects
          accordingly. For example, the device might not support
          envelopes for this type of effect. */
       .
       .
       .
       // Create one or more constant force effects.
       // For each, you have to initialize a DICONSTANTFORCE
       // and a DIEFFECT structure.
       .
       .
       .
        hr = lpdid->CreateEffect(pdei->guid,
                                &diEffect,
                                &lpdiEffect,
                                NULL);
       .
       .
       .
    }
    // And so on for other types of effect
   .
   .
   .

    return DIENUM_CONTINUE;
}  // End of callback

For a detailed example of creating an effect, and for more information about how to initialize an effect, see Creating an Effect.


Effect Object Enumeration
Microsoft DirectX 9.0 SDK Update (October 2004)

Effect Object Enumeration

When you need to examine or manipulate all the effects you have created, you can use the IDirectInputDevice8::EnumCreatedEffectObjects method. As no flags are currently defined for this method, you cannot restrict the enumeration to particular kinds of effects; all effects will be enumerated.

Note This method enumerates created effects, not effects supported by a device. For more information about the distinction between the two, see Effect Enumeration.

Like other Microsoft DirectInput enumerations, the IDirectInputDevice8::EnumCreatedEffectObjects method requires a callback function. This standard callback is documented with the placeholder name DIEnumCreatedEffectObjectsCallback, but you can use a different name. The function is called for each effect enumerated. Within the function, you can perform any processing you want. However, it is not safe to create a new effect while enumeration is going on.

The following is a skeletal example of the callback function. The pvRef parameter of the callback can be any 32-bit value; in this case, it is a pointer to the IDirectInputDevice8 interface that is performing the enumeration.

HRESULT  hr;

BOOL CALLBACK DIEnumCreatedEffectObjectsCallback(
                             LPDIRECTINPUTEFFECT peff, LPVOID pvRef);
{
    LPDIRECTINPUTDEVICE pdid = (IDirectInputDevice*)pvRef;
                                        // Pointer to calling device
    DIEFFECT            diEffect;      // Params for created effect

    diEffect.dwSize = sizeof(DIEFFECTINFO);
    peff->GetParameters(&diEffect, DIEP_ALLPARAMS);
    // Check or set parameters, or do anything else.
    .
    .
    .
}  // End of callback

Here's the call that sets the enumeration in motion, passing in the DirectInputDevice pointer lpdid:

hr = lpdid->EnumCreatedEffectObjects(
         &DIEnumCreatedEffectObjectsCallback,
         &lpdid, 0);


Effect Playback
Microsoft DirectX 9.0 SDK Update (October 2004)

Effect Playback

There are two principal ways to start playback of an effect: manually by a call to the IDirectInputEffect::Start method, or automatically in response to a button press. Playback also starts when you change an effect by calling the IDirectInputEffect::SetParameters method with the DIEP_START flag.

Passing INFINITE in the dwIterations parameter of the IDirectInputEffect::Start method has the effect of playing the effect repeatedly, with the envelope being applied each time. If you want to repeat an effect without repeating the envelope—for example, to begin with a strong kick, then settle down to a steady throb—set dwIterations to 1, and set the dwDuration member of the DIEFFECT structure to INFINITE. (This is the structure passed to the IDirectInputDevice8::CreateEffect method.)

Note Some devices do not support multiple iterations of an effect, and they accept only the value 1 in the dwIterations parameter to the IDirectInputEffect::Start method. Always check the return value from IDirectInputEffect::Start to be sure the effect played successfully.

To associate an effect with a button press, set the dwTriggerButton member of the DIEFFECT structure. Also set the dwTriggerRepeatIntervalmember to the desired delay between playbacks when the button is held down. This is the interval, in microseconds, between the end of one playback and the start of the next.

Note On some devices, multiple effects cannot be triggered by the same button. If you associate more than one effect with a button, the last effect downloaded is the one triggered. Also, trigger repeat interval might not be supported.

To dissociate an effect from its trigger button, either call the IDirectInputEffect::Unload method or set the parameters for the effect with dwTriggerButton set to DIEB_NOTRIGGER.

Triggered effects, like all others, are lost when the application loses access to the device. To make them active again, download them as soon as the application reacquires the device. See Downloading and Unloading Effects. This step is not necessary for effects not associated with a trigger, because they are automatically downloaded if necessary whenever the IDirectInputEffect::Start method is called.

If an effect has a finite duration and is started by a call to the IDirectInputEffect::Start method, it stops playing when the time has elapsed. If its duration was set to INFINITE, playback ends only when the IDirectInputEffect::Stop method is called. An effect associated with a trigger button starts when the button is pressed and stops when the button is released or the duration has elapsed, whichever comes sooner.


Envelopes and Offsets
Microsoft DirectX 9.0 SDK Update (October 2004)

Envelopes and Offsets

You can modify the basic magnitude of some effects by applying an envelope and an offset. For an overview, see Basic Concepts of Force Feedback.

To apply an envelope when creating or modifying an effect, initialize a DIENVELOPE structure and put a pointer to it in the lpEnvelope member of the DIEFFECT structure.

The device driver determines which effects support envelopes. Typically, you can apply an envelope to a constant force, a ramp force, or a periodic effect, but not to a condition. To determine whether a particular effect supports an envelope, call the IDirectInputDevice8::GetEffectInfo method and check for the DIEP_ENVELOPE flag in the dwStaticParams member of the DIEFFECTINFO structure.

To apply an offset, set the lOffset member of the DIPERIODIC or DICONDITION structure pointed to by the lpvTypeSpecificParams member of the DIEFFECT structure. For periodic effects, the absolute value of the offset plus the magnitude of the effect must not exceed DI_FFNOMINALMAX.

You cannot apply an offset to a constant force or ramp force. In these cases, you can achieve the same effect by altering the magnitude.


Force-Feedback State
Microsoft DirectX 9.0 SDK Update (October 2004)

Force-Feedback State

The IDirectInputDevice8::SendForceFeedbackCommand method enables you to turn off the device's actuators (effectively causing it to ignore any effects that are being played), pause, stop, or continue playback of effects, and reset the device so that all downloaded effects are removed.

To retrieve the current force-feedback state, use the IDirectInputDevice8::GetForceFeedbackState method. This method returns information about whether the actuators are active, whether playback is paused, and whether the device has been reset. It also retrieves information about various switches and whether the device is currently powered.


Gain
Microsoft DirectX 9.0 SDK Update (October 2004)

Gain

You might want to scale the force of your effects according to the force exerted by different devices. For example, if an application's effects feel right on a device that puts out a maximum force of n newtons on a given axis, you might want to adjust the gain for a device that puts out more force. (You cannot use the gain to increase the maximum force of the axis, so you should set the basic effect magnitudes to values suitable for devices that put out less force.)

Gain can also be used to decrease the magnitude of a hardware-defined effect.

The actual force generated by a device object such as an axis or button is returned in the dwFFMaxForce member of the DIDEVICEOBJECTINSTANCE structure when objects are enumerated. (See Device Object Enumeration.)

You can set the gain for the entire device by using the IDirectInputDevice8::SetProperty method.

You must set the gain for individual effects when creating them by putting a value in the dwGain member of the DIEFFECT structure. (If dwGain is 0, the effect will not be felt.) You can change this value later by using IDirectInputEffect::SetParameters, passing DIEP_GAIN in the dwFlags parameter.

The purpose of setting the device gain is to allow your application to have control over the strength of all effects all at once. For example, you might have a slider control in your application to enable the user to specify how strong the force-feedback effects should be, such as the master volume control on a sound mixer. When the device gain is set, your application does not need to adjust the gain of each individual effect to suit the user's preferences.

A gain value can be in the range from 0 through 10,000, where 10,000 indicates that magnitudes are not to be scaled, 7,500 means that forces are to be scaled to 75 percent of their nominal magnitudes, and so on.


Information About a Supported Effect
Microsoft DirectX 9.0 SDK Update (October 2004)

Information About a Supported Effect

The IDirectInputDevice8::GetEffectInfo method can be used to retrieve information about the device's support for an effect whose globally unique identifier (GUID) is known. It retrieves the same information that is returned in the DIEFFECTINFO structure during enumeration. For more information, see Effect Enumeration.

The following code fetches information about an effect whose GUID is stored in the EffectGuid variable, and determines whether the direction of the effect can be changed without stopping and restarting it:

DIEFFECTINFO diEffectInfo;
diEffectInfo.dwSize = sizeof(DIEFFECTINFO);
g_lpdid->GetEffectInfo(&diEffectInfo, EffectGuid);
if (diEffectInfo.dwDynamicParams & DIEP_DIRECTION)
{
  // Can reset parameter dynamically
}


Loading Effects from a File
Microsoft DirectX 9.0 SDK Update (October 2004)

Loading Effects from a File

Using the Force Editor supplied with the Microsoft DirectX software development kit (SDK), or another application that uses the same file format, you can design effects and save them in a file. You can then use these effects in any application by loading them at run time.

To load effects, call the IDirectInputDevice8::EnumEffectsInFile method. By default, the enumeration is limited to the standard Microsoft DirectInput effects, but you can enumerate other effects by setting the DIFEF_INCLUDENONSTANDARD flag. By setting the DIFEF_MODIFYIFNEEDED flag, you can also instruct DirectInput to modify the parameters of effects, if necessary, so that they work on the device. (For example, an effect authored for two axes can be made to work on a single-axis steering wheel.)

In the following code example, the first three standard effects are loaded from a file and created as DirectInputEffect objects.

// g_lpdid is a valid IDirectInputDevice8 pointer to a
// force feedback device.

// The array of effect pointers is declared globally.
LPDIRECTINPUTEFFECT pEff[3];
.
.
.
g_lpdid->EnumEffectsInFile("FEdit1.ffe",
                            EnumEffectsInFileProc,
                            NULL,
                            DIFEF_MODIFYIFNEEDED);
.
.
.

The following callback function is called once for each effect in the file or until it returns DIENUM_STOP. Note that because the DIFEF_MODIFYIFNEEDED flag was passed, the effect parameters may have been modified in lpdife->lpDiEffect. The callback creates the effect with these modified parameters.

BOOL CALLBACK EnumEffectsInFileProc(LPCDIFILEEFFECT lpdife,
        LPVOID pvRef)

{
    HRESULT     hr;
    static int  i;

    hr = g_lpdid->CreateEffect(lpdife->GuidEffect,
                               lpdife->lpDiEffect,
                               &pEff[i],
                               NULL);
    if (FAILED(hr))
    {
        // Error handling
    }
    if (++i > 2) return DIENUM_STOP;
    else return DIENUM_CONTINUE;
}


Effect Types
Microsoft DirectX 9.0 SDK Update (October 2004)

Effect Types

This section contains information about force-feedback effects.

  • Conditions
  • Constant Forces
  • Custom Forces
  • Device-Specific Effects
  • Periodic Effects
  • Ramp Forces


Conditions
Microsoft DirectX 9.0 SDK Update (October 2004)

Conditions

Conditions are forces applied in response to current sensor values within the device. In other words, conditions require information about device motion, such as position or velocity of a joystick handle.

In general, conditions are not associated with individual events during a game or other application. They represent ambient phenomena, such as the stiffness or looseness of a flight stick, or the tendency of a steering wheel to return to a straight-ahead position.

A condition does not have a predefined magnitude. The magnitude is scaled in proportion to the movement or position of the input object.

Microsoft DirectInput defines the following types of condition effects:

  • Friction. The force is applied when the axis is moved and depends on the defined friction coefficient.
  • Damper. The force increases in proportion to the velocity with which the user moves the axis.
  • Inertia. The force increases in proportion to the acceleration of the axis.
  • Spring. The force increases in proportion to the distance of the axis from a defined neutral point.

Most hardware devices do not support the application of envelopes to conditions.

Conditions have the following type-specific parameters:

Offset | The offset from the zero reading of the appropriate sensor value at which the condition begins to be applied. For a spring effect, the neutral point—that is, the point along the axis at which the spring would be considered at rest—would be defined by the offset for the condition. For a damper, the offset would define the greatest velocity value for which damping force is zero. Offset is not normally used for inertia or friction effects.
Coefficient | A multiplier that scales the effect. For some devices, you can set separate coefficients for the positive and negative direction along the axis associated with the condition. For example, a flight stick controlling a damaged aircraft might move more easily to the right than to the left.
Saturation | In force feedback, saturation is an expression of the maximum possible force for an effect. For example, suppose a flight stick has a spring condition on the x-axis. The offset is 0 and the coefficient is 10,000, so the maximum force is normally exerted when the stick is furthest from the center. But if you define a positive and negative saturation of 5,000, the force does not increase after the stick has been moved halfway to the right or left. Not all devices support saturation.
Deadband | The deadband is a zone around the offset of an axis at which the condition is not active. In the case of a spring that is at rest in the middle of an axis, the deadband enlarges this area of rest. Not all devices support deadband.

Conditions can have duration, although in most cases you would probably want to set the duration to infinite (—1) and stop the effect only in response to some event in the application.

To create a condition, pass one of the following values in the rguid parameter of the IDirectInputDevice8::CreateEffect method:

  • GUID_Spring
  • GUID_Damper
  • GUID_Inertia
  • GUID_Friction

You can also pass any other globally unique identifier (GUID) obtained by the IDirectInputDevice8::EnumEffects method, provided the low byte of the dwEffType member of the DIEFFECTINFO structure (DIEFT_GETTYPE(dwEffType)) is equal to DIEFT_CONDITION. In this way, you can use hardware-specific conditions designed by the manufacturer.

The type-specific structure for conditions is DICONDITION. For multiple-axis conditions, you can provide an array of such structures, one for each axis, or a single structure that defines the condition in the specified direction. In either case, you must set the cbTypeSpecificParams member of the DIEFFECT structure to the number of bytes used; that is, to sizeof(DICONDITION) * n, where n is the number of structures provided. For more information about how to use either single or multiple structures, see the DICONDITION structure.

An application should call the IDirectInputDevice8::GetEffectInfo method or the IDirectInputDevice8::EnumEffects method and examine the dwEffType member of the DIEFFECTINFO structure to determine whether both a positive and a negative coefficient and saturation for the effect are supported on the device. If the effect does not return the DIEFT_POSNEGCOEFFICIENTS flag, it ignores the value in the lNegativeCoefficient member, and the value in lPositiveCoefficient is applied to the entire axis. Likewise, if the effect does not return the DIEFT_POSNEGSATURATION flag, it ignores the value in dwNegativeSaturation, and the value in dwPositiveSaturation is used as the negative saturation level. Finally, if the effect does not return the DIEFT_SATURATION flag, it ignores both the dwPositiveSaturation and dwNegativeSaturation values, and no saturation is applied.

You should also check DIEFFECTINFO.dwEffType for the DIEFT_DEADBAND flag, to see if deadband is supported for the condition. If it is not supported, the value in the lDeadBand member of the DICONDITION structure will be ignored.

You can set a coefficient to a negative value, and this has the effect of generating the force in the opposite direction. For example, for a spring effect, it would cause the spring to push away from the offset point rather than pulling toward it.


Constant Forces
Microsoft DirectX 9.0 SDK Update (October 2004)

Constant Forces

A constant force is a force with a defined magnitude and duration.

You can apply an envelope to a constant force to give it shape. For example, suppose you have an effect with a nominal magnitude of 2,000 and a duration of 2 seconds. Then you apply an envelope with the following values:

Parameter | Value
Attack time | 0.5 second
Initial attack level | 5,000
Fade time | 1 second
Fade level | 0

When you play the effect, you get the following:

Elapsed time | Magnitude
0.0 | 5,000
0.1 | 4,400
0.2 | 3,800
0.3 | 3,200
0.4 | 2,600
0.5 | 2,000
(Duration of sustain) | 2,000
1.0: | 2,000
1.1 | 1,800
1.2 | 1,600
1.3 | 1,400
1.4 | 1,200
1.5 | 1,000
1.6 | 800
1.7 | 600
1.8 | 400
1.9 | 200
2.0 | 0

You cannot apply an offset to a constant force.

To create a constant force, pass GUID_ConstantForce to the IDirectInputDevice8::CreateEffect method. You can also pass any other globally unique identifier (GUID) obtained by the IDirectInputDevice8::EnumEffects method, provided the low byte of the dwEffType member of the DIEFFECTINFO structure (DIEFT_GETTYPE(dwEffType)) is equal to DIEFT_CONSTANTFORCE. In this way, you can use hardware-specific forces designed by the manufacturer such as a "constant" force that actually varies in magnitude in a seemingly random fashion to simulate turbulence.

A constant force uses a DICONSTANTFORCE structure to define the magnitude. A negative magnitude has the effect of reversing the direction of the force.


Custom Forces
Microsoft DirectX 9.0 SDK Update (October 2004)

Custom Forces

Application writers can create their own effects by creating a custom force. A custom force is an array of constant force values played back by the device.

The type-specific structure for custom waveform effects is DICUSTOMFORCE.

Set the dwSamplePeriod member of the DICUSTOMFORCE structure and the dwSamplePeriod member of the DIEFFECT structure to the same value. This is the time, in milliseconds, for which each element in the array of forces is played.

The custom force is played repeatedly until the time set in the dwDuration member of the DIEFFECT structure has elapsed.


Device-Specific Effects
Microsoft DirectX 9.0 SDK Update (October 2004)

Device-Specific Effects

Hardware drivers can support special effects that do not fit into the categories defined by Microsoft DirectInput. The type-specific parameters for these effects may be either hard-coded or modifiable by the application.

If type-specific parameters are modifiable, the application developer must obtain a header file declaring the data structure required by the effect.

The hardware vendor must provide a globally unique identifier (GUID) identifying the device-specific effect and might provide a custom structure for the type-specific parameters of the effect. Your application then must initialize a DIEFFECT structure and a type-specific structure, as with any other effect. You then call the IDirectInputDevice8::CreateEffect method, passing the device-specific GUID and a pointer to the DIEFFECT structure.

When you obtain information about a device-specific effect in a DIEFFECTINFO structure, the low byte of the dwEffType member (DIEFT_GETTYPE(dwEffType)) indicates into which of the predefined DirectInput effect categories (constant force, ramp force, periodic, or condition) the effect falls. If it does not fall into any of the predefined categories, the value is DIEFT_HARDWARE.

If a device-specific effect falls into one of the predefined categories, the lpvTypeSpecificParams member of the DIEFFECT structure must point to the corresponding DICONSTANTFORCE, DIRAMPFORCE, DIPERIODIC, or DICONDITION structure, and the cbTypeSpecificParams member must be equal to the size of that structure.

If (DIEFT_GETTYPE(dwEffType) == DIEFT_HARDWARE), the values of the lpvTypeSpecificParams and cbTypeSpecificParams members depend on whether the effect requires custom type-specific parameters. If it does, these values must refer to the appropriate structure defined in the manufacturer's header file and declared and initialized by your application. If the effect does not require custom parameters—that is, if the dwStaticParams member of the DIEFFECTINFO structure for the hardware effect does not have the DIEP_TYPESPECIFICPARAMS flag—lpvTypeSpecificParams must be NULL and cbTypeSpecificParams must be 0.

DirectInput passes the GUID and the DIEFFECT structure to the device driver for verification. If the GUID is unknown, the device returns DIERR_DEVICENOTREG. If the GUID is known but the type-specific data is incorrect for that effect, the device returns DIERR_INVALIDPARAM.


Periodic Effects
Microsoft DirectX 9.0 SDK Update (October 2004)

Periodic Effects

Periodic effects are waveform effects. Microsoft DirectInput defines the following waveforms.

  • Square.
  • Sine.
  • Cosine.
  • Triangle.
  • SawtoothUp. The waveform drops vertically after it reaches maximum positive force. See Basic Concepts of Force Feedback for an example.
  • SawtoothDown. The waveform rises vertically after it reaches maximum negative force.

An envelope can be applied to periodic effects. See the example in Basic Concepts of Force Feedback.

The phase of a periodic effect is the point along the waveform where the effect begins. Phase is measured in hundredths of a degree, from 0 to 35,999. The following table indicates where selected phase values (in degrees) lie along the various waveforms. Max is the top (+) or bottom (—) of the wave, and Mid is the midpoint, where no force is applied in either direction.

Waveform | 0 | 90 | 180 | 270
Square | +Max | +Max | —Max | —Max
Sine | Mid | +Max | Mid | —Max
Triangle | +Max | Mid | —Max | Mid
SawtoothUp | —Max | —Max/2 | Mid | +Max/2 (reaches +Max just before the cycle repeats)
SawtoothDown | +Max | +Max/2 | Mid | —Max/2 (reaches —Max just before the cycle repeats)

A driver may round off a phase value to the nearest supported value. For example, for a sine effect some drivers support only values of 0 and 9,000 (to create a cosine); for other effects, only values of 0 and 18,000 are supported.

To create a periodic force, pass one of the following values in the rguid parameter of the IDirectInputDevice8::CreateEffect method:

  • GUID_Square
  • GUID_Sine
  • GUID_Triangle
  • GUID_SawtoothUp
  • GUID_SawtoothDown

You can also pass any other globally unique identifier (GUID) obtained by the IDirectInputDevice8::EnumEffects method, provided the low byte of the dwEffType member of the DIEFFECTINFO structure (DIEFT_GETTYPE(dwEffType)) is equal to DIEFT_PERIODIC. In this way, you can use hardware-specific forces designed by the manufacturer. For example, a hardware device might support a periodic effect that rotates the stick in a small circle.

The type-specific structure for periodic effects is DIPERIODIC.

Do not confuse the period of a periodic effect (DIPERIODIC.dwPeriod) with the sample period (DIEFFECT.dwSamplePeriod). The period is the time that it takes to go through a complete wave cycle. The sample period, as for all effects, is the minimum time between actual adjustments of magnitude.


Ramp Forces
Microsoft DirectX 9.0 SDK Update (October 2004)

Ramp Forces

A ramp force is a force with defined starting and ending magnitudes and a finite duration. A ramp force can continue in a single direction, or it can start as a strong push in one direction, weaken, stop, and then strengthen in the opposite direction.

The following illustration shows a ramp force that starts at a magnitude of -5,000 and ends at 5,000:

Graph of ramp force

You can apply an envelope to a ramp force to shape it further. The following diagram shows the effect of applying an envelope, shown in green, to the ramp force in the previous diagram.

Graph of ramp force with envelope

Note that during the sustain portion of the envelope, the magnitude of the effect follows the same straight line as before the envelope was applied. For the duration of the attack and fade, the slope of the ramp is modified by the attack and fade levels.

You cannot apply an offset to a ramp force.

To create a ramp force, pass GUID_RampForce to the IDirectInputDevice8::CreateEffect method. You can also pass any other globally unique identifier (GUID) obtained by the IDirectInputDevice8::EnumEffects method, provided the low byte of the dwEffType member of the DIEFFECTINFO structure (DIEFT_GETTYPE(dwEffType)) is equal to DIEFT_RAMPFORCE. In this way, you can use hardware-specific ramp forces designed by the manufacturer.

A ramp force uses a DIRAMPFORCE structure to define the starting and ending magnitude of the force, whereas the duration is taken from the DIEFFECT structure. Duration must never be set to INFINITE.


Programming Tips and Tools
Microsoft DirectX 9.0 SDK Update (October 2004)

Programming Tips and Tools

This topic covers the following specialized programming tips.

  • Designing for Previous Versions of DirectInput
  • Preventing Response Delays During Debugging
  • Avoiding Duplicate Registry Keys
  • Force Editor
  • GetDeviceData and an Unacquired Device

Designing for Previous Versions of DirectInput

In the DirectInput8Create, IDirectInput8::Initialize, IDirectInputDevice8::Initialize, and IDirectInputEffect::Initialize methods, you are required to pass the Microsoft DirectInput version number. This parameter specifies which version of Microsoft DirectX the DirectInput subsystem should emulate.

Applications designed for the latest version of DirectInput should pass the value DIRECTINPUT_VERSION as defined in Dinput.h.

Applications designed to run under previous versions should pass a value corresponding to the version of DirectInput for which they were designed, with the main version number in the high-order byte. For example, an application designed to run on DirectInput 3.0 should pass a value of 0x0300.

If you define DIRECTINPUT_VERSION as 0x0300 before including the Dinput.h header file, the header file generates structure definitions compatible with DirectInput 3.0.

If you do not define DIRECTINPUT_VERSION before including the Dinput.h header file, the header file generates structure definitions compatible with the current version of DirectInput. However, the DirectX 3–compatible structures are available under the same names with "_DX3" appended. For example, the DirectX 3–compatible DIDEVCAPS structure is called DIDEVCAPS_DX3.

You must also use the appropriate versions of the DirectInput and DirectInputDevice interfaces. For versions of DirectX prior to DirectX 7.0, you must use IDirectInput and either IDirectInputDevice or IDirectInputDevice2 (the latter is available for DirectX 5.0 or later.)

Preventing Response Delays During Debugging

When using the keyboard or mouse with DirectInput under Microsoft Windows 2000, you might notice short delays in response when you step through code during a debugging session. This behavior occurs only in debug mode, so it is not seen by your application's end users. However, this behavior can be eliminated in debug mode as well by adding the emulation value to the following registry key.

HKEY_LOCAL_MACHINE
    SOFTWARE
        Microsoft
            DirectInput
Name | Type | Data
Emulation | DWORD | 0x08 (for the keyboard) 0x10 (for the mouse) 0x18 (for both)

You can also switch to use emulation from the DirectX control panel by following these steps.

  1. Open the Windows control panel
  2. Open the DirectX control panel. Note that if you are using Windows XP, you might need to click Switch to Classic View to see the DirectX icon.
  3. Select the DirectInput tab.
  4. In the Debug Input Device Emulation section, you can check the Emulate Keyboard and Emulate Mouse boxes.

Without changing how DirectInput returns data, this value invokes an emulation mode that is not susceptible to those delays. These settings are global and affect all DirectInput clients. Performance only improves when using the debug binaries and only for applications that employ foreground exclusive device access. Some features, such as masking the Windows keys, are not available when devices are emulated so emulation is recommended only for debugging.

Note If you are using earlier versions of DirectX, you must do a debug software development kit (SDK) install in order to get the correct debug dynamic-link library (DLL) onto your computer.

Avoiding Duplicate Registry Keys

For every application that uses DirectInput 8.0 or later versions, DirectInput creates a key in the following registry.

HKEY_CURRENT_USER
    SOFTWARE
        Microsoft
            DirectInput

This allows the independent hardware vendors (IHVs) to turn off their own device mapping for certain applications. During debugging, however, each build will generate a new key which contains a time stamp and the file size. To avoid generating multiple keys in the registry, use the binary value, AppIdFlag.

The following table lists the possible values for AppIdFlag.

1 | The time stamp is ignored when generating the key.
2 | The file size is ignored when generating the key.
3 | Both the time stamp and file size are ignored when generating the key.

If AppIdFlag is set to 3, all builds of applications with the same file name will use the same key.

Note The AppIdFlag value should only be set on test computers to avoid the possibility of two applications that ship with the same file name interfering with each other's input control mappings.

Force Editor

Force Editor has the following characteristics.

Description

The Force Editor application enables you to design force-feedback effects and test them singly or in combination. Effects can be saved to file and then loaded into DirectInput applications.

Path

Executable: (SDK root)\Bin\Dxutils\Fedit.exe

User's Guide

The Force Editor has its own documentation. When you've launched Fedit.exe, press F1 for online Help. The Help file can also be launched directly.

(SDK root)\Bin\Dxutils\Fedit.chm

GetDeviceData and an Unacquired Device

When using the debug version of Microsoft DirectPlay, you may notice some unusual behavior from the IDirectInputDevice8::GetDeviceData method when a device is unacquired. If you call IDirectInputDevice8::GetDeviceData and the device is not acquired, random bytes will be placed in the device data buffer and the value of the pdwInOut parameter will not be changed. Therefore, if your application does not check for the DPNERR_UNACQUIRED error code, your application will mistakenly determine that there is data in the buffer.


DirectInput C/C++ Tutorials
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectInput C/C++ Tutorials

This section contains five tutorials, each providing step-by-step instructions for implementing basic Microsoft DirectInput functionality in a C or C++ application.

Tutorials

  • Tutorial 1: Using the Keyboard
  • Tutorial 2: Using the Mouse
  • Tutorial 3: Using the Joystick
  • Tutorial 4: Using Force Feedback
  • Tutorial 5: Using Action Mapping

Note These tutorials are written using C++ style function calls. For instructions on writing Microsoft DirectX function calls in a C environment, see Using C to Access COM Objects.


Tutorial 1: Using the Keyboard
Microsoft DirectX 9.0 SDK Update (October 2004)

Tutorial 1: Using the Keyboard

To prepare for keyboard input, first create an instance of a Microsoft DirectInput object. You then use the IDirectInput8::CreateDevice method to create an instance of an IDirectInputDevice8 interface. The IDirectInputDevice8 interface methods are used to manipulate the device, set its behavior, and retrieve data.

This tutorial divides the required tasks into the following steps.

  • Step 1: Creating the DirectInput Object
  • Step 2: Creating the DirectInput Keyboard Device
  • Step 3: Setting the Keyboard Data Format
  • Step 4: Setting the Keyboard Behavior
  • Step 5: Gaining Access to the Keyboard
  • Step 6: Retrieving Data from the Keyboard
  • Step 7: Closing Down the DirectInput System

Adding DirectInput keyboard support to an application is relatively simple, so this tutorial is not based on the complete Keyboard Sample application. All of the tutorial steps are illustrated by code fragments within the text. All related steps for initializing the system are gathered in Sample Function 1: DI_Init. Another function, Sample Function 2: DI_Term, is called whenever the system needs to be closed down. Much of the content of these functions are reused in subsequent tutorials.


Step 1: Creating the DirectInput Object
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 1: Creating the DirectInput Object

The first step in setting up the Microsoft DirectInput system is to create a single DirectInput object as overall manager. This is done with a call to the DirectInput8Create function.

// HINSTANCE  g_hinst; // initialized earlier
HRESULT         hr;
LPDIRECTINPUT8  g_lpDI;

hr = DirectInput8Create(g_hinst, DIRECTINPUT_VERSION,
        IID_IDirectInput8, (void**)&g_lpDI, NULL);
if FAILED(hr)
{
    // DirectInput not available; take appropriate action
}

The first parameter for DirectInput8Create is the instance handle to the application or dynamic-link library (DLL) that is creating the object.

The second parameter tells the DirectInput object which version of the DirectInput system should be used. You can design your application to be compatible with earlier versions of DirectInput. For more information, see Designing for Previous Versions of DirectInput.

The third parameter determines which interface is returned. Most applications obtain the most recent version, by passing IID_IDirectInput8.

The fourth parameter is the address of a variable that is initialized with a valid interface pointer if the call succeeds.

The last parameter specifies the address of the controlling object's IUnknown interface for use in Component Object Model (COM) aggregation. Because most applications do not use aggregation, the value of this parameter is usually NULL.

After creating a single DirectInput object as overall manager, go to Step 2: Creating the DirectInput Keyboard Device.


Step 2: Creating the DirectInput Keyboard Device
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 2: Creating the DirectInput Keyboard Device

After creating the Microsoft DirectInput object, your application must create the keyboard object—the device—and retrieve a pointer to an IDirectInputDevice8 interface. The device performs most of the keyboard-related tasks, using the methods of the interface.

To do this your application must call the IDirectInput8::CreateDevice method, as shown in Sample Function 1: DI_Init. IDirectInput8::CreateDevice accepts three parameters.

The first parameter is the globally unique identifier (GUID) for the device being created. Because the system keyboard is used, your application should pass the GUID_SysKeyboard predefined global variable.

The second parameter is the address of a variable that is initialized with the interface pointer if the call succeeds.

The third parameter specifies the address of the controlling object's IUnknown interface for use in COM aggregation. Because most applications do not use aggregation, the value of this parameter is usually NULL.

The following example attempts to retrieve a pointer to an IDirectInputDevice8 interface. If this fails, it calls the DI_Term application-defined sample function to deallocate existing DirectInput objects, if any.

Note In all the examples, g_lpdi is the initialized pointer to the DirectInput object.
HRESULT               hr;
LPDIRECTINPUTDEVICE8  g_lpDIDevice

hr = g_lpDI->CreateDevice(GUID_SysKeyboard, &g_lpDIDevice, NULL);
if FAILED(hr) {
    DI_Term();
    return FALSE;
}

After creating the DirectInput keyboard device, go to Step 3: Setting the Keyboard Data Format.


Step 3: Setting the Keyboard Data Format
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 3: Setting the Keyboard Data Format

After retrieving an IDirectInputDevice8 pointer, your application must set the device's data format, as shown in Tutorial 1 Samples. For keyboards, this is a very simple task. Call the IDirectInputDevice8::SetDataFormat method, specifying the data format provided by Microsoft DirectInput in the c_dfDIKeyboard global variable.

The following example attempts to set the data format. If this fails, it calls the DI_Term sample function to deallocate existing DirectInput objects, if any.

hr = g_lpDIDevice->SetDataFormat(&c_dfDIKeyboard);

if FAILED(hr) {
    DI_Term();
    return FALSE;
}

After setting the keyboard data format, go to Step 4: Setting the Keyboard Behavior.


Step 4: Setting the Keyboard Behavior
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 4: Setting the Keyboard Behavior

Before your application can gain access to the keyboard, it must set the device's behavior using the IDirectInputDevice8::SetCooperativeLevel method, as shown in Tutorial 1 Samples. This method accepts the handle to the window to be associated with the device and a combination of flags that determine the cooperative level. In this case the application is requesting foreground, nonexclusive access.

The following example attempts to set the device's cooperative level. If this fails, it calls the DI_Term application-defined sample function to deallocate existing Microsoft DirectInput objects, if any.

// Set the cooperative level

hr = g_lpDIDevice->SetCooperativeLevel(g_hwndMain,
        DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);

 if FAILED(hr) {
    DI_Term();
    return FALSE;
}

After setting the keyboard behavior, go to Step 5: Gaining Access to the Keyboard.


Step 5: Gaining Access to the Keyboard
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 5: Gaining Access to the Keyboard

After your application sets the keyboard's behavior, it can acquire access to the device by calling the IDirectInputDevice8::Acquire method. The application must acquire the device before retrieving data from it. The IDirectInputDevice8::Acquire method accepts no parameters.

The following line of sample code acquires the keyboard device that was created in Step 2: Creating the DirectInput Keyboard Device.

if (g_lpDIDevice) g_lpDIDevice->Acquire();

Now that your application has acquired access to the keyboard, go to Step 6: Retrieving Data from the Keyboard.


Step 6: Retrieving Data from the Keyboard
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 6: Retrieving Data from the Keyboard

After a device is acquired, your application can start retrieving data from it. The simplest way to do this is to call the IDirectInputDevice8::GetDeviceState method, which takes a snapshot of the device's state at the time of the call.

The IDirectInputDevice8::GetDeviceState method accepts two parameters: the size of a buffer to be filled with device state data, and a pointer to that buffer. For keyboards, always declare a buffer of 256 unsigned bytes.

The following sample attempts to retrieve the state of the keyboard. If this fails, it calls an application-defined sample function to deallocate existing Microsoft DirectInput objects, if any. For more information, see Sample Function 2: DI_Term.

After retrieving the keyboard's current state, your application can respond to specific keys that were pressed down at the time of the call. Each element in the buffer represents a key. If an element's high bit is 1, the key was down at the moment of the call; otherwise, the key was up. To check the state of a given key, use the DirectInput Keyboard Device to index the buffer for a given key.

The following skeleton function, called from the main loop of a hypothetical spaceship game, uses the IDirectInputDevice8::GetDeviceState method to poll the keyboard. It then checks to see if the LEFT ARROW, RIGHT ARROW, UP ARROW or DOWN ARROW keys were pressed when the device state was retrieved. This is accomplished with the KEYDOWN macro defined in the body of the function. The macro accepts a buffer's variable name and an index value, and then checks the byte at the specified index to see if the high bit is set and returns TRUE if it is.

void WINAPI ProcessKBInput()
{
    #define KEYDOWN(name, key) (name[key] & 0x80)

     char     buffer[256];
    HRESULT  hr;

    hr = g_lpDIDevice->GetDeviceState(sizeof(buffer),(LPVOID)&buffer);
    if FAILED(hr)
    {
        // If it failed, the device has probably been lost.
        // Check for (hr == DIERR_INPUTLOST)
        // and attempt to reacquire it here.
        return;
    }

     // Turn the spaceship right or left
    if (KEYDOWN(buffer, DIK_RIGHT));
        // Turn right.
    else if(KEYDOWN(buffer, DIK_LEFT));
        // Turn left.

     // Thrust or stop the spaceship
    if (KEYDOWN(buffer, DIK_UP)) ;
        // Move the spaceship forward.
    else if (KEYDOWN(buffer, DIK_DOWN));
        // Stop the spaceship.
}

Now that your application can retrieve data from the keyboard, go to Step 7: Closing Down the DirectInput System.


Step 7: Closing Down the DirectInput System
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 7: Closing Down the DirectInput System

When an application is about to close, it should destroy all Microsoft DirectInput objects. This is a three-step process.

  • Release access to all DirectInput devices (IDirectInputDevice8::Unacquire).
  • Release all DirectInput devices (IDirectInputDevice8::Release).
  • Release the DirectInput object (IDirectInput8::Release).

For a sample function that closes down the DirectInput system, see Sample Function 2: DI_Term.


Tutorial 1 Samples
Microsoft DirectX 9.0 SDK Update (October 2004)

Tutorial 1 Samples

Sample Function 1: DI_Init

This application-defined sample function creates a Microsoft DirectInput object, initializes it, and retrieves the necessary interface pointers, assigning them to global variables. When initialization is complete, it acquires the device.

If any part of the initialization fails, this function calls the DI_Term application-defined sample function to deallocate DirectInput objects and interface pointers in preparation for terminating the program. For more information, see Sample Function 2: DI_Term.

In addition to creating the DirectInput object, the DI_Init function performs the tasks discussed in the following tutorial steps.

  • Step 2: Creating the DirectInput Keyboard Device
  • Step 3: Setting the Keyboard Data Format
  • Step 4: Setting the Keyboard Behavior
  • Step 5: Gaining Access to the Keyboard

The following is the DI_Init function.

/* The following variables are presumed to be initialized:
HINSTANCE             g_hinst;    // application instance
HWND                  g_hwndMain; // application window
*/

LPDIRECTINPUT8        g_lpDI;
LPDIRECTINPUTDEVICE8  g_lpDIDevice;

BOOL WINAPI DI_Init()
{
    HRESULT hr;

    // Create the DirectInput object.
    hr = DirectInput8Create(g_hinst, DIRECTINPUT_VERSION,
                            IID_IDirectInput8, (void**)&g_lpDI, NULL);

    if FAILED(hr) return FALSE;

    // Retrieve a pointer to an IDirectInputDevice8 interface
    hr = g_lpDI->CreateDevice(GUID_SysKeyboard, &g_lpDIDevice, NULL);

    if FAILED(hr)
    {
        DI_Term();
        return FALSE;
    }

    // Now that you have an IDirectInputDevice8 interface, get
    // it ready to use.

    // Set the data format using the predefined keyboard data
    // format provided by the DirectInput object for keyboards.

    hr = g_lpDIDevice->SetDataFormat(&c_dfDIKeyboard);

    if FAILED(hr)
    {
        DI_Term();
        return FALSE;
    }

    // Set the cooperative level
    hr = g_lpDIDevice->SetCooperativeLevel(g_hwndMain,
                             DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
    if FAILED(hr)
    {
        DI_Term();
        return FALSE;
    }

    // Get access to the input device.
    hr = g_lpDIDevice->Acquire();
    if FAILED(hr)
    {
        DI_Term();
        return FALSE;
    }

    return TRUE;
}

Sample Function 2: DI_Term

This application-defined sample function deallocates existing DirectInput interface pointers in preparation for program shutdown or in the event of a failure to properly initialize a device.

/* The following variables are presumed initialized:
LPDIRECTINPUT8        g_lpDI;
LPDIRECTINPUTDEVICE8  g_lpDIDevice;
*/

void WINAPI DI_Term()
{
    if (g_lpDI)
    {
        if (g_lpDIDevice)
        {
        // Always unacquire device before calling Release().
            g_lpDIDevice-&gt;Unacquire();
            g_lpDIDevice-&gt;Release();
            g_lpDIDevice = NULL;
        }
        g_lpDI-&gt;Release();
        g_lpDI = NULL;
    }
}

For additional DirectInput tutorials, see DirectInput C/C++ Tutorials.


Tutorial 2: Using the Mouse
Microsoft DirectX 9.0 SDK Update (October 2004)

Tutorial 2: Using the Mouse

This tutorial guides you through the process of setting up a mouse device and retrieving buffered input data. The examples are based on the Scrawl Sample.

To prepare for mouse input, you first create an instance of a Microsoft DirectInput object. Then you use the IDirectInput8::CreateDevice method to create an instance of an IDirectInputDevice8 interface. The IDirectInputDevice8 interface methods are used to manipulate the device, set its behavior, and retrieve data.

The first step of setting up the DirectInput system and the final step of closing it down are the same for any application and are covered in Tutorial 1: Using the Keyboard.

This tutorial divides the required tasks into the following steps.

  • Step 1: Creating the DirectInput Mouse Device
  • Step 2: Setting the Mouse Data Format
  • Step 3: Setting the Mouse Behavior
  • Step 4: Preparing for Buffered Input from the Mouse
  • Step 5: Managing Access to the Mouse
  • Step 6: Retrieving Buffered Data from the Mouse
Note When an application acquires the mouse at the exclusive cooperative level, Microsoft Windows does not show a pointer on the screen. For this, your application needs a simple sprite engine. The Scrawl sample application uses the Microsoft Win32 function DrawIcon to display a crosshair cursor.


Step 1: Creating the DirectInput Mouse Device
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 1: Creating the DirectInput Mouse Device

After creating the Microsoft DirectInput object, your application should retrieve a pointer to an IDirectInputDevice8 interface, which is used to perform most mouse-related tasks. To do this, call the IDirectInput8::CreateDevice method.

The first parameter of IDirectInput8::CreateDevice is the globally unique identifier (GUID) for the device your application is creating. In this case, because the system mouse is used, your application should pass the predefined global variable GUID_SysMouse.

The second parameter is the address of a variable that is initialized with a valid IDirectInputDevice8 interface pointer if the call succeeds.

The third parameter specifies the address of the controlling object's IUnknown for use in COM aggregation. Because most applications do not use aggregation, the value of this parameter is usually NULL.

The following sample code attempts to retrieve a pointer to an IDirectInputDevice8 interface. If the call fails, FALSE is returned. It is assumed that g_pDI is a valid pointer to IDirectInput8.

LPDIRECTINPUTDEVICE g_pMouse;
HRESULT             hr;

hr = g_pDI->CreateDevice(GUID_SysMouse, &g_pMouse, NULL);

if (FAILED(hr)) {
    return FALSE;
}

After creating the DirectInput mouse device, go to Step 2: Setting the Mouse Data Format.


Step 2: Setting the Mouse Data Format
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 2: Setting the Mouse Data Format

After retrieving an IDirectInputDevice8 pointer, your application must set the device's data format. For mouse devices, this is a very simple task. Call the IDirectInputDevice8::SetDataFormat method, specifying the data format provided for your convenience by Microsoft DirectInput in the c_dfDIMouse global variable.

The following code fragment attempts to set the device's data format. If the call fails, FALSE is returned.

hr = g_pMouse->SetDataFormat(&c_dfDIMouse);

if (FAILED(hr)) {
    return FALSE;
}

After setting the mouse data format, go to Step 3: Setting the Mouse Behavior.


Step 3: Setting the Mouse Behavior
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 3: Setting the Mouse Behavior

Before it can gain access to the mouse, your application must set the mouse device's behavior using the IDirectInputDevice8::SetCooperativeLevel method. This method accepts the handle to the window to be associated with the device. In Scrawl, the DISCL_EXCLUSIVE flag is included to ensure that this application is the only one that can have exclusive access to the device. This flag is combined with DISCL_FOREGROUND because Scrawl should not allow data input when another application is in the foreground.

The following code sample attempts to set the device's cooperative level. If this attempt fails, FALSE is returned. It is assumed that hWnd is a valid window handle.

hr = g_pMouse->SetCooperativeLevel(hWnd,
               DISCL_EXCLUSIVE | DISCL_FOREGROUND);

if (FAILED(hr)) {
    return FALSE;
}

After setting the mouse behavior, go to Step 4: Preparing for Buffered Input from the Mouse.


Step 4: Preparing for Buffered Input from the Mouse
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 4: Preparing for Buffered Input from the Mouse

The Scrawl application demonstrates how to use event notification to find out about mouse activity, and how to read buffered input from the mouse. Both of these techniques require some setup. You can perform these steps at any time after creating the mouse device and before acquiring it.

First, create an event and associate it with the mouse device. You are instructing Microsoft DirectInput to notify the mouse device object whenever a hardware interrupt indicates that new data is available.

This is how it is done in Scrawl, where g_hevtMouse is a global HANDLE.

g_hMouseEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

if (g_hMouseEvent == NULL) {
    return FALSE;
}

hr = g_pMouse->SetEventNotification(g_hMouseEvent);

if (FAILED(hr)) {
    return FALSE;
}

Now set the buffer size so that DirectInput can store any input data until you are ready to view it. Note that by default the buffer size is zero, so this step is essential if you want to use buffered data.

It is not necessary to used buffered data with event notification. If you prefer, you can retrieve immediate data when an event is signaled.

To set the buffer size, initialize a DIPROPDWORD structure with information about itself and about the property you want to set. Most of the values are boilerplate. The key value is the last one, dwData, which is initialized with the number of items you want the buffer to hold.

#define SAMPLE_BUFFER_SIZE  16

DIPROPDWORD dipdw;
    // the header
    dipdw.diph.dwSize       = sizeof(DIPROPDWORD);
    dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
    dipdw.diph.dwObj        = 0;
    dipdw.diph.dwHow        = DIPH_DEVICE;
    // the data
    dipdw.dwData            = SAMPLE_BUFFER_SIZE;

You then pass the address of the header (the DIPROPHEADER structure within the DIPROPDWORD structure ), along with the identifier of the property you want to change, to the IDirectInputDevice8::SetProperty method, as follows:

hr = g_pMouse->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph);

if (FAILED(hr)) {
    return FALSE;
}

The setup is now complete, and you are ready to acquire the mouse and start collecting data.

After preparing your application for buffered input from the mouse, go to Step 5: Managing Access to the Mouse.


Step 5: Managing Access to the Mouse
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 5: Managing Access to the Mouse

Microsoft DirectInput provides the IDirectInputDevice8::Acquire and IDirectInputDevice8::Unacquire methods to manage device access. Your application must call the IDirectInputDevice8::Acquire method to gain access to the device before requesting mouse information with the IDirectInputDevice8::GetDeviceState and IDirectInputDevice8::GetDeviceData methods.

Most of the time your application has the device in an acquired state. However, if you have only foreground access, the mouse is automatically unacquired whenever your application moves to the background. You are responsible for reacquiring it when you get the focus back again. This can be done in response to a WM_ACTIVATE message.

Scrawl handles this message by setting a global variable, g_bActive, according to whether the application is gaining or losing the focus. It then calls a helper function, SetAcquire, which acquires the mouse if g_bActive is TRUE and unacquires it otherwise.

case WM_ACTIVATE:
    if (WA_INACTIVE == wParam)
        g_bActive = FALSE;
    else
        g_bActive = TRUE;

    // Set exclusive mode access to the mouse based on active state
    SetAcquire();
    return 0;

If you have exclusive access, your application might need to unacquire the mouse to enable the user to interact with Microsoft Windows—for example, to access a menu or a dialog box. In Scrawl this can happen when the user opens the system menu with ALT+SPACEBAR.

The Scrawl window procedure has a handler for WM_ENTERMENULOOP that responds by setting the global variable g_bActive to FALSE and calling the SetAcquire function. This handler enables Windows to have the mouse and display its own cursor.

When the user is done using a menu, Windows sends the application a WM_EXITSIZEMOVE message. In this case, the Scrawl window process sets g_bActive appropriately and calls SetAcquire.

Scrawl also unacquires the mouse in response to a right-button click, which displays a shortcut menu. Although the mouse would get unacquired later, in the WM_ENTERMENULOOP handler, it is unacquired here first so that the position of the Windows cursor can be set before the menu appears.

Finally, Scrawl tries to reacquire the mouse if it receives a DIERR_INPUTLOST error after an attempt to retrieve data. This is in case the device has been unacquired by some mechanism not covered elsewhere; for instance, if the user has pressed CTRL+ALT+DEL.

In summary, your application needs to acquire the mouse before it can get data from it. This needs to be done only once, as long as nothing happens to force your application to surrender access to it. In exclusive mode, you are responsible for giving up control of the mouse when Windows needs it. You are also responsible for reacquiring the mouse whenever your program needs access to it after losing it to Windows or another application.

Once your application can manage access to the mouse, go to Step 6: Retrieving Buffered Data from the Mouse.


Step 6: Retrieving Buffered Data from the Mouse
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 6: Retrieving Buffered Data from the Mouse

Once the mouse is acquired, your application can begin to retrieve data from it.

In the Scrawl sample, retrieval is triggered by a signaled event. In the WinMain function, the application sleeps until MsgWaitForMultipleObjects indicates that there is either a signal or a message. If there is a signal associated with the mouse, the OnMouseInput function is called. This function is a good illustration of how buffered input is handled, as shown in the following process.

First, the function makes sure that the old cursor position is cleaned up. Note that Scrawl is maintaining its own cursor and is wholly responsible for drawing and erasing it.

VOID OnMouseInput(HWND hWnd)
{
    /* Invalidate the old cursor so that it will be erased */
    InvalidateCursorRect(hWnd);

Next, the function enters a loop to read and respond to the entire contents of the buffer. Because it retrieves just one item at a time, it needs only a single DIDEVICEOBJECTDATA structure to hold the data.

    while (!bDone) {
        DIDEVICEOBJECTDATA od;
        DWORD dwElements = 1;   // number of items to be retrieved
Note Another way to go about handling input would be to read the entire buffer at once and then loop through the retrieved items, responding to each one in turn. In that case, dwElements would be the size of the buffer, and od would be an array with the same number of elements.

The application calls the IDirectInputDevice8::GetDeviceData method in order to fetch the data. The second parameter tells Microsoft DirectInput where to put the data, and the third tells it how many items are wanted. The final parameter would be DIGDD_PEEK if the data was to be left in the buffer, but in this case the data is not needed again, and so it is removed.

        hr = g_pMouse->GetDeviceData(sizeof(DIDEVICEOBJECTDATA),
                                     &od, &dwElements, 0);

Next, the application checks to see if access to the device has been lost and, if so, attempts to reacquire the mouse at the first opportunity. This step was discussed in Step 5: Managing Access to the Mouse.

        if (hr == DIERR_INPUTLOST)
        {
            SetAcquire();
            break;
        }

Next, the application makes sure the call to the IDirectInputDevice8::GetDeviceData method succeeded and that there was actually data to be retrieved. Note that after the call to IDirectInputDevice8::GetDeviceData the dwElements variable shows how many items were actually retrieved.

        /* Unable to read data or no data available */

        if (FAILED(hr) || dwElements == 0)
        {
            break;
        }

If execution has proceeded to this point, the call succeeded and there is an item of data in the buffer. Now the application looks at the dwOfs member of the DIDEVICEOBJECTDATA structure to determine which object on the device reported a change of state, and it calls helper functions to respond appropriately. The value of the dwData member, which contains information about what occurred with the device object, is passed to these functions.

        /* View the element to see what occurred */

        switch (od.dwOfs)
        {
            // Mouse horizontal motion
            case DIMOFS_X:
                UpdateCursorPosition(od.dwData, 0);
                break;

            // Mouse vertical motion
            case DIMOFS_Y:
                UpdateCursorPosition(0, od.dwData);
                break;

            // DIMOFS_BUTTON0: Right button pressed or released
            case DIMOFS_BUTTON0:

            // DIMOFS_BUTTON1: Left button pressed or released
            case DIMOFS_BUTTON1:
                // Is the right button or a swapped left button down?
                if((g_bSwapMouseButtons &&
                               DIMOFS_BUTTON1 == od.dwOfs) ||
                   (!g_bSwapMouseButtons &&
                               DIMOFS_BUTTON0 == od.dwOfs))
                {
                    if (od.dwData & 0x80)  // Left button pressed, so
                                           // go into button-down mode
                    {
                        bDone = TRUE;
                        OnLeftButtonDown(hWnd);
                    }
                // Is the left button or a swapped right button down?
                if((g_bSwapMouseButtons &&
                               DIMOFS_BUTTON0 == od.dwOfs) ||
                   (!g_bSwapMouseButtons &&
                               DIMOFS_BUTTON1 == od.dwOfs))
                {
                    if(!(od.dwData & 0x80))  // button release, so
                                             // check shortcut menu
                    {
                        bDone = TRUE;
                        OnRightButtonUp(hWnd);
                    }
                }
                break;
        }

Finally, in the event that the cursor has been moved by one of the helper functions, the OnMouseInput sample function invalidates the screen rectangle occupied by the cursor.

    // Invalidate the new cursor so that it will be drawn
    InvalidateCursorRect(hWnd);
}

Scrawl also collects mouse data in the OnLeftButtonDown function. This is where the application keeps track of mouse movements while the primary button is being held down—that is, while the user is drawing. This function does not rely on event notification, but repeatedly polls the DirectInput buffer until the button is released.

Note that in the OnLeftButtonDown function no drawing is done until all pending data has been read. This is because each horizontal or vertical movement of the mouse is reported as a separate event. (Both events are, however, placed in the buffer at the same time. ) If a line were immediately drawn in response to each separate axis movement, a diagonal mouse movement would produce two lines at right angles.

Another way you can be sure that the movement in both axes is taken into account before responding in your application is to check the sequence numbers of the x-axis item and the y-axis item. If the numbers are the same, the two events took place simultaneously. For more information, see Time Stamps and Sequence Numbers.

For additional DirectInput tutorials, see DirectInput C/C++ Tutorials.


Tutorial 3: Using the Joystick
Microsoft DirectX 9.0 SDK Update (October 2004)

Tutorial 3: Using the Joystick

This tutorial shows you how to enumerate a joystick attached to a system and set it up for input. Code samples are based on the Joystick Sample.

The first step of setting up the Microsoft DirectInput system and the final step of closing it down are the same for any application and are covered in Tutorial 1: Using the Keyboard.

The first step in this tutorial is to enumerate devices; that is, to see what joysticks are available. As part of this process you initialize each joystick device and set its desired characteristics. You then use the IDirectInputDevice8 interface methods to retrieve data from each joystick.

This tutorial divides the required tasks into the following steps.

Steps

  • Step 1: Enumerating the Joysticks
  • Step 2: Creating the DirectInput Joystick Device
  • Step 3: Setting the Joystick Data Format
  • Step 4: Setting the Joystick Behavior
  • Step 5: Gaining Access to the Joystick
  • Step 6: Retrieving Data from the Joystick


Step 1: Enumerating the Joysticks
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 1: Enumerating the Joysticks

After creating the Microsoft DirectInput system, call the IDirectInput8::EnumDevices method to enumerate the joysticks, as in the following sample code.

//g_pDI is an initialized pointer to IDirectInput8
g_pDI->EnumDevices(DI8DEVCLASS_GAMECTRL, EnumJoysticksCallback,
                       NULL, DIEDFL_ATTACHEDONLY)

The DI8DEVCLASS_GAMECTRL constant, passed as the first parameter, specifies the class of device to be enumerated.

EnumJoysticksCallback is the address of a callback function to be called each time a joystick is found. This is where the individual devices are created in Step 2: Creating the DirectInput Joystick Device.

The third parameter can be any 32-bit value that you want to make available to the callback function. In this case, nothing is being sent.

The last parameter, DIEDFL_ATTACHEDONLY, is a flag that restricts enumeration to devices that are attached to the computer.

When your application can enumerate the joysticks, go to Step 2: Creating the DirectInput Joystick Device.


Step 2: Creating the DirectInput Joystick Device
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 2: Creating the DirectInput Joystick Device

After creating the Microsoft DirectInput object, the application must retrieve a pointer to an IDirectInputDevice8 interface, which is used to perform most joystick-related tasks. In the Joystick Sample, this is done in the callback function EnumJoysticksCallback, which is called each time a joystick is enumerated.

The following sample code is the first part of the callback function.

BOOL CALLBACK EnumJoysticksCallback(const DIDEVICEINSTANCE*
                                       pdidInstance, VOID* pContext)
{
    HRESULT hr;

    // Obtain an interface to the enumerated joystick.
    hr = g_pDI->CreateDevice(pdidInstance->guidInstance,
                                &g_pJoystick, NULL);
    if(FAILED(hr))
        return DIENUM_CONTINUE;

    return DIENUM_STOP;

The EnumJoysticksCallback callback function parameters are as follows:

  • A pointer to the device instance, supplied by the DirectInput system when the device is enumerated.
  • A pointer to a 32-bit value that you supplied as a parameter to IDirectInput8::EnumDevices. This parameter could be any 32-bit value such as a pointer to an interface so that you could use its methods. In this case, however, NULL was passed.

The first task of the callback function is to create the device. The IDirectInput8::CreateDevice method accepts three parameters.

The first parameter is a reference to the globally unique identifier (GUID) for the instance of the device. In this case, the GUID is taken from the DIDEVICEINSTANCE structure supplied by DirectInput when it enumerated the device.

The second parameter is the address of the variable that is initialized with a valid interface pointer if the call succeeds.

The third parameter specifies the address of the controlling object's IUnknown for use in COM aggregation. The Joystick Sample does not use aggregation, so the parameter is NULL.

Note that if the device interface cannot be created, DIENUM_CONTINUE is returned from the callback function. This flag instructs DirectInput to keep enumerating as long as there are devices to be enumerated.

After creating the DirectInput joystick device, go to Step 3: Setting the Joystick Data Format.


Step 3: Setting the Joystick Data Format
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 3: Setting the Joystick Data Format

Now that the application has a pointer to a Microsoft DirectInput device, it can call the IDirectInputDevice8 methods to manipulate that device. The first step, which is essential, is to set the data format for the joystick. This step tells DirectInput how to format the input data.

if (FAILED(hr = g_pJoystick->SetDataFormat(&c_dfDIJoystick2)))
    return hr;

The IDirectInputDevice8::SetDataFormat method takes one parameter, a pointer to a DIDATAFORMAT structure containing information about how the data for the device is to be formatted. For the joystick, you can use the predefined global variable c_dfDIJoystick2, which signifies use of the DIJOYSTATE2 structure to retrieve data.

After setting the joystick data format, go to Step 4: Setting the Joystick Behavior.


Step 4: Setting the Joystick Behavior
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 4: Setting the Joystick Behavior

The joystick device has been created, and its data format has been set. The next step is to set its cooperative level. As in the previous step, g_pJoystick is a pointer to the device interface.

if (FAILED(hr = g_pJoystick->SetCooperativeLevel(hDlg,
                    DISCL_EXCLUSIVE | DISCL_FOREGROUND)))
    return hr;

The first parameter to IDirectInputDevice8::SetCooperativeLevel is a window handle. In this case, the handle to the dialog box serving as the main program window is passed to the function.

The final parameter is a combination of flags describing the desired cooperative level. The Joystick sample requires input from the joystick only when it is the foreground application. Also, when the joystick sample is in the foreground, it should be the only application with exclusive access to the joystick. Therefore, the flags are set to DISCL_EXCLUSIVE | DISCL_FOREGROUND. See Cooperative Levels for a full explanation of these flags.

The next step is to gather information about the capabilities of the joystick. This information includes the number of axes, buttons, and other controllers, whether the device supports force feedback, and other details about the joystick's behavior and supported options.

A DIDEVCAPS structure is used to hold the capability information. The dwSize member of the DIDEVCAPS structure must first be initialized, then the address of the structure sent to IDirectInputDevice8::GetCapabilities. In the example below, g_diDevCaps is a previously declared DIDEVCAPS structure.

g_diDevCaps.dwSize = sizeof(DIDEVCAPS);
if (FAILED(hr = g_pJoystick->GetCapabilities(&g_diDevCaps)))
    return hr;

At this point, you could proceed using the device defaults or you could customize the device properties. The Joystick sample enumerate the axes on the joystick and sets a range for each by calling IDirectInputDevice8::EnumObjects.

if (FAILED(hr = g_pJoystick->EnumObjects(EnumAxesCallback,
                                       (VOID*)hDlg, DIDFT_AXIS)))
    return hr;

The first parameter to the IDirectInputDevice8::EnumObjects method, EnumAxesCallback, is the address of a callback function which processes the enumerated objects as desired.

The second parameter can be any 32-bit value that you might want to provide to the callback function. Here, the handle to the main dialog window is passed so that it can update the display to indicate which axes are found on the joystick.

The last parameter, DIDFT_AXIS, tells the callback function to enumerate only device axes.

In the sample, the properties changed will be the range for any axis or slider detected (a slider is considered an axis ).

By setting the range, you are telling Microsoft DirectInput what maximum and minimum values you want returned for an axis. If you set a range of -1,000 to +1,000 for the x-axis, as in the example, you are asking that a value of -1,000 be returned when the stick is at the extreme left, +1,000 when it is at the extreme right, and zero when it is in the middle.

The following sample code sets the range of an enumerated axis. The pdidoi variable is the address of a DIDEVICEOBJECTINSTANCE structure passed by the system to the callback function. This variable contains information about the object currently being enumerated.

DIPROPRANGE diprg;

diprg.diph.dwSize       = sizeof(DIPROPRANGE);
diprg.diph.dwHeaderSize = sizeof(DIPROPHEADER);
diprg.diph.dwHow        = DIPH_BYID;
diprg.diph.dwObj        = pdidoi->dwType;
diprg.lMin              = -1000;
diprg.lMax              = +1000;
.
.
hr = g_pJoystick->SetProperty(DIPROP_RANGE, &diprg.diph);
if (FAILED(hr))
    return DIENUM_STOP;

The first task here is to set up the DIPROPRANGE structure diprg, whose address is passed into the IDirectInputDevice8::SetProperty method. Note that it is not the address of the structure itself that is passed but rather the address of its first member, which is a DIPROPHEADER structure. For more information, see Device Properties.

The property header is initialized with the following values.

  • The size of the property structure
  • The size of the header structure
  • A flag to indicate how the dwObj member is to be interpreted.
  • The value found in the dwType member of the DIDEVICEOBJECTINSTANCE structure indicating the object whose property is being changed.

The lmin and lmax members of the DIPROPRANGE structure are assigned the desired range values.

The application now calls the IDirectInputDevice8::SetProperty method. The first parameter is a flag indicating which property is being changed. The second parameter is the address of the DIPROPHEADER member of the property structure.

After setting the joystick behavior, go to Step 5: Gaining Access to the Joystick.


Step 5: Gaining Access to the Joystick
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 5: Gaining Access to the Joystick

After your application sets a joystick's behavior, it can acquire access to the device by calling the IDirectInputDevice8::Acquire method. The application must acquire the device before retrieving data from it. The IDirectInputDevice8::Acquire method accepts no parameters.

The Joystick sample performs initial acquisition in the message loop as the application is activated. This loop also automatically reacquires the device whenever the application regains focus after having lost it. Acquisition is also performed if access to the joystick is lost or a DIERR_INPUTLOST error is returned when the application attempts to get input data. This is shown in the following code sample.

hr = g_pJoystick->Poll();
if (FAILED(hr))
{
    hr = g_pJoystick->Acquire();
    while(hr == DIERR_INPUTLOST)
        hr = g_pJoystick->Acquire();
    return S_OK;
}

Once your application can gain access to the joystick go to Step 6: Retrieving Data from the Joystick.


Step 6: Retrieving Data from the Joystick
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 6: Retrieving Data from the Joystick

Because your application is more likely concerned with the position of the joystick axes than with their movement, you probably want to retrieve immediate rather than buffered data from the device. You can do this by polling with IDirectInputDevice8::GetDeviceState. Note that not all device drivers notify Microsoft DirectInput when the state of the device changes. Therefore, it is always good policy to call the IDirectInputDevice8::Poll method before checking the device state.

The Joystick application calls the following function from the Microsoft Windows message loop.

HRESULT UpdateInputState(HWND hDlg)
{
    HRESULT     hr;
    CHAR        strText[128]; // Device state text
    DIJOYSTATE2 js;           // Direct Input joystick state
    CHAR*       str;

    if (NULL == g_pJoystick)
        return S_OK;

    // Poll the device to read the current state
    hr = g_pJoystick->Poll();
    if (FAILED(hr))
    {
        // Attempt to reacquire joystick
    }
    hr = g_pJoystick->GetDeviceState(sizeof(DIJOYSTATE2), &js);
    if (FAILED(hr))
        return hr;

Note the call to IDirectInputDevice8::GetDeviceState. The first parameter is the size of the structure in which the data is returned, and the second parameter is the address of this structure, which is of type DIJOYSTATE2. This structure holds data for up to six axes, 128 buttons, and four point-of-view hats. The sample program proceeds to view the state of all axes and buttons, and one slider. This information is then displayed in the main dialog window.

Joystick buttons work just like keys or mouse buttons. If the high bit of the returned byte is 1, the button is pressed.

For additional DirectInput tutorials, see DirectInput C/C++ Tutorials.


Tutorial 4: Using Force Feedback
Microsoft DirectX 9.0 SDK Update (October 2004)

Tutorial 4: Using Force Feedback

This tutorial takes you through the process of creating, playing, and modifying a simple effect on a force-feedback joystick. The effect is based on the feel of running a chain saw. Effects are created that simulate a chain saw starting with some difficulty, running normally, and cutting into wood.

The first step of setting up the Microsoft DirectInput system and the final step of closing it down are essentially the same for any application and are covered in Tutorial 1: Using the Keyboard. However, when closing down the DirectInput force-feedback system, you are required to take the additional step of releasing any effects you have created.

This tutorial divides the required tasks into the following steps.

  • Step 1: Enumerating Force-Feedback Devices
  • Step 2: Creating the DirectInput Force-Feedback Device
  • Step 3: Enumerating Supported Effects
  • Step 4: Creating an Effect
  • Step 5: Playing an Infinite Effect
  • Step 6: Changing an Effect


Step 1: Enumerating Force-Feedback Devices
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 1: Enumerating Force-Feedback Devices

The first step is to ensure that a force-feedback device is available on the system. You do this by calling the IDirectInput8::EnumDevices method. In the following example, the global pointer to the game device interface is initialized only if the enumeration has succeeded in finding at least one suitable device:

LPDIRECTINPUTDEVICE8  g_lpDIDevice = NULL;

hr = g_lpDI->EnumDevices(DI8DEVTYPE_GAMECTRL,
                         DIEnumDevicesProc,
                         NULL,
                         DIEDFL_FORCEFEEDBACK | DIEDFL_ATTACHEDONLY);
if (FAILED(hr))
{
  // No force-feedback joystick available; take appropriate action.
}

In the example, g_lpDI is an initialized pointer to the IDirectInput8 interface. The first parameter to IDirectInput8::EnumDevices restricts the enumeration to joystick-type devices. The second parameter is the callback function that is called whenever Microsoft DirectInput identifies a device that qualifies for enumeration. The third parameter is for user-defined data to be passed in or out of the callback function; in this case it is not used. Finally, the flags further restrict the enumeration to devices attached to the system that support force feedback.

The callback function is a convenient place to initialize the device as soon as it has been found. (It is assumed that the first device found is the one you want to use.) You do this in Step 2: Creating the DirectInput Force-Feedback Device.


Step 2: Creating the DirectInput Force-Feedback Device
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 2: Creating the DirectInput Force-Feedback Device

To have Microsoft DirectInput enumerate devices, create a callback function of the same type as DIEnumDevicesCallback. In Step 1 you passed the address of this function to the IDirectInput8::EnumDevices method.

DirectInput passes into the callback, as the first parameter, a pointer to a DIDEVICEINSTANCE structure that tells you what you need to know about the device. The structure member of most interest in the example is guidInstance, the unique identifier for the particular piece of hardware on the user's system. You must pass this globally unique identifier (GUID) to the IDirectInput8::CreateDevice method.

The following code fragment is the first part of the callback, which extracts the GUID and creates the device object.

BOOL CALLBACK DIEnumDevicesProc( LPCDIDEVICEINSTANCE lpddi,
                                 LPVOID pvRef )
{
    HRESULT hr;
    GUID DeviceGuid = lpddi->guidInstance;

    // Create game device.

    hr = g_lpDI->CreateDevice(DeviceGuid, &g_lpDIDevice, NULL);

    if (FAILED(hr))
        // Continue enumerating until successful or finished
        return DIENUM_CONTINUE;

The next steps of the callback function are similar to those for setting up any input device. Note that you need the exclusive cooperative level for any force-feedback device.

    // Set cooperative level.
    hr = g_lpDIDevice->SetCooperativeLevel(g_hwndMain,
                                  DISCL_EXCLUSIVE | DISCL_FOREGROUND);
    if (FAILED(hr))
        return hr;

    // set game data format
    hr = g_lpDIDevice->SetDataFormat(&c_dfDIJoystick);
    if (FAILED(hr))
        return hr;

Finally, you might want to turn off the device's autocenter feature. Autocenter is essentially a condition effect that uses the motors to simulate the springs in a standard joystick. It is a good idea to turn it off so that it does not interfere with other effects.

    DIPROPDWORD DIPropAutoCenter;

    DIPropAutoCenter.diph.dwSize       = sizeof(DIPropAutoCenter);
    DIPropAutoCenter.diph.dwHeaderSize = sizeof(DIPROPHEADER);
    DIPropAutoCenter.diph.dwObj        = 0;
    DIPropAutoCenter.diph.dwHow        = DIPH_DEVICE;
    DIPropAutoCenter.dwData            = DIPROPAUTOCENTER_OFF;

    hr = g_lpDIDevice->SetProperty(DIPROP_AUTOCENTER,
                                   &DIPropAutoCenter.diph);
    if (FAILED(hr))
    {
        // Handle the failure as appropriate
    }

    return DIENUM_STOP;   // One is enough.
}   // end DIEnumDevicesProc

Before using the device, you must acquire it. See Step 5: Gaining Access to the Joystick in Tutorial 3: Using the Joystick for an example of how to handle acquisition. Note that unlike other property changes, force-feedback effects can be downloaded to a device when it is in an acquired state.

After you have created the DirectInput force-feedback device, go to Step 3: Enumerating Supported Effects.


Step 3: Enumerating Supported Effects
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 3: Enumerating Supported Effects

Now that you have successfully enumerated and created a force-feedback device, you can enumerate the effect types it supports.

Effect enumeration is not strictly necessary if you want to create only standard effects that will be available on any device, such as constant forces. When creating the effect object, you can identify the desired effect type by using one of the predefined globally unique identifiers (GUIDs), such as GUID_ConstantForce. For a complete list of these identifiers, see IDirectInputDevice8::CreateEffect.

Another more flexible approach is to enumerate supported effects of a particular type, then obtain the GUID for the effect from the callback function. You could use the callback to obtain more information about the device's support for the effect— for example, whether it supports an envelope—but in this tutorial you obtain only the effect GUID.

First, create the callback function that Microsoft DirectInput calls for each effect enumerated. For information about this standard callback, see DIEnumEffectsCallback. You can give the function any name you like.

BOOL  EffectFound = FALSE;  // global flag
BOOL CALLBACK DIEnumEffectsProc(LPCDIEFFECTINFO pei, LPVOID pv)
{
    *((GUID *)pv) = pei->guid;
    EffectFound = TRUE;
    return DIENUM_STOP;  // one is enough
}

The GUID variable pointed to by the application-defined value pv is assigned the value passed in the DIEFFECTINFO structure created by DirectInput for the effect.

To obtain the effect GUID, set the callback in motion by calling the IDirectInputDevice8::EnumEffects method, as follows:

HRESULT  hr;
GUID     guidEffect;
hr = g_lpDIDevice->EnumEffects(
                         (LPDIENUMEFFECTSCALLBACK) DIEnumEffectsProc,
                          &guidEffect,
                          DIEFT_PERIODIC);
if (FAILED(hr))
{
    // Note that success does not mean that any effects were found,
    // only that the process went smoothly.
}

Note that you pass the address of a GUID variable, guidEffect, to the IDirectInputDevice8::EnumEffects method. This address is passed in turn to the callback as the pv parameter. You also restrict the enumeration to periodic effects by setting the flag DIEFT_PERIODIC.

Once your application can enumerate supported effects, go to Step 4: Creating an Effect.


Step 4: Creating an Effect
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 4: Creating an Effect

If the EffectFound value is no longer FALSE after effect enumeration, you can safely assume that Microsoft DirectInput has found support for at least one effect of the periodic type you requested by passing the DIEFT_PERIODIC flag. Knowing the effect globally unique identifier (GUID), you can now create the effect object.

Before calling the IDirectInputDevice8::CreateEffect method, you set up the following arrays and structures.

  • An array of axes that will be involved in the effect. For a joystick, this array normally consists of the identifiers for the x-axis and the y-axis.
  • An array of values for setting the direction. The values differ according to both the number of axes and whether you want to use polar, spherical, or Cartesian coordinates. For a full explanation, see Effect Direction.
  • A structure of type-specific parameters. In the example, because you are creating a periodic effect, this is of type DIPERIODIC.
  • A DIENVELOPE structure for defining an envelope to be applied to the effect.
  • A DIEFFECT structure to contain the basic parameters for the effect.

Arrays can be initialized when they, along with the structures, are declared.

DWORD      dwAxes[2] = {DIJOFS_X, DIJOFS_Y};
LONG       lDirection[2] = {0, 0};

DIPERIODIC diPeriodic;      // type-specific parameters
DIENVELOPE diEnvelope;      // envelope
DIEFFECT   diEffect;        // general parameters

Next, initialize the type-specific parameters. The values in this example create a full-force periodic effect with a period of one-twentieth of a second.

diPeriodic.dwMagnitude = DI_FFNOMINALMAX;
diPeriodic.lOffset = 0;
diPeriodic.dwPhase = 0;
diPeriodic.dwPeriod = (DWORD)(0.05 * DI_SECONDS);

To produce an effect of the chain-saw motor trying to start, briefly coughing into life, and then slowly dying, you set an envelope with an attack time of one-half second and a fade time of one second.

diEnvelope.dwSize = sizeof(DIENVELOPE);
diEnvelope.dwAttackLevel = 0;
diEnvelope.dwAttackTime = (DWORD)(0.5 * DI_SECONDS);
diEnvelope.dwFadeLevel = 0;
diEnvelope.dwFadeTime = (DWORD)(1.0 * DI_SECONDS);

Next, set up the basic effect parameters. These include flags to determine how the directions and device objects (buttons and axes) are identified, the sample period and gain for the effect, and pointers to the other data that you have just prepared. You also associate the effect with the joystick's fire button so that it is automatically played whenever that button is pressed.

diEffect.dwSize = sizeof(DIEFFECT);
diEffect.dwFlags = DIEFF_POLAR | DIEFF_OBJECTOFFSETS;
diEffect.dwDuration = (DWORD)(2 * DI_SECONDS);

diEffect.dwSamplePeriod = 0;               // = default
diEffect.dwGain = DI_FFNOMINALMAX;         // no scaling
diEffect.dwTriggerButton = DIJOFS_BUTTON0;
diEffect.dwTriggerRepeatInterval = 0;
diEffect.cAxes = 2;
diEffect.rgdwAxes = dwAxes;
diEffect.rglDirection = &lDirection[0];
diEffect.lpEnvelope = &diEnvelope;
diEffect.cbTypeSpecificParams = sizeof(diPeriodic);
diEffect.lpvTypeSpecificParams = &diPeriodic;

Finally, you can create the effect.

LPDIRECTINPUTEFFECT  g_lpdiEffect;  // global effect object

hr = g_lpDIDevice->CreateEffect(
                     guidEffect,     // GUID from enumeration
                     &diEffect,      // where the data is
                     &g_lpdiEffect,  // where to put interface pointer
                     NULL);          // no aggregation
if (FAILED(hr))
{
    return hr;
}

Note that, by default, the effect is downloaded to the device as soon as it has been created, provided that the device is in an acquired state at the exclusive cooperative level. You should now be able to compile, run, press the fire button, and feel the sputtering of a chain saw that's out of gas.

After creating an effect object, go to Step 5: Playing an Infinite Effect.


Step 5: Playing an Infinite Effect
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 5: Playing an Infinite Effect

The effect created in the previous step starts in response to the press of a button. To create an effect that is to be played in response to an explicit call, return to Step 4: Creating an Effect and modify the dwTriggerButton member of the DIEFFECT structure as follows:

diEffect.dwTriggerButton = DIEB_NOTRIGGER;

To make a chain saw that starts and keeps going, change the dwDuration member as follows:

diEffect.dwDuration = INFINITE;

Next, start the effect.

g_lpdiEffect->Start(1, 0);

The effect keeps running until you stop it.

g_lpdiEffect->Stop();

Note that it is not necessary to change the envelope you created in the previous step. The attack is played as the effect starts, but the fade value is ignored.

Once your application can play an infinite effect, go to Step 6: Changing an Effect.


Step 6: Changing an Effect
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 6: Changing an Effect

Next, you modify the effect to simulate the slowing down of the engine as the saw bites into wood. Microsoft DirectInput enables you to modify the parameters of an effect while it is playing.

To change the effect, set up a new DIEFFECT structure or have access to the one you used to create the effect. If you are setting up a new structure with local scope, initialize only the dwSize member and any members that contain or point to data that is to be changed.

In this case, you want to change a type-specific parameter—the period of the effect—so you need to have access to the DIPERIODIC structure you used when creating the effect. Alternatively, you can create a local copy with all members initialized. Make sure that the address of the DIPERIODIC structure is in the lpvTypeSpecificParams member of the DIEFFECT structure.

First, set the new period of the effect.

diPeriodic.dwPeriod = (DWORD)(0.08 * DI_SECONDS);

Next, call the IDirectInputEffect::SetParameters method to make the changes.

hr = g_lpdiEffect->SetParameters(&diEffect, DIEP_TYPESPECIFICPARAMS);

Note the DIEP_TYPESPECIFICPARAMS flag that restricts the changes to a single member of the DIEFFECT structure.

You can control the way changes are handled by using other flags. For example, by using the DIEP_NODOWNLOAD flag you could change the parameters immediately after starting the effect but delay the implementation until a specific call to the IDirectInputEffect::Download method. For more information concerning use of the various control flags, see IDirectInputEffect::SetParameters.

For additional DirectInput tutorials, see DirectInput C/C++ Tutorials.


Tutorial 5: Using Action Mapping
Microsoft DirectX 9.0 SDK Update (October 2004)

Tutorial 5: Using Action Mapping

This tutorial guides you through the setup, modification, and application of an action map. Examples are based written as though they were to be used in a space combat game.

The first step of setting up the Microsoft DirectInput system and the final step of closing it down are the same for any application and are covered in Tutorial 1: Using the Keyboard. The keyboard, a mouse, and a joystick are all used in the sample, so each of those devices needs to be set up.

This tutorial divides the required tasks into the following steps.

  • Step 1: Defining the Game Actions
  • Step 2: Defining the Action Map
  • Step 3: Mapping Actions to Devices
  • Step 4: Configuring and Applying the Action Map
  • Step 5: Displaying the Action Map
  • Step 6: User Configuration of the Action Map
  • Step 7: Retrieval of Action Mapped Data


Step 1: Defining the Game Actions
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 1: Defining the Game Actions

The first step toward creating an action map is the definition of the game actions. These actions are specific to the application and are defined by the developer. In the case of this example, the actions chosen reflect its needs as a space combat simulator. These values can be defined in many ways as the developer sees fit. They could be defined as an enumeration, as in the Preparing the Action Map overview, or they could be defined as constants as in this code fragment.

#define INPUT_LEFTRIGHT_AXIS   1L
#define INPUT_UPDOWN_AXIS      2L
#define INPUT_TURNLEFT         3L
#define INPUT_TURNRIGHT        4L
#define INPUT_FORWARDTHRUST    5L
#define INPUT_REVERSETHRUST    6L
#define INPUT_FIREWEAPONS      7L
#define INPUT_ENABLESHIELD     8L
#define INPUT_DISPLAYGAMEMENU  9L
#define INPUT_QUITGAME        10L

Once these values are defined, they can be assigned to genre-specific action-mapping constants. This is done in Step 2: Defining the Action Map.


Step 2: Defining the Action Map
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 2: Defining the Action Map

Next, each game action should be assigned to at least one virtual control or device object. These controls are defined as action-mapping constants and are defined by genre and subgenre. In this case, the best choice is the Space Combat subgenre of the flight-games genre. This subgenre makes the following constants available.

Priority 1 Controls
DIAXIS_SPACESIM_LATERAL

DIAXIS_SPACESIM_MOVE

DIAXIS_SPACESIM_THROTTLE

DIBUTTON_SPACESIM_FIRE

DIBUTTON_SPACESIM_MENU

DIBUTTON_SPACESIM_TARGET

DIBUTTON_SPACESIM_WEAPONS

Priority 2 Controls
DIAXIS_SPACESIM_CLIMB

DIAXIS_SPACESIM_ROTATE

DIBUTTON_SPACESIM_BACKWARD_LINK

DIBUTTON_SPACESIM_DEVICE

DIBUTTON_SPACESIM_DISPLAY

DIBUTTON_SPACESIM_FASTER_LINK

DIBUTTON_SPACESIM_FIRESECONDARY

DIBUTTON_SPACESIM_FORWARD_LINK

DIBUTTON_SPACESIM_GEAR

DIBUTTON_SPACESIM_GLANCE_DOWN_LINK

DIBUTTON_SPACESIM_GLANCE_LEFT_LINK

DIBUTTON_SPACESIM_GLANCE_RIGHT_LINK

DIBUTTON_SPACESIM_GLANCE_UP_LINK

DIBUTTON_SPACESIM_LEFT_LINK

DIBUTTON_SPACESIM_LOWER

DIBUTTON_SPACESIM_PAUSE

DIBUTTON_SPACESIM_RAISE

DIBUTTON_SPACESIM_RIGHT_LINK

DIBUTTON_SPACESIM_SLOWER_LINK

DIBUTTON_SPACESIM_TURN_LEFT_LINK

DIBUTTON_SPACESIM_TURN_RIGHT_LINK

DIBUTTON_SPACESIM_VIEW

DIHATSWITCH_SPACESIM_GLANCE

Priority 1 controls are those controls that, at the minimum, should be mapped to a device object if possible. Priority 2 controls are less critical to basic game operation and may be mapped as needed.

Game actions are assigned to action-mapping constant controls in an array of DIACTION structures. Each DIACTION structure contains at least one game action, its associated action-mapping constant, any necessary flags, and either a friendly name or identifier (ID) string for the action. The remaining DIACTION members are not used at this point. The following code sample shows definition of the array of DIACTION structures.

#define NUMBER_OF_ACTIONS 18

DIACTION g_rgGameAction[NUMBER_OF_ACTIONS] =
{
    // Device input pre-defined by DirectInput, according to genre
    {INPUT_LEFTRIGHT_AXIS, DIAXIS_SPACESIM_LATERAL, 0, "Turn",},
    {INPUT_UPDOWN_AXIS, DIAXIS_SPACESIM_MOVE, 0, "Move",},
    {INPUT_FIREWEAPONS, DIBUTTON_SPACESIM_FIRE, 0, "Shoot",},
    {INPUT_ENABLESHIELD, DIBUTTON_SPACESIM_GEAR, 0, "Shield",},
    {INPUT_DISPLAYGAMEMENU, DIBUTTON_SPACESIM_DISPLAY, 0, "Display",},
    {INPUT_QUITGAME, DIBUTTON_SPACESIM_MENU, 0, "Quit Game",},

    // Keyboard input mappings
    {INPUT_TURNLEFT, DIKEYBOARD_LEFT, 0, "Turn left", },
    {INPUT_TURNRIGHT, DIKEYBOARD_RIGHT, 0, "Turn right", },
    {INPUT_FORWARDTHRUST, DIKEYBOARD_UP, 0, "Forward thrust", },
    {INPUT_REVERSETHRUST, DIKEYBOARD_DOWN, 0, "Reverse thrust", },
    {INPUT_FIREWEAPONS, DIKEYBOARD_F, 0, "Fire weapons", },
    {INPUT_ENABLESHIELD, DIKEYBOARD_S, 0, "Enable shields", },
    {INPUT_DISPLAYGAMEMENU, DIKEYBOARD_D, DIA_APPFIXED,
                                      "Display game menu"), },
    {INPUT_QUITGAME, DIKEYBOARD_ESCAPE, DIA_APPFIXED, "Quit game", },

    // Mouse input mappings
    {INPUT_LEFTRIGHT_AXIS, DIMOUSE_XAXIS, 0, "Turn", },
    {INPUT_UPDOWN_AXIS, DIMOUSE_YAXIS, 0, "Move", },
    {INPUT_FIREWEAPONS, DIMOUSE_BUTTON0, 0, "Fire weapons", },
    {INPUT_ENABLESHIELD, DIMOUSE_BUTTON1, 0, "Enable shields", },
};

A DIACTIONFORMAT structure is then initialized to contain the DIACTION array g_rgGameAction defined above. The DIACTIONFORMAT structure also defines the genre, buffer size, axis scaling, and a friendly name for the action map. The g_AppGuid value is a globally unique identifier (GUID) defined in the application to identify the action map. For more information about creating GUIDs, see GUIDs.

DIACTIONFORMAT diaf;
diaf.dwSize        = sizeof(DIACTIONFORMAT);
diaf.dwActionSize  = sizeof(DIACTION);
diaf.dwDataSize    = NUMBER_OF_ACTIONS * sizeof(DWORD);
diaf.dwNumActions  = NUMBER_OF_ACTIONS;
diaf.guidActionMap = g_AppGuid;
diaf.dwGenre       = DIVIRTUAL_SPACESIM;
diaf.rgoAction     = g_rgGameAction;
diaf.dwBufferSize  = 16;
diaf.lAxisMin      = -100;
diaf.lAxisMax      = 100;
diaf.tszActionMap  = "DI Test";

This DIACTIONFORMAT structure is matched against enumerated devices to find the best match in Step 3: Mapping Actions to Devices.


Step 3: Mapping Actions to Devices
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 3: Mapping Actions to Devices

Once the desired mapping has been defined, it must be applied to physical devices. IDirectInput8::EnumDevicesBySemantics begins this process in the following code fragment, where m_pDI is a previously defined IDirectInput8 object.

HRESULT hr;

hr = m_pDI->EnumDevicesBySemantics(m_strUserName, &m_diaf,
                                EnumSuitableDevicesCB, this, 0L);

The first parameter, m_strUserName is useful in the case of multiple users who might have different mapping preferences. However, in the case of this example, this value is NULL, indicating the user currently logged onto the system.

The second parameter is the address of the DIACTIONFORMAT structure containing the mapping information.

The third parameter is the address of a callback function that is called for each device found on the system. The function used in the sample is based on the DIEnumDevicesBySemanticsCallback function.

The fourth parameter could be any 32-bit value that you want to make available to the callback function. Here, this is a this pointer to the class object used by the MultiMapper sample for the various action-mapping setup and manipulation functions. This gives the callback function access to the class' functions.

The final parameter is used for flags. None are used in this example.

The EnumSuitableDevicesCB callback function calls the application-defined function AddDevices, which in turn calls the IDirectInputDevice8::BuildActionMap function on the device pdidDevice currently being enumerated. This call is shown in the following code fragment.

hr = pdidDevice->BuildActionMap( &m_diaf, m_strUserName, 0L );

The first parameter is once again the address of the DIACTIONFORMAT structure containing the action map.

The second parameter is again the name of the user if desired, though NULL in this case.

The final parameter holds control flags, with none being passed in this case.

IDirectInputDevice8::BuildActionMap takes the list of control assignments specified in the DIACTIONFORMAT structure and attempts to map them to specific device objects on the device being enumerated. The results of the mapping are returned in the same structure. Each pass maps different controls depending on the nature of the currently enumerated device. A keyboard, for instance, maps controls that specify a mapping to a particular key, but leaves controls that specify buttons, sliders, or axes unmapped. If a joystick is enumerated next, IDirectInputDevice8::BuildActionMap ignores those controls mapped to keyboard keys, but it attempts to map the buttons, sliders, and axes to the joystick's device objects.

The results of this default mapping can be examined and manipulated. This is done in Step 4: Configuring and Applying the Action Map.


Step 4: Configuring and Applying the Action Map
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 4: Configuring and Applying the Action Map

Once the mapping has been returned in the DIACTIONFORMAT structure, it can be manipulated before being applied by IDirectInputDevice8::SetActionMap.

The dwHow member of each DIACTIONFORMAT structure might be examined at this point to determine both whether the mapping was successful and what the criteria were in selecting the device object to which that action was mapped. For instance, you can determine if the mapping was specified by the hardware manufacturer or requested by the user.

The actual mapping itself may be changed as well by editing the dwSemantic member of the appropriate DIACTIONFORMAT structure returned in the default mapping. You can choose to make those changes, but it is not recommended that you do so.

Once the action map configuration is finalized, it must be applied to the device to bind the physical controls to the game actions. This is done by calling IDirectInputDevice8::SetActionMap as follows:

    hr = pdidDevice->SetActionMap( &m_diaf, m_strUserName, 0L );

Action maps, once created, can be displayed for and easily altered by the user. This is explained in Step 5: Displaying the Action Map.


Step 5: Displaying the Action Map
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 5: Displaying the Action Map

In addition to the advantage of action mapping in enabling the developer to define game actions independently of specific controller hardware, action mapping also benefits the user by providing a user interface (UI) for easy reconfiguration.

The UI can be displayed in two forms, text-only or graphics. In addition, each of those two options can be viewed in two modes: view-only or edit.

To display the UI, some initial setup is involved. First, a DICOLORSET structure is declared and initialized. This structure, as its name implies, describes the color set used to display the UI. The following code fragment shows the setup of this structure.

DICOLORSET dics;
ZeroMemory(&dics, sizeof(DICOLORSET));
dics.dwSize = sizeof(DICOLORSET);

By using the ZeroMemory function to set the memory block to zeroes, it indicates that the default color scheme should be used. Beyond this, the only element that requires initialization is the dwSize member, which is set equal to the size of the DICOLORSET structure.

The DICOLORSET structure is then included as part of a larger DICONFIGUREDEVICESPARAMS structure as seen in this code fragment.

DICONFIGUREDEVICESPARAMS dicdp;
ZeroMemory(&dicdp, sizeof(dicdp));
dicdp.dwSize = sizeof(dicdp);
dicdp.dwcUsers       = 1;
dicdp.lptszUserNames = m_strUserName;

dicdp.dwcFormats     = 1;
dicdp.lprgFormats    = &m_diaf;
dicdp.hwnd           = m_hWnd;
dicdp.lpUnkDDSTarget = NULL;

The DICONFIGUREDEVICESPARAMS structure is declared and its allotted memory is set to contain nothing but zeroes. Once again, the dwSize member is set to the size of the structure. Only the currently logged user is being used in this example, so dwcUsers is set to 1. Recall that the m_strUserName variable is set to NULL so that the user's name is the name of the user currently logged onto the system.

Only one DIACTIONFORMAT structure containing the action map is being passed, so dwcFormats is set to 1 and the address of the DIACTIONFORMAT structure is passed as lprgFormats.

The hwnd variable is assigned the handle of the application window and the lpUnkDDSTarget is set to NULL to indicate that the Microsoft Windows Windows Graphics Device Interface (GDI) functions should be used to draw the configuration user interface image.

The initialized DICONFIGUREDEVICESPARAMS structure is then passed to IDirectInput8::ConfigureDevices as illustrated in this code fragment.

hr = m_pDI->ConfigureDevices(NULL, &dicdp, dwFlags, NULL);

The first and last parameters, which are used with an optional callback function, are set to NULL as they are not used in this sample.

The second parameter is the address of the DICONFIGUREDEVICESPARAMS structure containing the data to be displayed and other auxiliary information.

The third parameter is used for flags that determine whether the display is in read-only or edit mode. If you want to display the configuration for informational purposes without giving the user the option of changing it, you use the DICD_DEFAULT flag in this parameter. However, in this sample the dwFlags variable had been set earlier to DICD_EDIT, so the display allows user configuration. This is discussed in Step 6: User Configuration of the Action Map.


Step 6: User Configuration of the Action Map
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 6: User Configuration of the Action Map

At this point, the user configuration interface is displayed. If the device manufacturer has provided a graphic, users see an image of the device with labels indicating the action assigned to each device object. If no graphic is available, a simple text list of available device objects with their associated actions is displayed. An example of the former is shown here.

Graphical user interface for configuring the action map

Users can now reassign controllers to actions as they see fit. Any changes made will be reflected in the DIACTIONFORMAT structure. When the user interface is closed, the new action map must be sent to IDirectInputDevice8::SetActionMap before it can be implemented.

Using the data associated with the controls in an action map is described in Step 7: Retrieval of Action Mapped Data.


Step 7: Retrieval of Action Mapped Data
Microsoft DirectX 9.0 SDK Update (October 2004)

Step 7: Retrieval of Action Mapped Data

Action mapping was designed with buffered data in mind and will most often be used in that manner. The only difference between retrieving data from an action-mapped device and a device with no mapping is where you get it. Without action mapping, you would look to the dwOfs member of the DIDEVICEOBJECTDATA structure to determine which device object reported a change. However, with action mapping, you look to the uAppData member. Data is found in the dwData member.

For more detailed information about retrieving action-mapped data, see Retrieving Action Data.


DirectInput C/C++ Samples
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectInput C/C++ Samples

The following sample programs demonstrate the use and capabilities of Microsoft DirectInput.

Samples

  • ActionBasic Sample
  • ActionMapper Sample
  • CustomFormat Sample
  • DeviceView Sample
  • DIConfig Sample
  • FFConst Sample
  • Joystick Sample
  • Keyboard Sample
  • Mouse Sample
  • MultiMapper Sample
  • ReadFFE Sample
  • Scrawl Sample

Although Microsoft DirectX samples include Microsoft Visual C++ project workspace files, you might need to verify other settings in your development environment to ensure that the samples compile properly. .


ActionBasic Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

ActionBasic Sample

Description

The ActionBasic sample is intended to be an introduction to action mapping. The source code includes a step by step approach to creating an action mapped application.

Path

Source: | (SDK root)\Samples\C++\DirectInput\ActionBasic
Executable: | (SDK root)\Samples\C++\DirectInput\Bin\ActionBasic.exe

User's Guide

When you start the sample, a window will open displaying a chart that lists the detected devices plotted against the sample game actions. Actions which were not successfully mapped to an object on the device are given a crosshatch-filled cell on the chart. When you trigger a mapped keyboard device or a mapped mouse device, the corresponding cell will be highlighted. Triggered axis actions will also feature an arrow to indicate the axis position.

To view the current action mappings for all the detected devices, click the View Configuration button. This will open the default configuration user interface (UI) managed by Microsoft DirectInput. These mappings cannot be changed for this sample.

Programming Notes

The ActionBasic sample is intended to be an introduction to the action mapping features of DirectInput. The source code is commented and labeled according to the primary steps to be followed when writing an action mapped application. If you're already familiar with the fundamentals of action mapping, you may want to refer to the ActionMapper Sample, which shows how the framework supplied with this software development kit (SDK) can simplify development.


ActionMapper Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

ActionMapper Sample

Description

The ActionMapper sample program demonstrates the retrieval of action-mapped data. It also enables reconfiguration of the keyboard, mouse, and other controller action mappings through the user interface.

Path

Source: | (SDK root)\Samples\C++\DirectInput\ActionMapper
Executable: | (SDK root)\Samples\C++\DirectInput\Bin\ActionMapper.exe

User's Guide

When you run the ActionMapper sample, a window opens where you can watch the input state change as you press keys or click the mouse button. The World State tells you where you are located in the two-dimensional grid space. If you click Configure Input, a window opens where you can change the keys that control various options such as moving forward or backward or firing your weapon. Click OK to return to the World State window.

Programming Notes

The application retrieves action-mapped data in the UpdateInput function by calling the IDirectInputDevice8::GetDeviceData method.


CustomFormat Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

CustomFormat Sample

Description

The CustomFormat Sample illustrates the use of a custom data format.

Path

Source: | (SDK root)\Samples\C++\DirectInput\CustomFormat
Executable: | (SDK root)\Samples\C++\DirectInput\Bin\CustomFormat.exe

User's Guide

After you have started the sample, the sample displays the mouse location and which mouse button is clicked.

Note If your mouse has more than four buttons, not all of the buttons will be used by this sample.

Programming Notes

The comments in CustomFormat.cpp explain how to create, initialize, and retrieve data with a custom data format. You might want to use a custom data format for adding support for a non-standard input device. By enumerating the device objects, you can determine exactly what data is available. The data format you create specifies how the data you are interested in will be stored.

For compatibility, this sample creates a new format to store mouse data. Usually, you would want to use one of the provided c_dfDIMouse types, but the steps taken to create the custom format will be the same for any hardware device. For more information, see IDirectInputDevice8::SetDataFormat.


DeviceView Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

DeviceView Sample

Description

This sample shows how the DIDevImage framework provided with the samples, located in the (SDK root)\samples\C++\Common folder, can be used to create a custom device configuration interface.

DIDevImage framework handles issues such as bookkeeping involved with bitmaps, ToolTips, and image scaling. If extra functionality is needed, you can modify the source code for the DIDevImage framework at (SDK root)\samples\cpp\common\src\didevimg.cpp.

Path

Source: | (SDK root)\Samples\Multimedia\DirectInput\DeviceView
Executable: | (SDK root)\Samples\Multimedia\DirectInput\Bin\DeviceView.exe

User's Guide

When you run the application, it will display a tab for each Microsoft DirectInput device on your system. For each device, you scroll through multiple pages by entering a value for the desired page or by using the scroll arrows.

To select a device object, click the mouse on the name of the device or activate the device object. This will highlight the name of the current device object and display the object's image overlay (if available).

To hide unmapped objects, select the Hide Unmapped check box.

Programming Notes

This sample is built on the DIDevImage framework, which handles the device image loading, scaling, and rendering. To use the framework:

  1. Create an instance of the CDIDevImage class.
  2. Initialize the CIDevImage object by passing a pointer to an IDirectInputDevice8 object to the CIDevImage::Init method.
  3. Set the desired names associated with each object through a series of calls to the CIDevImage::SetCalloutText method.
  4. Render the image associated with the object to your client application by passing either a device context to the CIDevImage::RenderToDC method, or an IDirect3DTexture9 object to the CIDevImage::Render method.
  5. Highlight, display full name, or hide names associate with each object by passing the appropriate flags to the DIDevImage::SetCalloutState method.

The CIDevImage framework has some optimizations for quick renderings, but your application should not call the Render method for each frame. Instead, try to call the framework's Render method only when the device image changes due to user input.

Read the inline comments included with the CIDevImage framework source code for information about using some of the more advanced features, such as transparent backgrounds for Microsoft Direct3D surfaces.

It is not necessary to create a device configuration user interface (UI). DirectInput provides a UI that can be customized and is called by the IDirectInput8::ConfigureDevices method. The source code for the default UI is also provided with this software development kit (SDK) (samples\cpp\DirectInput\diconfig). The DirectInput UI, as well as the DIDevImage framework UI, call the IDirectInputDevice8::GetImageInfo method to retrieve the device images.


DIConfig Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

DIConfig Sample

Description

The DIConfig code demonstrates the implementation of a configuration user interface based upon the Microsoft DirectInput Mapper technology. This sample code is very complex and is intended to be used more as a reference implementation than as a learning tool.

Path

Source: | (SDK root)\Samples\C++\DirectInput\DIConfig
Executable: | None (see Programming Notes).

User's Guide

This sample does not create an executable file, so there are no end-user instructions.

Programming Notes

This code generates Diconfig.dll, a binary file that contains all of the functionality used in the default Mapper user interface (UI). This code is very complex and is intended as a reference implementation of a DirectInput-based configuration user interface.

For more information about this sample, see the comments within the sample code itself. The following major features are supported.

  • Display of device images.
  • Reconfiguration of devices.
  • Support for multiple device views to illustrate alternate viewing angles.
  • Support for control activation overlays.
  • Use of the IDirectInputDevice8::GetImageInfo method.
  • Device ownership for multiuser applications on the same computer.
  • Persistence of user settings through the IDirectInputDevice8::SetActionMap method.


FFConst Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

FFConst Sample

Description

The FFConst sample program applies raw forces to a force-feedback input device, illustrating how a simulator-type application can use force feedback to generate forces computed by a physics engine.

You must have a force-feedback device connected to your system in order to run the application.

Path

Source: | (SDK root)\Samples\C++\DirectInput\FFConst
Executable: | (SDK root)\Samples\C++\DirectInput\Bin\FFConst.exe

User's Guide

When you run the application, it displays a window with a crosshair and a black spot in it. Click anywhere within the window's client area to move the black spot. (Note that moving the device itself does not do anything.) FFConst exerts a constant force on the device from the direction of the spot, in proportion to the distance from the crosshair. You can also hold down the mouse button and move the spot continuously.

Programming Notes

This sample program enumerates the input devices and acquires the first force-feedback device that it finds. If none are detected, it displays a message and terminates.

When the user moves the black spot, the joySetForcesXY function converts the cursor coordinates to a force direction and magnitude. This data is used to modify the parameters of the constant force effect.


Joystick Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

Joystick Sample

Description

The Joystick sample program obtains and displays joystick data.

Path

Source: | (SDK root)\Samples\C++\DirectInput\Joystick
Executable: | (SDK root)\Samples\C++\DirectInput\Bin\Joystick.exe

User's Guide

Observe how the displayed data changes when you move and twist the stick, rotate the throttle wheel, and press buttons in various combinations.

Programming Notes

The application polls the joystick for immediate data in response to a timer set inside the dialog procedure.


Keyboard Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

Keyboard Sample

Description

The Keyboard sample program enables the exploration of Foreground versus Background and Exclusive versus Non-Exclusive cooperative levels, and Buffered versus Immediate data retrieval from the keyboard.

Path

Source: | (SDK root)\Samples\C++\DirectInput\Keyboard
Executable: | (SDK root)\Samples\C++\DirectInput\Bin\Keyboard.exe

User's Guide

Through the user interface, any combination of cooperative level and data styles can be created and the resulting keyboard behavior observed. Each setting is explained as it is selected, and the expected behavior is predicted when the device is created.

Programming Notes

Note that holding down a key in immediate mode holds that key indefinitely as subsequent snapshots of the keyboard are taken by Microsoft DirectInput. This is an optical illusion because DirectInput is taking individual snapshots at the rate of twelve times a second, but it demonstrates that, in immediate mode, only the state of the keyboard at that time is considered, while anything that has happened between snapshots is ignored.

Holding down a key in buffered mode briefly displays the data indicating that the key has been pressed, then quickly clears that data as it is flushed from the buffer. Releasing the key generates another briefly displayed key-up event. This is a significant difference from immediate mode.


Mouse Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

Mouse Sample

Description

The Mouse sample program enables the exploration of Foreground versus Background and Exclusive versus Non-Exclusive cooperative levels, and Buffered versus Immediate data retrieval from the mouse.

Path

Source: | (SDK root)\Samples\C++\DirectInput\Mouse
Executable: | (SDK root)\Samples\C++\DirectInput\Bin\Mouse.exe

User's Guide

Through the user interface, any combination of cooperative level and data styles can be created and the resulting keyboard behavior observed. Each setting is explained as it is selected, and the expected behavior is predicted when the device is created.

To release the mouse, press ENTER.

Programming Notes

Note that in immediate mode, all device objects are visible and you can see the data change as the mouse is moved. This is an optical illusion because Microsoft DirectInput is taking individual snapshots at the rate of twelve times a second, but it demonstrates that, in immediate mode, only the state of the device at that time is considered, while anything that has happened between device snapshots is ignored.

Holding down a button in buffered mode briefly displays the data indicating that the button has been pressed, then quickly clears that data as it is flushed from the buffer. Releasing the button generates another briefly displayed button up event. This is a significant difference from immediate mode.


MultiMapper Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

MultiMapper Sample

Description

The MultiMapper sample program shows how to set up, apply, and retrieve data using the Action Mapping functionality. It also demonstrates remapping through the user interface.

Path

Source: | (SDK root)\Samples\C++\DirectInput\MultiMapper
Executable: | (SDK root)\Samples\C++\DirectInput\Bin\MultiMapper.exe

User's Guide

First, assign a number of players. The MultiMapper sample program accepts up to four. There must be one device, including the keyboard and the mouse, for each player. If more players are chosen than there are devices available, the program automatically scales back to the maximum number of players based on the devices attached.

The MultiMapper sample program is designed as though it were a space combat application. Each player is assigned a basic set of actions such as turning, firing, and activating thrusters. These actions are then mapped to device controls. Activation of those controls is then reflected by data in the display window.

To activate the action mapping user interface, press D. Each device has a separate tab for mapping that particular device. Double-clicking a device object label activates the list of possible actions to be assigned to that device object. Make a selection from the action list to map that action to the selected device object. You can also reassign devices among players.

Programming Notes

If a controller such as a joystick or a wheel is attached to the system, it displays a graphic of the device with actions as callouts to each device object. The display of this graphic depends on the presence of a provided bitmap for that device.


ReadFFE Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

ReadFFE Sample

Description

The ReadFFE sample program enumerates and plays all of the Microsoft DirectInput force-feedback effects stored in a DirectInput effects file created by the Force Editor.

Path

Source: | (SDK root)\Samples\C++\DirectInput\ReadFFE
Executable: | (SDK root)\Samples\C++\DirectInput\Bin\ReadFFE.exe
Media: | (SDK root)\Samples\C++\DirectInput\ReadFFE\*.ffe

User's Guide

Click Read File and open an existing Force Feedback Effects (FFE) file. If it was successfully read, click Play Effects to play the effects on the force-feedback device. FFE files can be authored using the Force Feedback Editor utility packaged with the Microsoft DirectX software development kit (SDK).

Programming Notes

For each file effect enumerated, the EnumAndCreateEffectsCallback function initializes an IDirectInputEffect pointer and adds it to a linked list. The OnPlayEffects function traverses this list and plays all effects.


Scrawl Sample
Microsoft DirectX 9.0 SDK Update (October 2004)

Scrawl Sample

Description

The Scrawl application demonstrates using the mouse in exclusive mode in a windowed application. It functions in the same way as a pencil tool in a paint program.

Path

Source: | (SDK root)\Samples\C++\DirectInput\Scrawl
Executable: | (SDK root)\Samples\C++\DirectInput\Bin\Scrawl.exe

User's Guide

To draw, hold down the left mouse button and move the mouse. Click the right mouse button to invoke a shortcut menu. From the shortcut menu you can clear the client window, set the mouse sensitivity, or close the application. If the mouse buttons have been switched through Control Panel settings, Scrawl will detect and mimic this behavior. Note that Microsoft DirectInput ignores Control Panel settings and the application itself must make the switch.

Programming Notes

The Scrawl sample program demonstrates many aspects of DirectInput programming, including the following:

  • Using the mouse in non-exclusive mode in a windowed application.
  • Releasing the mouse when Microsoft Windows needs to use it for menu access.
  • Reacquiring the mouse when Windows no longer needs it.
  • Reading buffered device data.
  • Deferring screen updates until movement on both axes has been fully processed.
  • Displaying event notifications of device activity.
  • Restricting the cursor to an arbitrary region.
  • Scaling raw mouse coordinates before using them.
  • Using relative axis mode.


DirectInput C/C++ Reference
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectInput C/C++ Reference

Reference material for the Microsoft DirectInput C/C++ application programming interface (API) is divided into the following categories.

  • Interfaces
  • Callback Functions
  • Functions
  • Macros
  • Structures
  • Device Constants
  • Action Mapping Constants
  • Return Values


Interfaces
Microsoft DirectX 9.0 SDK Update (October 2004)

Interfaces

This section contains references for methods of the following Microsoft DirectInput interfaces.

Interfaces

  • IDirectInput8
  • IDirectInputDevice8
  • IDirectInputEffect

Note All DirectInput methods have corresponding macros that expand to C or C++ syntax depending on which language is defined. These macros are found in the Dinput.h header file and are not documented separately.


IDirectInput8 Interface

Applications use the methods of the IDirectInput8 interface to enumerate, create, and retrieve the status of Microsoft DirectInput devices, initialize the DirectInput object, and invoke an instance of the Microsoft Windows Control Panel.

IDirectInput8 Members

ConfigureDevices

Displays property pages for connected input devices and enables the user to map actions to device controls.

CreateDevice

Creates and initializes an instance of a device based on a given globally unique identifier (GUID), and obtains an IDirectInputDevice8 interface.

EnumDevices

Enumerates available devices.

EnumDevicesBySemantics

Enumerates devices that most closely match the application-specified action map.

FindDevice

Retrieves the instance GUID of a device that has been newly attached to the system. It is called in response to a Microsoft Win32 device management notification.

GetDeviceStatus

Retrieves the status of a specified device.

Initialize

Initializes a DirectInput object. Applications normally do not need to call this method. The DirectInput8Create function automatically initializes the DirectInput object after creating it.

RunControlPanel

Runs Control Panel to enable the user to install a new input device or modify configurations.

Remarks

IDirectInput8 supersedes the IDirectInput, IDirectInput2, and IDirectInput7 interfaces used in earlier versions of Microsoft DirectX.

IDirectInput8 is an interface to a new class of object, represented by the class identifier CLSID_DirectInput8, and cannot be obtained by calling QueryInterface on an interface to objects of class CLSID_DirectInput. Instead, obtain the IDirectInput8 interface by using the DirectInput8Create function.

The LPDIRECTINPUT8 type is defined as a pointer to the IDirectInput8 interface:

typedef struct IDirectInput8    *LPDIRECTINPUT8;

Interface Information

Stock Implementation | dinput.dll
Custom Implementation | No
Inherits from | IUnknown
Header | dinput.h
Minimum operating systems | Windows 98


IDirectInput8::ConfigureDevices Method

Displays property pages for connected input devices and enables the user to map actions to device controls.

Syntax

HRESULT ConfigureDevices(

    LPDICONFIGUREDEVICESCALLBACK lpdiCallback,
    LPDICONFIGUREDEVICESPARAMS lpdiCDParams,
    DWORD dwFlags,
    LPVOID pvRefData
);

Parameters

lpdiCallback
Address of a callback function to be called each time the contents of the surface change. See DIConfigureDevicesCallback. Pass NULL if the application does not handle the display of the property sheet. In this case, Microsoft DirectInput displays the property sheet and returns control to the application when the user closes the property sheet. If you supply a callback pointer, you must also supply a valid surface pointer in the lpUnkDDSTarget member of the DICONFIGUREDEVICESPARAMS structure.
lpdiCDParams
Address of a DICONFIGUREDEVICESPARAMS structure that contains information about users and genres for the game, as well as information about how the user interface is displayed.
dwFlags
DWORD value that specifies the mode in which the control panel should be invoked. The dwFlags parameter must be one of the following values.
DICD_DEFAULT
Open the property sheet in view-only mode.
DICD_EDIT
Open the property sheet in edit mode. This mode enables the user to change action-to-control mappings. After the call returns, the application should assume current devices are no longer valid, release all device interfaces, and reinitialize them by calling IDirectInput8::EnumDevicesBySemantics.
pvRefData
Application-defined value to pass to the callback function.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_OUTOFMEMORY | The DirectInput subsystem couldn't allocate sufficient memory to complete the call. This value is equal to the E_OUTOFMEMORY standard COM return value.

Remarks

IDirectInput8::ConfigureDevices was designed to work in the Microsoft Direct3D 8.x environment. Developers should use the DIConfig Sample to produce the same results in the Direct3D 9.0 environment.

Hardware vendors provide bitmaps and other display information for their device.

Before calling the method, an application can modify the text labels associated with each action by changing the value in the lptszActionName member of the DIACTION structure.

Configuration is stored for each user of each device for each game. The information can be retrieved by the IDirectInputDevice8::BuildActionMap method.

By default, acceleration is supported for these pixel formats:

  • A1R5G5B5

    16-bit pixel format with 5 bits reserved for each color and 1 bit reserved for alpha (transparent texel).

  • A8R8G8B8

    32-bit ARGB pixel format with alpha.

  • R9G8B8

    24-bit RGB pixel format.

  • X1R5G5B5

    16-bit pixel format with 5 bits reserved for each color.

  • X8R8G8B8

    32-bit RGB pixel format with 8 bits reserved for each color.

Other formats will result in color conversion and dramatically slow the frame rate.

Note Even if the cooperative level for the application is disabling the Microsoft Windows logo key passively through an exclusive cooperative level or actively through use of the DISCL_NOWINKEY flag, that key will be active while the default action mapping user interface (UI) is displayed.


IDirectInput8::CreateDevice Method

Creates and initializes an instance of a device based on a given globally unique identifier (GUID), and obtains an IDirectInputDevice8 interface.

Syntax

HRESULT CreateDevice(

    REFGUID rguid,
    LPDIRECTINPUTDEVICE *lplpDirectInputDevice,
    LPUNKNOWN pUnkOuter
);

Parameters

rguid
Reference to (C++) or address of (C) the instance GUID for the desired input device (see Remarks). The GUID is retrieved through the IDirectInput8::EnumDevices method, or it can be one of the predefined GUIDs listed below. For the following GUID values to be valid, your application must define INITGUID before all other preprocessor directives at the beginning of the source file, or link to Dxguid.lib.
GUID_SysKeyboard
The default system keyboard.
GUID_SysMouse
The default system mouse.
lplpDirectInputDevice
Address of a variable to receive the IDirectInputDevice8 interface pointer if successful.
pUnkOuter
Address of the controlling object's IUnknown interface for Component Object Model (COM) aggregation, or NULL if the interface is not aggregated. Most calling applications pass NULL.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following:

DIERR_DEVICENOTREG | The device or device instance is not registered with Microsoft DirectInput. This value is equal to the REGDB_E_CLASSNOTREG standard COM return value.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard COM return value.
DIERR_NOINTERFACE | The specified interface is not supported by the object. This value is equal to the E_NOINTERFACE standard COM return value.
DIERR_NOTINITIALIZED | The object has not been initialized.
DIERR_OUTOFMEMORY | The DirectInput subsystem couldn't allocate sufficient memory to complete the call. This value is equal to the E_OUTOFMEMORY standard COM return value.

Remarks

Calling this method with pUnkOuter = NULL is equivalent to creating the object by CoCreateInstance (&CLSID_DirectInputDevice, NULL, CLSCTX_INPROC_SERVER, riid, lplpDirectInputDevice) and then initializing it with Initialize.

Calling this method with pUnkOuter != NULL is equivalent to creating the object by CoCreateInstance (&CLSID_DirectInputDevice, punkOuter, CLSCTX_INPROC_SERVER, &IID_IUnknown, lplpDirectInputDevice). The aggregated object must be initialized manually.


IDirectInput8::EnumDevices Method

Enumerates available devices.

Syntax

HRESULT EnumDevices(

    DWORD dwDevType,
    LPDIENUMDEVICESCALLBACK lpCallback,
    LPVOID pvRef,
    DWORD dwFlags
);

Parameters

dwDevType
Device type filter.

To restrict the enumeration to a particular type of device, set this parameter to a DI8DEVTYPE_* value. See DIDEVICEINSTANCE.

To enumerate a class of devices, use one of the following values.

DI8DEVCLASS_ALL
All devices.
DI8DEVCLASS_DEVICE
All devices that do not fall into another class.
DI8DEVCLASS_GAMECTRL
All game controllers.
DI8DEVCLASS_KEYBOARD
All keyboards. Equivalent to DI8DEVTYPE_KEYBOARD.
DI8DEVCLASS_POINTER
All devices of type DI8DEVTYPE_MOUSE and DI8DEVTYPE_SCREENPOINTER.
lpCallback
Address of a callback function to be called once for each device enumerated. See DIEnumDevicesCallback.
pvRef
Application-defined 32-bit value to be passed to the enumeration callback each time it is called.
dwFlags
Flag value that specifies the scope of the enumeration. This parameter can be one or more of the following values:
DIEDFL_ALLDEVICES
All installed devices are enumerated. This is the default behavior.
DIEDFL_ATTACHEDONLY
Only attached and installed devices.
DIEDFL_FORCEFEEDBACK
Only devices that support force feedback.
DIEDFL_INCLUDEALIASES
Include devices that are aliases for other devices.
DIEDFL_INCLUDEHIDDEN
Include hidden devices. For more information about hidden devices, see DIDEVCAPS.
DIEDFL_INCLUDEPHANTOMS
Include phantom (placeholder) devices.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values.

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

All installed devices can be enumerated, even if they are not present. For example, a flight stick might be installed on the system but not currently plugged into the computer. Set the dwFlags parameter to indicate whether only attached or all installed devices should be enumerated. If the DIEDFL_ATTACHEDONLY flag is not present, all installed devices are enumerated.

A preferred device type can be passed as a dwDevType filter so that only the devices of that type are enumerated.

On Microsoft Windows XP, Microsoft DirectInput enumerates only one mouse and one keyboard device, referred to as the system mouse and the system keyboard. These devices represent the combined output of all mice and keyboards respectively on a system. For information about how to read from multiple mice or keyboards individually on Windows XP, see the WM_INPUT documentation.

Note The order in which devices are enumerated by DirectInput is not guaranteed.

See Also

IDirectInput8::EnumDevicesBySemantics


IDirectInput8::EnumDevicesBySemantics Method

Enumerates devices that most closely match the application-specified action map.

Syntax

HRESULT EnumDevicesBySemantics(

    LPCTSTR ptszUserName,
    LPDIACTIONFORMAT lpdiActionFormat,
    LPDIENUMDEVICESBYSEMANTICSCB lpCallback,
    LPVOID pvRef,
    DWORD dwFlags
);

Parameters

ptszUserName
String identifying the current user, or NULL to specify the user logged onto the system. The user name is taken into account when enumerating devices. A device with user mappings is preferred to a device without any user mappings. By default, devices in use by other users are not enumerated for this user.
lpdiActionFormat
Address of a DIACTIONFORMAT structure that specifies the action map for which suitable devices are enumerated.
lpCallback
Address of a callback function to be called once for each device enumerated. See DIEnumDevicesBySemanticsCallback.
pvRef
Application-defined 32-bit value to pass to the enumeration callback each time it is called.
dwFlags
Flag value that specifies the scope of the enumeration. This parameter can be one or more of the following values.
DIEDBSFL_ATTACHEDONLY
Only attached and installed devices are enumerated.
DIEDBSFL_AVAILABLEDEVICES
Only unowned, installed devices are enumerated.
DIEDBSFL_FORCEFEEDBACK
Only devices that support force feedback are enumerated.
DIEDBSFL_MULTIMICEKEYBOARDS
Only secondary (non-system) keyboard and mouse devices.
DIEDBSFL_NONGAMINGDEVICES
Only HID-compliant devices whose primary purpose is not as a gaming device. Devices such as USB speakers and multimedia buttons on some keyboards would fall within this value.
DIEDBSFL_THISUSER
All installed devices for the user identified by ptszUserName, and all unowned devices, are enumerated.
DIEDBSFL_VALID
DIEDBSFL_VALID is also defined in Dinput.h, but is not used by applications.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values.

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

The keyboard and mouse are enumerated last.

Note The order in which devices are enumerated by Microsoft DirectInput is not guaranteed.

See Also

IDirectInput8::EnumDevices, Action Mapping


IDirectInput8::FindDevice Method

Retrieves the instance globally unique identifier (GUID) of a device that has been newly attached to the system. It is called in response to a Microsoft Win32 device management notification.

Syntax

HRESULT FindDevice(

    REFGUID rguidClass,
    LPCTSTR ptszName,
    LPGUID pguidInstance
);

Parameters

rguidClass
Unique identifier of the device class for the device that the application is to locate. The application obtains the class GUID from the device arrival notification. For more information, see the documentation on the DBT_DEVICEARRIVAL event in the Microsoft Platform Software Development Kit (SDK).
ptszName
Name of the device. The application obtains the name from the device arrival notification.
pguidInstance
Address of a variable to receive the instance GUID for the device, if the device is found. This value can be passed to IDirectInput8::CreateDevice.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be DIERR_DEVICENOTREG. Failure results if the GUID and name do not correspond to a device class that is registered with Microsoft DirectInput. For example, they might refer to a storage device, rather than an input device.


IDirectInput8::GetDeviceStatus Method

Retrieves the status of a specified device.

Syntax

HRESULT GetDeviceStatus(

    REFGUID rguidInstance
);

Parameters

rguidInstance
Reference to (C++) or address of (C) the globally unique identifier (GUID) identifying the instance of the device whose status is being checked.

Return Value

If the method succeeds, the return value is DI_OK if the device is attached to the system, or DI_NOTATTACHED otherwise.

If the method fails, the return value can be one of the following error values:

DIERR_GENERIC | An undetermined error occurred inside the Microsoft DirectInput subsystem. This value is equal to the E_FAIL standard Component Object Model (COM) return value.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard COM return value.
DIERR_NOTINITIALIZED | The object has not been initialized.


IDirectInput8::Initialize Method

Initializes a Microsoft DirectInput object. Applications normally do not need to call this method. The DirectInput8Create function automatically initializes the DirectInput object after creating it.

Syntax

HRESULT Initialize(

    HINSTANCE hinst,
    DWORD dwVersion
);

Parameters

hinst
Instance handle to the application or dynamic-link library (DLL) that is creating the DirectInput object. DirectInput uses this value to determine whether the application or DLL has been certified and to establish any special behaviors that might be necessary for backward compatibility.

It is an error for a DLL to pass the handle of the parent application. For example, a Microsoft ActiveX control embedded in a Web page that uses DirectInput must pass its own instance handle, and not the handle of the browser. This ensures that DirectInput recognizes the control and can enable any special behaviors that might be necessary.
dwVersion
Version number of DirectInput for which the application is designed. This value is normally DIRECTINPUT_VERSION. Passing the version number of a previous version causes DirectInput to emulate that version.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_BETADIRECTINPUTVERSION | The application was written for an unsupported prerelease version of DirectInput.
DIERR_OLDDIRECTINPUTVERSION | The application requires a newer version of DirectInput.


IDirectInput8::RunControlPanel Method

Runs Control Panel to enable the user to install a new input device or modify configurations.

Syntax

HRESULT RunControlPanel(

    HWND hwndOwner,
    DWORD dwFlags
);

Parameters

hwndOwner
Handle of the window to be used as the parent window for the subsequent user interface. If this parameter is NULL, no parent window is used.
dwFlags
Currently not used and must be set to 0.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.

See Also

IDirectInputDevice8::RunControlPanel


IDirectInputDevice8 Interface

Applications use the methods of the IDirectInputDevice8 interface to gain and release access to Microsoft DirectInput devices, manage device properties and information, set behavior, perform initialization, create and play force-feedback effects, and invoke a device's control panel.

IDirectInputDevice8 Members

Acquire

Obtains access to the input device.

BuildActionMap

Builds an action map for the device and retrieves information about it.

CreateEffect

Creates and initializes an instance of an effect identified by the effect globally unique identifier (GUID).

EnumCreatedEffectObjects

Enumerates all the currently created effects for this device. Effects created by IDirectInputDevice8::CreateEffect are enumerated.

EnumEffects

Enumerates all the effects supported by the force-feedback system on the device. The enumerated GUIDs can represent predefined effects, as well as effects peculiar to the device manufacturer.

EnumEffectsInFile

Enumerates all the effects in a file created by the Force Editor utility or another application using the same file format.

EnumObjects

Enumerates the input and output objects available on a device.

Escape

Sends a hardware-specific command to the force-feedback driver.

GetCapabilities

Obtains the capabilities of the DirectInputDevice object.

GetDeviceData

Retrieves buffered data from the device.

GetDeviceInfo

Obtains information about the device's identity.

GetDeviceState

Retrieves immediate data from the device.

GetEffectInfo

Obtains information about an effect.

GetForceFeedbackState

Retrieves the state of the device's force-feedback system.

GetImageInfo

Retrieves information about a device image for use in a configuration property sheet.

GetObjectInfo

Retrieves information about a device object, such as a button or axis.

GetProperty

Retrieves information about the input device.

Initialize

Initializes a DirectInputDevice object. The IDirectInput8::CreateDevice method automatically initializes a device after creating it; applications normally do not need to call this method.

Poll

Retrieves data from polled objects on a DirectInput device. If the device does not require polling, calling this method has no effect. If a device that requires polling is not polled periodically, no new data is received from the device. Calling this method causes DirectInput to update the device state, generate input events (if buffered data is enabled), and set notification events (if notification is enabled).

RunControlPanel

Runs the DirectInput control panel associated with this device. If the device does not have a control panel associated with it, the default device control panel is launched.

SendDeviceData Sends data to a device that accepts output.
Note There are no devices that accept output from IDirectInputDevice8::SendDeviceData. See Remarks.
SendForceFeedbackCommand

Sends a command to the device's force-feedback system.

SetActionMap Sets the data format for a device and maps application-defined actions to device objects. It also sets the buffer size for buffered data.
SetCooperativeLevel

Establishes the cooperative level for this instance of the device. The cooperative level determines how this instance of the device interacts with other instances of the device and the rest of the system.

SetDataFormat

Sets the data format for the DirectInput device.

SetEventNotification

Specifies an event that is to be set when the device state changes. It is also used to turn off event notification.

SetProperty

Sets properties that define the device behavior. These properties include input buffer size and axis mode.

Unacquire

Releases access to the device.

WriteEffectToFile

Saves information about one or more force-feedback effects to a file that can be read by using IDirectInputDevice8::EnumEffectsInFile. This method is chiefly of interest to those wanting to write their own force-authoring applications.

Remarks

The IDirectInputDevice8 interface is obtained by using the IDirectInput8::CreateDevice method. For an example, see Creating a DirectInput Device.

IDirectInputDevice8 supersedes the IDirectInputDevice, IDirectInputDevice2, and IDirectInputDevice7 interfaces used in previous versions of Microsoft DirectX, but does not inherit from them. Methods that share names with those from older interfaces perform similar services, but may not have exactly the same functionality or behavior. You cannot obtain the earlier interfaces by using QueryInterface.

The LPDIRECTINPUTDEVICE8 type is defined as a pointer to the IDirectInputDevice8 interface:

typedef struct IDirectInputDevice8    *LPDIRECTINPUTDEVICE8;

Interface Information

Stock Implementation | dinput.dll
Custom Implementation | No
Inherits from | IUnknown
Header | dinput.h
Minimum operating systems | Windows 98

See Also

IDirectInput8


IDirectInputDevice8::Acquire Method

Obtains access to the input device.

Syntax

HRESULT Acquire(VOID);

Return Value

If the method succeeds, the return value is DI_OK, or S_FALSE if the device was already acquired.

If the method fails, the return value can be one of the following error values.

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.
DIERR_OTHERAPPHASPRIO | Another application has a higher priority level, preventing this call from succeeding. This value is equal to the E_ACCESSDENIED standard COM return value. This error can be returned when an application has only foreground access to a device but is attempting to acquire the device while in the background.

Remarks

Before a device can be acquired, a data format must be set by using the IDirectInputDevice8::SetDataFormat method or IDirectInputDevice8::SetActionMap method. If the data format has not been set, IDirectInputDevice8::Acquire returns DIERR_INVALIDPARAM.

Devices must be acquired before calling the IDirectInputDevice8::GetDeviceState or IDirectInputDevice8::GetDeviceData methods for that device.

Device acquisition does not use a reference count. Therefore, if an application calls the IDirectInputDevice8::Acquire method twice, then calls the IDirectInputDevice8::Unacquire method once, the device is unacquired.

If IDirectInputDevice8::BuildActionMap succeeds but no actions have been mapped, a subsequent call to IDirectInputDevice8::SetActionMap will return DI_OK but a call to IDirectInputDevice8::Acquire will fail with DIERR_INVALIDPARAM.


IDirectInputDevice8::BuildActionMap Method

Builds an action map for the device and retrieves information about it.

Syntax

HRESULT BuildActionMap(

    LPDIACTIONFORMAT lpdiaf,
    LPCTSTR lpszUserName,
    DWORD dwFlags
);

Parameters

lpdiaf
Address of a DIACTIONFORMAT structure that receives information about the action map.
lpszUserName
Pointer to a string that specifies the name of the user for whom mapping is requested. When using ANSI compiler settings, pass NULL and Microsoft DirectInput will assume the current user name. When using Unicode compiler settings, do not pass NULL because the mappings will not be saved.
dwFlags
Flags to control the mapping. This can be one of the following values.
DIDBAM_DEFAULT
Overwrite all mappings except application-specified mappings; that is, mappings that have the DIA_APPMAPPED flag in the DIACTION structure.
DIDBAM_HWDEFAULTS
Overwrite all mappings, including application-specified mappings. This flag is similar to DIDBAM_INITIALIZE, but automatically overrides user-mapped actions with the defaults specified by the device driver or DirectInput.
DIDBAM_INITIALIZE
Overwrite all mappings, including application-specified mappings.
DIDBAM_PRESERVE
Preserve current mappings assigned for this device or any other configured device.

Return Value

If the method succeeds, the return value is DI_OK, DI_NOEFFECT, or DI_WRITEPROTECT. See Remarks.

If the method fails, the return value can be one of the following error values.

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_MAPFILEFAIL | An error has occurred reading either the vendor-supplied action-mapping file for the device or reading or writing the user configuration file for the device.

Remarks

The method returns DI_NOEFFECT if no mappings were created for the device. For example, a keyboard or mouse will not provide mappings for genre-specific actions.

If DIERR_INVALIDPARAM is returned, one or more of the mappings was not valid. The dwHow member of the DIACTION structure is set to DIAH_ERROR. The application can iterate through the action map to find and correct errors.

If DIEFF_MAPFILEFAIL is returned, an error has occurred either reading the vendor supplied file for the device or reading or writing the user configuration file for the device.

DI_WRITEPROTECT is returned if the mappings were not configurable. For example, the buttons on a voice controller cannot be reconfigured because each button causes a specific hardware action to occur. DI_WRITEPROTECT overrides other success codes, so a check of the return codes will not reveal if any actions have been mapped.

If IDirectInputDevice8::BuildActionMap succeeds but no actions have been mapped, a subsequent call to IDirectInputDevice8::SetActionMap will return DI_OK but a call to IDirectInputDevice8::Acquire will fail with DIERR_INVALIDPARAM.

See Also

IDirectInputDevice8::SetActionMap, IDirectInputDevice8::SetDataFormat


IDirectInputDevice8::CreateEffect Method

Creates and initializes an instance of an effect identified by the effect globally unique identifier (GUID).

Syntax

HRESULT CreateEffect(

    REFGUID rguid,
    LPCDIEFFECT lpeff,
    LPDIRECTINPUTEFFECT *ppdeff,
    LPUNKNOWN punkOuter
);

Parameters

rguid
Reference to (C++) or address of (C) the GUID identifying the effect to be created. This can be a predefined effect GUID, or it can be a GUID obtained from IDirectInputDevice8::EnumEffects. The following standard effect GUIDs are defined:
  • GUID_ConstantForce
  • GUID_RampForce
  • GUID_Square
  • GUID_Sine
  • GUID_Triangle
  • GUID_SawtoothUp
  • GUID_SawtoothDown
  • GUID_Spring
  • GUID_Damper
  • GUID_Inertia
  • GUID_Friction
  • GUID_CustomForce
lpeff
DIEFFECT structure that provides parameters for the created effect. This parameter is optional. If it is NULL, the effect object is created without parameters. The application must then call the IDirectInputEffect::SetParameters method to set the parameters of the effect before it can download the effect.
ppdeff
Address of a variable to receive a pointer to the IDirectInputEffect interface if successful.
punkOuter
Controlling unknown for Component Object Model (COM) aggregation. The value is NULL if the interface is not aggregated. Most calling applications pass NULL.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_DEVICEFULL | The device is full.
DIERR_DEVICENOTREG | The device or device instance is not registered with Microsoft DirectInput. This value is equal to the REGDB_E_CLASSNOTREG standard COM return value.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard COM return value.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

If the return value is S_OK, the effect was created, and the parameters of the effect were updated, but the effect was not necessarily downloaded. For it to be downloaded, the device must be acquired in exclusive mode.


IDirectInputDevice8::EnumCreatedEffectObjects Method

Enumerates all the currently created effects for this device. Effects created by IDirectInputDevice8::CreateEffect are enumerated.

Syntax

HRESULT EnumCreatedEffectObjects(

    LPDIENUMCREATEDEFFECTOBJECTSCALLBACK lpCallback,
    LPVOID pvRef,
    DWORD fl
);

Parameters

lpCallback
Address of an application-defined callback function. Microsoft DirectInput provides the prototype function DIEnumCreatedEffectObjectsCallback.
pvRef
Reference data (context) for callback.
fl
No flags are currently defined. This parameter must be 0.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

The results are unpredictable if you create or destroy an effect while an enumeration is in progress. However, the callback function can safely release the effect passed to it.


IDirectInputDevice8::EnumEffects Method

Enumerates all the effects supported by the force-feedback system on the device. The enumerated globally unique identifiers (GUIDs) can represent predefined effects, as well as effects peculiar to the device manufacturer.

Syntax

HRESULT EnumEffects(

    LPDIENUMEFFECTSCALLBACK lpCallback,
    LPVOID pvRef,
    DWORD dwEffType
);

Parameters

lpCallback
Address of an application-defined callback function. The declaration of this function must conform to that of the DIEnumEffectsCallback prototype.
pvRef
A 32-bit application-defined value to be passed to the callback function. This parameter can be any 32-bit type; it is declared as LPVOID for convenience.
dwEffType
Effect type filter. Use one of the DIEFT_* values to indicate the effect type to be enumerated, or DIEFT_ALL to enumerate all effect types. For a list of these values, see DIEFFECTINFO.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

If the callback stops the enumeration prematurely, the enumeration is considered to have succeeded.

An application can use the dwEffType member of the DIEFFECTINFO structure to obtain general information about the effect, such as its type and which envelope and condition parameters are supported by the effect.

To exploit an effect to its fullest, contact the device manufacturer to obtain information about the semantics of the effect and its effect-specific parameters.


IDirectInputDevice8::EnumEffectsInFile Method

Enumerates all the effects in a file created by the Force Editor utility or another application using the same file format.

Syntax

HRESULT EnumEffectsInFile(

    LPCSTR lpszFileName,
    LPENUMEFFECTSINFILECALLBACK pec,
    LPVOID pvRef,
    DWORD dwFlags
);

Parameters

lpszFileName
Name of the RIFF file.
pec
Address of an application-defined callback function. The declaration of this function must conform to that of the DIEnumEffectsInFileCallback prototype.
pvRef
Application-defined value to be passed to the callback function. This parameter can be any 32-bit type.
dwFlags
Can be DIFEF_DEFAULT ( = 0) or one or both of the following values:
DIFEF_INCLUDENONSTANDARD
Include effect types that are not defined by Microsoft DirectInput.
DIFEF_MODIFYIFNEEDED
Instruct DirectInput to modify the authored effect, if necessary, so that it plays on the current device. For example, by default, an effect authored for two axes does not play on a single-axis device. Setting this flag allows the effect to play on a single axis. The parameters are modified in the DIEFFECT structure pointed to by the lpDiEffect member of the DIFILEEFFECT structure passed to the callback.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

If the callback stops the enumeration prematurely, the enumeration is considered to have succeeded.

See Also

IDirectInputDevice8::WriteEffectToFile, Loading Effects from a File


IDirectInputDevice8::EnumObjects Method

Enumerates the input and output objects available on a device.

Syntax

HRESULT EnumObjects(

    LPDIENUMDEVICEOBJECTSCALLBACK lpCallback,
    LPVOID pvRef,
    DWORD dwFlags
);

Parameters

lpCallback
Address of a callback function that receives DirectInputDevice objects. Microsoft DirectInput provides a prototype of this function as DIEnumDeviceObjectsCallback.
pvRef
Reference data (context) for callback.
dwFlags
Flags that specify the types of object to be enumerated. Each of the following values restricts the enumeration to objects of the described type:
DIDFT_ABSAXIS
An absolute axis.
DIDFT_ALIAS
Controls identified by a Human Interface Device (HID) usage alias. This flag applies only to HID-compliant USB devices.
DIDFT_ALL
All objects.
DIDFT_AXIS
An axis, either absolute or relative.
DIDFT_BUTTON
A push button or a toggle button.
DIDFT_COLLECTION
A HID link collection. HID link collections do not generate data of their own.
DIDFT_ENUMCOLLECTION(n)
An object that belongs to HID link collection number n.
DIDFT_FFACTUATOR
An object that contains a force-feedback actuator. In other words, forces can be applied to this object.
DIDFT_FFEFFECTTRIGGER
An object that can be used to trigger force-feedback effects.
DIDFT_NOCOLLECTION
An object that does not belong to any HID link collection; in other words, an object for which the wCollectionNumber member of the DIDEVICEOBJECTINSTANCE structure is 0.
DIDFT_NODATA
An object that does not generate data.
DIDFT_OUTPUT
An object that supports output. For details, see Remarks in IDirectInputDevice8::SendDeviceData.
DIDFT_POV
A point-of-view controller.
DIDFT_PSHBUTTON
A push button. A push button is reported as down when the user presses it, and as up when the user releases it.
DIDFT_RELAXIS
A relative axis.
DIDFT_TGLBUTTON
A toggle button. A toggle button is reported as down when the user presses it and remains so until the user presses the button a second time.
DIDFT_VENDORDEFINED
An object of a type defined by the manufacturer.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values.

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

The DIDFT_FFACTUATOR and DIDFT_FFEFFECTTRIGGER flags in the dwFlags parameter restrict enumeration to objects that meet all the criteria defined by the included flags. For all the other flags, an object is enumerated if it meets the criterion defined by any included flag in this category. For example, (DIDFT_FFACTUATOR | DIDFT_FFEFFECTTRIGGER) restricts enumeration to force-feedback trigger objects, and (DIDFT_FFEFFECTTRIGGER | DIDFT_TGLBUTTON | DIDFT_PSHBUTTON) restricts enumeration to buttons of any kind that can be used as effect triggers.

Applications should not rely on this method to determine whether certain keyboard keys or indicator lights are present, as these objects might be enumerated even though they are not present. Although the basic set of available objects can be determined from the device subtype, there is no reliable way of determining whether extra objects such as the menu key are available.


IDirectInputDevice8::Escape Method

Sends a hardware-specific command to the force-feedback driver.

Syntax

HRESULT Escape(

    LPDIEFFESCAPE pesc
);

Parameters

pesc
DIEFFESCAPE structure that describes the command to be sent. On success, the cbOutBuffer member contains the number of bytes of the output buffer actually used.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_DEVICEFULL | The device is full.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

Other device-specific error codes are also possible. Ask the hardware manufacturer for details.

Because each driver implements different escapes, it is the application's responsibility to ensure that it is sending the escape to the correct driver by comparing the value of the guidFFDriver member of the DIDEVICEINSTANCE structure against the value the application is expecting.


IDirectInputDevice8::GetCapabilities Method

Obtains the capabilities of the DirectInputDevice object.

Syntax

HRESULT GetCapabilities(

    LPDIDEVCAPS lpDIDevCaps
);

Parameters

lpDIDevCaps
Address of a DIDEVCAPS structure to be filled with the device capabilities. The dwSize member of this structure must be initialized before calling this method.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.
E_POINTER | An invalid pointer, usually NULL, was passed as a parameter.

Remarks

For compatibility with Microsoft DirectX 3, it is also valid to pass a DIDEVCAPS_DX3 structure with the dwSize member initialized to sizeof(DIDEVCAPS_DX3).

The number of objects returned in the DIDEVCAPS structure is the maximum number of objects that could be enumerated. However, all of these objects are not necessarily returned during a call to IDirectInputDevice8::EnumObjects.


IDirectInputDevice8::GetDeviceData Method

Retrieves buffered data from the device.

Syntax

HRESULT GetDeviceData(

    DWORD cbObjectData,
    LPDIDEVICEOBJECTDATA rgdod,
    LPDWORD pdwInOut,
    DWORD dwFlags
);

Parameters

cbObjectData
Size of the DIDEVICEOBJECTDATA structure, in bytes.
rgdod
Array of DIDEVICEOBJECTDATA structures to receive the buffered data. The number of elements in this array must be equal to the value of the pdwInOut parameter. If this parameter is NULL, the buffered data is not stored anywhere, but all other side effects take place.
pdwInOut
On entry, the number of elements in the array pointed to by the rgdod parameter. On exit, the number of elements actually obtained.
dwFlags
Flags that control the manner in which data is obtained. This value can be 0 or the following flag.
DIGDD_PEEK
Do not remove the items from the buffer. A subsequent IDirectInputDevice8::GetDeviceData call will read the same data. Normally, data is removed from the buffer after it is read.

Return Value

If the method succeeds, the return value is DI_OK or DI_BUFFEROVERFLOW.

If the method fails, the return value can be one of the following error values.

DIERR_INPUTLOST | Access to the input device has been lost. It must be reacquired.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTACQUIRED | The operation cannot be performed unless the device is acquired.
DIERR_NOTBUFFERED | The device is not buffered. Set the DIPROP_BUFFERSIZE property to enable buffering.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

Note If the method returns DI_BUFFEROVERFLOW, the data in the rgdod array has been truncated.

In the debug version of Microsoft DirectInput, if a call is made to IDirectInputDevice8::GetDeviceData and the device has been unacquired, then random bytes will be sent to the device data buffer. To make sure you are not using random device data, always check for the DIERR_UNACQUIRED return code.

Before device data can be obtained, you must set the data format and the buffer size by using the IDirectInputDevice8::SetDataFormat and IDirectInputDevice8::SetProperty methods, or by using the IDirectInputDevice8::SetActionMap method. You must also acquire the device by using the IDirectInputDevice8::Acquire method.

The maximum number of events that the buffer will hold is one less than the buffer size set with the IDirectInputDevice8::SetProperty method.

The following code example reads up to ten buffered data elements, removing them from the device buffer as they are read.

DIDEVICEOBJECTDATA rgdod[10];
DWORD dwItems = 10;
hres = idirectinputdevice9_GetDeviceData(
    sizeof(DIDEVICEOBJECTDATA),
    rgdod,
    &dwItems,
    0);
if (SUCCEEDED(hres)) {
    // dwItems = Number of elements read (could be zero).
    if (hres == DI_BUFFEROVERFLOW) {
    // Buffer had overflowed.
    }
}

Your application can flush the buffer and retrieve the number of flushed items by specifying NULL for the rgdod parameter and a pointer to a variable containing INFINITE for the pdwInOut parameter. The following code example illustrates how this can be done.

dwItems = INFINITE;
hres = idirectinputdevice9_GetDeviceData(
            pdid,
            sizeof(DIDEVICEOBJECTDATA),
            NULL,
            &dwItems,
            0);
if (SUCCEEDED(hres)) {
    // Buffer successfully flushed.
    // dwItems = Number of elements flushed.
    if (hres == DI_BUFFEROVERFLOW) {
        // Buffer had overflowed.
    }
}

Your application can query for the number of elements in the device buffer by setting the rgdod parameter to NULL, setting pdwInOut to INFINITE and setting dwFlags to DIGDD_PEEK. The following code example illustrates how this can be done.

dwItems = INFINITE;
hres = idirectinputdevice9_GetDeviceData(
            pdid,
            sizeof(DIDEVICEOBJECTDATA),
            NULL,
            &dwItems,
            DIGDD_PEEK);
if (SUCCEEDED(hres)) {
    // dwItems = Number of elements in buffer.
    if (hres == DI_BUFFEROVERFLOW) {
        // Buffer overflow occurred; not all data
        //   was successfully captured.
    }
}

To query about whether a buffer overflow has occurred, set the rgdod parameter to NULL and the pdwInOut parameter to 0. The following code example illustrates how this can be done.

dwItems = 0;
hres = idirectinputdevice9_GetDeviceData(
            pdid,
            sizeof(DIDEVICEOBJECTDATA),
            NULL,
            &dwItems,
            0);
if (hres == DI_BUFFEROVERFLOW) {
    // Buffer overflow occurred.
}

See Also

IDirectInputDevice8::Poll, Polling and Event Notification


IDirectInputDevice8::GetDeviceInfo Method

Obtains information about the device's identity.

Syntax

HRESULT GetDeviceInfo(

    LPDIDEVICEINSTANCE pdidi
);

Parameters

pdidi
Address of a DIDEVICEINSTANCE structure to be filled with information about the device's identity. An application must initialize the structure's dwSize member before calling this method.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.
E_POINTER | An invalid pointer, usually NULL, was passed as a parameter.

Remarks

For compatibility with Microsoft DirectX 3, it is also valid to pass a DIDEVICEINSTANCE_DX3 structure with the dwSize member initialized to sizeof(DIDEVICEINSTANCE_DX3).


IDirectInputDevice8::GetDeviceState Method

Retrieves immediate data from the device.

Syntax

HRESULT GetDeviceState(

    DWORD cbData,
    LPVOID lpvData
);

Parameters

cbData
Size of the buffer in the lpvData parameter, in bytes.
lpvData
Address of a structure that receives the current state of the device. The format of the data is established by a prior call to the IDirectInputDevice8::SetDataFormat method.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INPUTLOST | Access to the input device has been lost. It must be reacquired.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTACQUIRED | The operation cannot be performed unless the device is acquired.
DIERR_NOTINITIALIZED | The object has not been initialized.
E_PENDING | Data is not yet available.

Remarks

Before device data can be obtained, set the cooperative level by using the IDirectInputDevice8::SetCooperativeLevel method, then set the data format by using IDirectInputDevice8::SetDataFormat, and acquire the device by using the IDirectInputDevice8::Acquire method.

The five predefined data formats require corresponding device state structures according to the following table:

Data format | State structure
c_dfDIMouse | DIMOUSESTATE
c_dfDIMouse2 | DIMOUSESTATE2
c_dfDIKeyboard | array of 256 bytes
c_dfDIJoystick | DIJOYSTATE
c_dfDIJoystick2 | DIJOYSTATE2

For example, if you passed the c_dfDIMouse format to the IDirectInputDevice8::SetDataFormat method, you must pass a DIMOUSESTATE structure to the IDirectInputDevice8::GetDeviceState method.

See Also

IDirectInputDevice8::Poll, Polling and Event Notification, Buffered and Immediate Data


IDirectInputDevice8::GetEffectInfo Method

Obtains information about an effect.

Syntax

HRESULT GetEffectInfo(

    LPDIEFFECTINFO pdei,
    REFGUID rguid
);

Parameters

pdei
DIEFFECTINFO structure that receives information about the effect. The calling application must initialize the dwSize member of the structure before calling this method.
rguid
Reference to (C++) or address of (C) the globally unique identifier (GUID) identifying the effect for which information is being requested.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_DEVICENOTREG | The device or device instance is not registered with Microsoft DirectInput. This value is equal to the REGDB_E_CLASSNOTREG standard Component Object Model (COM) return value.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard COM return value.
DIERR_NOTINITIALIZED | The object has not been initialized.
E_POINTER | An invalid pointer, usually NULL, was passed as a parameter.

Remarks

Note If this method is called on an non-Force Feedback device, E_POINTER will be returned.


IDirectInputDevice8::GetForceFeedbackState Method

Retrieves the state of the device's force-feedback system.

Syntax

HRESULT GetForceFeedbackState(

    LPDWORD pdwOut
);

Parameters

pdwOut
Location for flags that describe the current state of the device's force-feedback system.

The value is a combination of the following constants.

DIGFFS_ACTUATORSOFF
The device's force-feedback actuators are disabled. If the device cannot report the actuator state, neither DIGFFS_ACTUATORSON nor DIGFFS_ACTUATORSOFF is returned.
DIGFFS_ACTUATORSON
The device's force-feedback actuators are enabled. If the device cannot report the actuator state, neither DIGFFS_ACTUATORSON nor DIGFFS_ACTUATORSOFF is returned.
DIGFFS_DEVICELOST
The device suffered an unexpected failure and is in an indeterminate state. It must be reset either by unacquiring and reacquiring the device, or by sending a DISFFC_RESET command.
DIGFFS_EMPTY
The device has no downloaded effects.
DIGFFS_PAUSED
Playback of all active effects has been paused.
DIGFFS_POWEROFF
The force-feedback system is not currently available. If the device cannot report the power state, neither DIGFFS_POWERON nor DIGFFS_POWEROFF is returned.
DIGFFS_POWERON
Power to the force-feedback system is currently available. If the device cannot report the power state, neither DIGFFS_POWERON nor DIGFFS_POWEROFF is returned.
DIGFFS_SAFETYSWITCHOFF
The safety switch is currently off; that is, the device cannot operate. If the device cannot report the state of the safety switch, neither DIGFFS_SAFETYSWITCHON nor DIGFFS_SAFETYSWITCHOFF is returned.
DIGFFS_SAFETYSWITCHON
The safety switch is currently on; that is, the device can operate. If the device cannot report the state of the safety switch, neither DIGFFS_SAFETYSWITCHON nor DIGFFS_SAFETYSWITCHOFF is returned.
DIGFFS_STOPPED
No effects are playing, and the device is not paused.
DIGFFS_USERFFSWITCHOFF
The user force-feedback switch is currently off; that is, the device cannot operate. If the device cannot report the state of the user force-feedback switch, neither DIGFFS_USERFFSWITCHON nor DIGFFS_USERFFSWITCHOFF is returned.
DIGFFS_USERFFSWITCHON
The user force-feedback switch is currently on; that is, the device can operate. If the device cannot report the state of the user force-feedback switch, neither DIGFFS_USERFFSWITCHON nor DIGFFS_USERFFSWITCHOFF is returned.

Applications should ignore any flags that are not currently defined.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values.

DIERR_INPUTLOST | Access to the input device has been lost. It must be reacquired.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTEXCLUSIVEACQUIRED | The operation cannot be performed unless the device is acquired in DISCL_EXCLUSIVE mode.
DIERR_NOTINITIALIZED | The object has not been initialized.
DIERR_UNSUPPORTED | The function called is not supported at this time. This value is equal to the E_NOTIMPL standard COM return value.

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.

The DIGFFS_PAUSED and DIGFFS_STOPPED flags may not always be reported correctly because there is no mechanism for the drivers to report that they support these flags.

Note When calling IDirectInputDevice8::GetForceFeedbackState, it is possible for the state of the device returned not to match the expected state. This might happen if commands recently sent by IDirectInputDevice8::SendForceFeedbackCommand are still pending. Wait a short time and then check the device state again.


IDirectInputDevice8::GetImageInfo Method

Retrieves information about a device image for use in a configuration property sheet.

Syntax

HRESULT GetImageInfo(

    LPDIDEVICEIMAGEINFOHEADER lpdiDevImageInfoHeader
);

Parameters

lpdiDevImageInfoHeader
Address of a DIDEVICEIMAGEINFOHEADER structure that receives information about the device image.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values.

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_MAPFILEFAIL | An error has occurred reading either the vendor-supplied action-mapping file for the device or reading or writing the user configuration file for the device.
DIERR_MOREDATA | Not all the requested information fitted into the buffer.
DIERR_NOTINITIALIZED | The object has not been initialized.
DIERR_OBJECTNOTFOUND | The requested object does not exist.


IDirectInputDevice8::GetObjectInfo Method

Retrieves information about a device object, such as a button or axis.

Syntax

HRESULT GetObjectInfo(

    LPDIDEVICEOBJECTINSTANCE pdidoi,
    DWORD dwObj,
    DWORD dwHow
);

Parameters

pdidoi
Address of a DIDEVICEOBJECTINSTANCE structure to be filled with information about the object. The structure's dwSize member must be initialized before this method is called.
dwObj
Value that identifies the object whose information is to be retrieved. The value set for this parameter depends on the value specified in the dwHow parameter.
dwHow
Value that specifies how the dwObj parameter should be interpreted. The dwHow value can be one of the following:
DIPH_BYOFFSET
The dwObj parameter is the offset into the current data format of the object whose information is being accessed.
DIPH_BYID
The dwObj parameter is the object type/instance identifier. This identifier is returned in the dwType member of the DIDEVICEOBJECTINSTANCE structure returned from a previous call to the IDirectInputDevice8::EnumObjects method.
DIPH_BYUSAGE
The dwObj parameter contains the HID Usage Page and Usage values of the object, combined by the DIMAKEUSAGEDWORD macro.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.
DIERR_OBJECTNOTFOUND | The requested object does not exist.
E_POINTER | An invalid pointer, usually NULL, was passed as a parameter.

Remarks

For compatibility with Microsoft DirectX 3, it is also valid to pass a DIDEVICEOBJECTINSTANCE_DX3 structure with the dwSize member initialized to sizeof(DIDEVICEOBJECTINSTANCE_DX3).


IDirectInputDevice8::GetProperty Method

Retrieves information about the input device.

Syntax

HRESULT GetProperty(

    REFGUID rguidProp,
    LPDIPROPHEADER pdiph
);

Parameters

rguidProp
Reference to (C++) or address of (C) the globally unique identifier (GUID) identifying the property to be retrieved. This can be one of the predefined values or a pointer to a GUID that identifies the property. The following properties are predefined for an input device.
DIPROP_APPDATA
Retrieves the application-defined value associated with an in-game action, as a DIPROPPOINTER.
DIPROP_AUTOCENTER
Determines whether device objects are self centering. The value returned can be DIPROPAUTOCENTER_OFF or DIPROPAUTOCENTER_ON. See IDirectInputDevice8::SetProperty for more information.
DIPROP_AXISMODE
Retrieves the axis mode. The retrieved value can be DIPROPAXISMODE_ABS or DIPROPAXISMODE_REL.
DIPROP_BUFFERSIZE
Retrieves the input buffer size. The buffer size determines the amount of data that the buffer can hold between calls to the IDirectInputDevice8::GetDeviceData method before data is lost. You can set this value to 0 to indicate that the application does not read buffered data from the device. If the buffer size in the dwData member of the DIPROPDWORD structure is too large for the device to support it, then the largest possible buffer size is set. However, this property always returns the buffer size set using the IDirectInputDevice8::SetProperty method, even if the buffer cannot be supported because it is too large.
DIPROP_CALIBRATION
Predefined property that allows the application to access the information that Microsoft DirectInput uses to manipulate axes that require calibration. This property exists primarily for applications of the control panel type. Normal applications should not need to deal with calibration information.

You can access the calibration mode property for a particular axis by setting the dwHow member of the DIPROPHEADER structure to DIPH_BYID or to DIPH_BYOFFSET and setting the dwObj member to the object ID or offset, respectively.

Control panel applications that set new calibration data must also invoke the IDirectInputJoyConfig::SendNotify method to notify other applications of the change in calibration. For more information about IDirectInputJoyConfig::SendNotify, see the DirectInput Driver Development Kit (DDK).

DIPROP_CALIBRATIONMODE
For use by device drivers; not used by applications.
DIPROP_CPOINTS
Retrieves calibration points used for the adjustment of incoming raw data as a DIPROPCPOINTS structure.
DIPROP_DEADZONE
Retrieves a value for the dead zone of a joystick, in the range from 0 through 10,000, where 0 indicates that there is no dead zone, 5,000 indicates that the dead zone extends over 50 percent of the physical range of the axis on both sides of center, and 10,000 indicates that the entire physical range of the axis is dead. When the axis is within the dead zone, it is reported as being at the center of its range.
DIPROP_FFGAIN
Retrieves the gain of the device. This property always returns DI_OK even if the device does not support force feedback. See IDirectInputDevice8::SetProperty for more information.
DIPROP_FFLOAD
Retrieves the memory load for the device. This setting applies to the entire device, rather than to any particular object, so the dwHow member of the associated DIPROPDWORD structure must be DIPH_DEVICE. The retrieved value is in the range from 0 through 100, indicating the percentage of device memory in use. The device must be acquired in exclusive mode. If it is not, the method will fail with a return value of DIERR_NOTEXCLUSIVEACQUIRED.
DIPROP_GETPORTDISPLAYNAME
Retrieves the human-readable display name of the port to which this device is connected. Not generally used by applications.
DIPROP_GRANULARITY
Retrieves the input granularity. Granularity represents the smallest distance over which the object reports movement. Most axis objects have a granularity of one; that is, all values are possible. Some axes have a larger granularity. For example, the wheel axis on a mouse can have a granularity of 20; that is, all reported changes in position are multiples of 20. In other words, when the user turns the wheel slowly, the device reports a position of 0, then 20, then 40, and so on. This is a read-only property.
DIPROP_GUIDANDPATH
Retrieves the class GUID and device interface (path) for the device. This property lets advanced applications perform operations on a HID that are not supported by DirectInput. For more information, see the DIPROPGUIDANDPATH structure.
DIPROP_INSTANCENAME
Retrieves the friendly instance name of the device. For more information, see IDirectInputDevice8::SetProperty.
DIPROP_JOYSTICKID
Retrieves the instance number of a joystick. This property is not implemented for the mouse or keyboard.
DIPROP_KEYNAME
Retrieves the localized key name for a keyboard key, as a DIPROPSTRING. Using this property on devices other than a keyboard will return unexpected names.
DIPROP_LOGICALRANGE
Retrieves the range of the raw data returned for axes on a HID. Devices can return negative values.
DIPROP_PHYSICALRANGE
Retrieves the range of data for axes as suggested by the manufacturer of a HID. Values can be negative. Normally DirectInput returns values from 0 through 0×FFFF, but the range can be made to conform to the manufacturer's suggested range by using DIPROP_RANGE.
DIPROP_PRODUCTNAME
Retrieves the friendly product name of the device. For more information, see IDirectInputDevice8::SetProperty.
DIPROP_RANGE
Retrieves the range of values an object can possibly report. For some devices, this is a read-only property.
DIPROP_SATURATION
Retrieves a value for the saturation zones of a joystick, in the range from 0 through 10,000. The saturation level is the point at which the axis is considered to be at its most extreme position. For example, if the saturation level is set to 9,500, the axis reaches the extreme of its range when it has moved 95 percent of the physical distance from its center position (or from the dead zone).
DIPROP_SCANCODE
Retrieves the scan code for a keyboard key, as a DIPROPDWORD. If successful, S_OK is returned. E_FAIL is returned if the property cannot resolve specialized keys on USB keyboards because they do not exist in scan code form. For all other failures, E_INVALIDARG is returned.
DIPROP_TYPENAME
Predefined property that retrieves the type name of a device. For most game controllers, this is the registry key name under REGSTR_PATH_JOYOEM from which static device settings can be retrieved, but predefined joystick types have special names consisting of a number sign (#) followed by a character dependent on the type. This value might not be available for all devices.
DIPROP_USERNAME
Retrieves the user name for a user currently assigned to a device, as a DIPROPSTRING. User names are set by calling IDirectInputDevice8::SetActionMap. If no user name is set, the method returns S_FALSE.
DIPROP_VIDPID
Read-only device property that retrieves the vendor identity (ID) and product ID of a HID device. This property is of type DIPROPDWORD and contains both values. These two WORD values are combined in the dwData member of the DIPROPDWORD structure. See Examples. This property applies to the entire device, rather than to any particular object, so the dwHow member of the DIPROPHEADER structure must be set to DIPH_DEVICE.
pdiph
Address of the DIPROPHEADER portion of a larger property-dependent structure that contains the DIPROPHEADER structure as a member. The following structures are used for properties:
  • DIPROPDWORD is used for properties represented by a single numerical value.
  • DIPROPGUIDANDPATH is used for DIPROP_GUIDANDPATH.
  • DIPROPRANGE is used for properties represented by a pair of numerical values. Currently, the only such property is DIPROP_RANGE.
  • DIPROPSTRING is used for string properties.

Return Value

If the method succeeds, the return value is DI_OK or S_FALSE.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTEXCLUSIVEACQUIRED | The operation cannot be performed unless the device is acquired in DISCL_EXCLUSIVE mode.
DIERR_NOTINITIALIZED | The object has not been initialized.
DIERR_OBJECTNOTFOUND | The requested object does not exist.
DIERR_UNSUPPORTED | The function called is not supported at this time. This value is equal to the E_NOTIMPL standard COM return value.

Remarks

If rguidProp is set to DIPROP_APPDATA, the dwHow member of the DIPROPHEADER structure should only be set to DIPH_BYUSAGE when getting information about input controls, such as buttons or axes. Setting DIPH_BYUSAGE for other device objects such as PID or LED devices can lead to unpredictable results.

S_FALSE is always returned when IDirectInputDevice8::GetProperty is called with rguidProp set to DIPROP_GETPORTDISPLAYNAME, even if the method succeeds.

The scan codes reported in Microsoft DirectX 8.1 are different from the ones reported in DirectX 8.0. In DirectX 8.0, the property actually reported the single byte DIK_* constant associated with the key, not the scan code. In DirectX 8.1 and DirectX 9.0, the property reports the make scan code as would be reported by a PS/2 keyboard. In some cases, scan codes are multiple bytes, in which case the scan code bytes are ordered with the first byte in the least significant byte of the DWORD retrieved by the property.

Examples

The following C example shows how to obtain the value of the DIPROP_BUFFERSIZE property.

DIPROPDWORD dipdw;  // DIPROPDWORD contains a DIPROPHEADER structure.
HRESULT hr;
dipdw.diph.dwSize       = sizeof(DIPROPDWORD);
dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
dipdw.diph.dwObj        = 0; // device property
dipdw.diph.dwHow        = DIPH_DEVICE;

hr = idirectinputdevice9_GetProperty(pdid, DIPROP_BUFFERSIZE, &dipdw.diph);
if (SUCCEEDED(hr)) {
    // The dipdw.dwData member contains the buffer size.
}

The following example shows how to extract the two WORD values from the dwData member of the DIPROPDWORD structure using the DIPROP_VIDPID property:

wVendorID  = LOWORD(DIPROPDWORD.dwData);
wProductID = HIWORD(DIPROPDWORD.dwData);

See Also

IDirectInputDevice8::SetProperty


IDirectInputDevice8::Initialize Method

Initializes a DirectInputDevice object. The IDirectInput8::CreateDevice method automatically initializes a device after creating it; applications normally do not need to call this method.

Syntax

HRESULT Initialize(

    HINSTANCE hinst,
    DWORD dwVersion,
    REFGUID rguid
);

Parameters

hinst
Instance handle to the application or dynamic-link library (DLL) that is creating the DirectInputDevice object. Microsoft DirectInput uses this value to determine whether the application or DLL has been certified and to establish any special behaviors that might be necessary for backward compatibility.

It is an error for a DLL to pass the handle to the parent application. For example, a Microsoft ActiveX control embedded in a Web page that uses DirectInput must pass its own instance handle, and not the handle to the browser. This ensures that DirectInput recognizes the control and can enable any special behaviors that may be necessary.
dwVersion
Version number of DirectInput for which the application is designed. This value is normally DIRECTINPUT_VERSION. Passing the version number of a previous version causes DirectInput to emulate that version.
rguid
Reference to (C++) or address of (C) the globally unique identifier (GUID) identifying the instance of the device with which the interface should be associated. The IDirectInput8::EnumDevices method can be used to determine which instance GUIDs are supported by the system.

Return Value

If the method succeeds, the return value is DI_OK or S_FALSE. If the method returns S_FALSE, the device had already been initialized with the instance GUID passed in though rGUID.

If the method fails, the return value can be one of the following error values:

DIERR_ACQUIRED | The operation cannot be performed while the device is acquired.
DIERR_DEVICENOTREG | The device or device instance is not registered with DirectInput. This value is equal to the REGDB_E_CLASSNOTREG standard Component Object Model (COM) return value.

Remarks

If this method fails, the underlying object should be considered to be in an indeterminate state and must be reinitialized before use.


IDirectInputDevice8::Poll Method

Retrieves data from polled objects on a Microsoft DirectInput device. If the device does not require polling, calling this method has no effect. If a device that requires polling is not polled periodically, no new data is received from the device. Calling this method causes DirectInput to update the device state, generate input events (if buffered data is enabled), and set notification events (if notification is enabled).

Syntax

HRESULT Poll(VOID);

Return Value

If the method succeeds, the return value is DI_OK, or DI_NOEFFECT if the device does not require polling.

If the method fails, the return value can be one of the following error values:

DIERR_INPUTLOST | Access to the input device has been lost. It must be reacquired.
DIERR_NOTACQUIRED | The operation cannot be performed unless the device is acquired.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

Before a device data can be polled, the data format must be set by using the IDirectInputDevice8::SetDataFormat or IDirectInputDevice8::SetActionMap method, and the device must be acquired by using the IDirectInputDevice8::Acquire method.

See Also

Polling and Event Notification


IDirectInputDevice8::RunControlPanel Method

Runs the Microsoft DirectInput control panel associated with this device. If the device does not have a control panel associated with it, the default device control panel is launched.

Syntax

HRESULT RunControlPanel(

    HWND hwndOwner,
    DWORD dwFlags
);

Parameters

hwndOwner
Parent window handle. If this parameter is NULL , no parent window is used.
dwFlags
Not currently used. Zero is the only valid value.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.


IDirectInputDevice8::SendDeviceData Method

Sends data to a device that accepts output.

Note There are no devices that accept output from IDirectInputDevice8::SendDeviceData. See Remarks.

Syntax

HRESULT SendDeviceData(

    DWORD cbObjectData,
    LPCDIDEVICEOBJECTDATA rgdod,
    LPDWORD pdwInOut,
    DWORD fl
);

Parameters

cbObjectData
Size, in bytes, of a single DIDEVICEOBJECTDATA structure.
rgdod
Array of DIDEVICEOBJECTDATA structures containing the data to send to the device.
pdwInOut
On entry, the variable pointed to by this parameter contains the number of elements in the array pointed to by rgdod. On exit, it contains the number of elements sent to the device.
fl
Flags controlling the manner in which data is sent. This can be 0 or the following value.
DISDD_CONTINUE
The device data sent is overlaid on the previously sent device data.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values.

DIERR_INPUTLOST | Access to the input device has been lost. It must be reacquired.
DIERR_NOTACQUIRED | The operation cannot be performed unless the device is acquired.
DIERR_REPORTFULL | More information was requested to be sent than can be sent to the device.
DIERR_UNPLUGGED | The operation could not be completed because the device is not plugged in.

Remarks

Applications should not use IDirectInputDevice8::SendDeviceData. Force Feedback is the recommended way to send data to a device. If you want to send other data to a device, such as changing LED or internal device states, the HID application programming interface (API) is the recommended way.


IDirectInputDevice8::SendForceFeedbackCommand Method

Sends a command to the device's force-feedback system.

Syntax

HRESULT SendForceFeedbackCommand(

    DWORD dwFlags
);

Parameters

dwFlags
Single value indicating the desired change in state. The value can be one of the following.
DISFFC_CONTINUE
Paused playback of all active effects is to be continued. It is an error to send this command when the device is not in a paused state.
DISFFC_PAUSE
Playback of all active effects is to be paused. This command also stops the clock-on effects so that they continue playing to their full duration when restarted.

While the device is paused, new effects cannot be started, and existing ones cannot be modified. Doing so can cause the subsequent DISFFC_CONTINUE command to fail to perform properly.

To abandon a pause and stop all effects, use the DISFFC_STOPALL or DISFCC_RESET commands.

DISFFC_RESET
The device's force-feedback system is to be put in its startup state. All effects are removed from the device, are no longer valid, and must be re-created if they are to be used again. The device's actuators are disabled.
DISFFC_SETACTUATORSOFF
The device's force-feedback actuators are to be disabled. While the actuators are off, effects continue to play but are ignored by the device. Using the analogy of a sound playback device, they are muted, rather than paused.
DISFFC_SETACTUATORSON
The device's force-feedback actuators are to be enabled.
DISFFC_STOPALL
Playback of any active effects is to be stopped. All active effects are reset, but are still being maintained by the device and are still valid. If the device is in a paused state, that state is lost. This command is equivalent to calling the IDirectInputEffect::Stop method for each effect playing.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values.

DIERR_INPUTLOST | Access to the input device has been lost. It must be reacquired.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTEXCLUSIVEACQUIRED | The operation cannot be performed unless the device is acquired in DISCL_EXCLUSIVE mode.
DIERR_NOTINITIALIZED | The object has not been initialized.
DIERR_UNSUPPORTED | The function called is not supported at this time. This value is equal to the E_NOTIMPL standard COM return value.

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.

Note When calling IDirectInputDevice8::GetForceFeedbackState, it is possible for the state of the device returned not to match the expected state. This might happen if commands recently sent by IDirectInputDevice8::SendForceFeedbackCommand are still pending. Wait a short time and then check the device state again.


IDirectInputDevice8::SetActionMap Method

Sets the data format for a device and maps application-defined actions to device objects. It also sets the buffer size for buffered data.

Syntax

HRESULT SetActionMap(

    LPCDIACTIONFORMAT lpdiActionFormat,
    LPCTSTR lptszUserName,
    DWORD dwFlags
);

Parameters

lpdiActionFormat
Address of a DIACTIONFORMAT structure containing information about the action map to be applied.
lptszUserName
Unicode string that specifies the name of the user for which the action map is being set. A value of NULL specifies the user currently logged into the system.
dwFlags
DWORD value that specifies how the action map is applied. This can be one of the following values.
DIDSAM_DEFAULT
Set the action map for this user. If the map differs from the current map, the new settings are saved to disk.
DIDSAM_FORCESAVE
Always save the configuration to disk.
DIDSAM_NOUSER
Reset user ownership for this device in the default configuration property sheet. Resetting user ownership does not remove the current action map.

Return Value

If the method succeeds, the return value can be one of the following error values: DI_OK, DI_SETTINGSNOTSAVED, or DI_WRITEPROTECT.

If the method fails, the return value can be one of the following error values: DIERR_ACQUIRED or DIERR_INVALIDPARAM.

DI_OK | The operation completed successfully. This value is equal to the S_OK standard Component Object Model (COM) return value.
DI_SETTINGSNOTSAVED | The action map was applied to the device, but the settings could not be saved.
DI_WRITEPROTECT | A SUCCESS code indicating that settings cannot be modified.
DIERR_ACQUIRED | The operation cannot be performed while the device is acquired.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard COM return value.

Remarks

This method provides the mechanism to change action-to-control mapping from the device defaults. An application must use this method to map its in-game actions to virtual controls.

The user name passed to this method binds a set of action mappings for a device to a specific user. Settings are automatically saved to disk when they differ from the currently applied map. Applications that accept input from multiple users should be very careful when applying action maps to the system mouse or keyboard, as the action maps for each user may conflict.

The method can be called only when the device is not acquired.

If IDirectInputDevice8::BuildActionMap succeeds but no actions have been mapped, a subsequent call to IDirectInputDevice8::SetActionMap will return DI_OK but a call to IDirectInputDevice8::Acquire will fail with DIERR_INVALIDPARAM.

See Also

IDirectInputDevice8::BuildActionMap


IDirectInputDevice8::SetCooperativeLevel Method

Establishes the cooperative level for this instance of the device. The cooperative level determines how this instance of the device interacts with other instances of the device and the rest of the system.

Syntax

HRESULT SetCooperativeLevel(

    HWND hwnd,
    DWORD dwFlags
);

Parameters

hwnd
Window handle to be associated with the device. This parameter must be a valid top-level window handle that belongs to the process. The window associated with the device must not be destroyed while it is still active in a Microsoft DirectInput device.
dwFlags
Flags that describe the cooperative level associated with the device. The following flags are defined:
DISCL_BACKGROUND
The application requires background access. If background access is granted, the device can be acquired at any time, even when the associated window is not the active window.
DISCL_EXCLUSIVE
The application requires exclusive access. If exclusive access is granted, no other instance of the device can obtain exclusive access to the device while it is acquired. However, nonexclusive access to the device is always permitted, even if another application has obtained exclusive access.

An application that acquires the mouse or keyboard device in exclusive mode should always unacquire the devices when it receives WM_ENTERSIZEMOVE and WM_ENTERMENULOOP messages. Otherwise, the user cannot manipulate the menu or move and resize the window.
DISCL_FOREGROUND
The application requires foreground access. If foreground access is granted, the device is automatically unacquired when the associated window moves to the background.
DISCL_NONEXCLUSIVE
The application requires nonexclusive access. Access to the device does not interfere with other applications that are accessing the same device.
DISCL_NOWINKEY
Disable the Microsoft Windows logo key. Setting this flag ensures that the user cannot inadvertently break out of the application. Note, however, that DISCL_NOWINKEY has no effect when the default action mapping user interface (UI) is displayed, and the Windows logo key will operate normally as long as that UI is present.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.
E_HANDLE | The HWND parameter is not a valid top-level window that belongs to the process.

Remarks

Applications must specify either DISCL_FOREGROUND or DISCL_BACKGROUND; it is an error to specify both or neither. Similarly, applications must specify either DISCL_EXCLUSIVE or DISCL_NONEXCLUSIVE.

If the system mouse is acquired in exclusive mode, the pointer is removed from the screen until the device is unacquired. This applies only to a mouse created by passing GUID_SysMouse to IDirectInput8::CreateDevice.

Applications that select the background exclusive mode cooperative level are not guaranteed to retain access to the device if another application requests exclusive access. When a background exclusive mode application loses access, calls to DirectInput device methods will fail and return DIERR_NOTACQUIRED. The application can regain access to the device by manually unacquiring the device and reaquiring it.

Applications must call this method before acquiring the device by using the IDirectInputDevice8::Acquire method.

See Also

Cooperative Levels


IDirectInputDevice8::SetDataFormat Method

Sets the data format for the Microsoft DirectInput device.

Syntax

HRESULT SetDataFormat(

    LPCDIDATAFORMAT lpdf
);

Parameters

lpdf
Address of a structure that describes the format of the data that the DirectInputDevice should return. An application can define its own DIDATAFORMAT structure or use one of the following predefined global variables:
  • c_dfDIKeyboard
  • c_dfDIMouse
  • c_dfDIMouse2
  • c_dfDIJoystick
  • c_dfDIJoystick2

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_ACQUIRED | The operation cannot be performed while the device is acquired.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

The data format must be set before the device can be acquired by using the IDirectInputDevice8::Acquire method. It is necessary to set the data format only once. The data format cannot be changed while the device is acquired.

If the application is using action mapping, the data format is set instead by the call to IDirectInputDevice8::SetActionMap.

See Also

IDirectInputDevice8::GetDeviceState


IDirectInputDevice8::SetEventNotification Method

Specifies an event that is to be set when the device state changes. It is also used to turn off event notification.

Syntax

HRESULT SetEventNotification(

    HANDLE hEvent
);

Parameters

hEvent
Handle to the event that is to be set when the device state changes. Microsoft DirectInput uses the Microsoft Win32 SetEvent function on the handle when the state of the device changes. If the hEvent parameter is NULL, notification is disabled.

The application can create the handle as either a manual-reset or autoreset event by using the Win32 CreateEvent function. If the event is created as an autoreset event, the operating system automatically resets the event when a wait has been satisfied. If the event is created as a manual-reset event, it is the application's responsibility to call the Win32 ResetEvent function to reset it. DirectInput does not call the Win32 ResetEvent function for event notification handles. Most applications create the event as an automatic-reset event.

Return Value

If the method succeeds, the return value is DI_OK or DI_POLLEDDEVICE.

If the method fails, the return value can be one of the following error values:

DIERR_ACQUIRED | The operation cannot be performed while the device is acquired.
DIERR_HANDLEEXISTS | The device already has an event notification associated with it. This value is equal to the E_ACCESSDENIED standard Component Object Model (COM) return value.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard COM return value.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

A device state change is defined as any of the following:

  • A change in the position of an axis
  • A change in the state (pressed or released) of a button
  • A change in the direction of a POV control
  • Loss of acquisition

Do not call the Win32 CloseHandle function on the event while it has been selected into a DirectInputDevice object. You must call this method with the hEvent parameter set to NULL before closing the event handle.

The event notification handle cannot be changed while the device is acquired. If the function is successful, the application can use the event handle like any other Win32 event handle.

Examples

The following code example checks whether the handle is currently set without blocking:

dwResult = WaitForSingleObject(hEvent, 0);
if (dwResult == WAIT_OBJECT_0) {
    // Event is set. If the event was created as
    // autoreset, it has also been reset.
}

The following code example illustrates blocking indefinitely until the event is set. This behavior is strongly discouraged because the thread does not respond to the system until the wait is satisfied. In particular, the thread does not respond to Microsoft Windows messages.

dwResult = WaitForSingleObject(hEvent, INFINITE);
if (dwResult == WAIT_OBJECT_0) {
    // Event has been set. If the event was created
    // as autoreset, it has also been reset.
}

The following code example illustrates a typical application loop for a non-message-based application that uses two events:

HANDLE ah[2] = { hEvent1, hEvent2 };

while (TRUE) {

    dwResult = MsgWaitForMultipleObjects(2, ah, FALSE,
                        INFINITE, QS_ALLINPUT);
    switch (dwResult) {
    case WAIT_OBJECT_0:
        // Event 1 has been set. If the event was created as
        // autoreset, it has also been reset.
        ProcessInputEvent1();
        break;

    case WAIT_OBJECT_0 + 1:
        // Event 2 has been set. If the event was created as
        // autoreset, it has also been reset.
        ProcessInputEvent2();
        break;

    case WAIT_OBJECT_0 + 2:
        // A Windows message has arrived. Process
        // messages until there aren't any more.
        while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){
            if (msg.message == WM_QUIT) {
                goto exitapp;
            }
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        break;

    default:
        // Unexpected error.
        Panic();
        break;
    }
}

The following code example illustrates a typical message loop for a message-based application that uses two events:

HANDLE ah[2] = { hEvent1, hEvent2 };
DWORD dwWait = 0;

while (TRUE) {

    dwResult = MsgWaitForMultipleObjects(2, ah, FALSE,
                                         dwWait, QS_ALLINPUT);
    dwWait = 0;

    switch (dwResult) {
    case WAIT_OBJECT_0:
        // Event 1 has been set. If the event was
        // created as autoreset, it has also
        // been reset.
        ProcessInputEvent1();
        break;

    case WAIT_OBJECT_0 + 1:
        // Event 2 has been set. If the event was
        // created as autoreset, it has also
        // been reset.
        ProcessInputEvent2();
        break;

    case WAIT_OBJECT_0 + 2:
        // A Windows message has arrived. Process
        // messages until there aren't any more.
        while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){
            if (msg.message == WM_QUIT) {
                goto exitapp;
            }
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        break;

    default:
        // No input or messages waiting.
        // Do a frame of the game.
        // If the game is idle, tell the next wait
        // to wait indefinitely for input or a message.
        if (!DoGame()) {
            dwWait = INFINITE;
        }
        break;
    }
}

See Also

Polling and Event Notification


IDirectInputDevice8::SetProperty Method

Sets properties that define the device behavior. These properties include input buffer size and axis mode.

Syntax

HRESULT SetProperty(

    REFGUID rguidProp,
    LPCDIPROPHEADER pdiph
);

Parameters

rguidProp
Reference to (C++) or address of (C) the globally unique identifier (GUID) identifying the property to be set. This can be one of the predefined values, or a pointer to a GUID that identifies the property. The following property values are predefined for an input device:
DIPROP_APPDATA
Sets the application-defined value associated with an in-game action, as a DIPROPPOINTER.
DIPROP_AUTOCENTER
Specifies whether device objects are self centering. This setting applies to the entire device, rather than to any particular object, so the dwHow member of the associated DIPROPDWORD structure must be DIPH_DEVICE.

The dwData member can be one of the following values.

DIPROPAUTOCENTER_OFF: The device should not automatically center when the user releases the device. An application that uses force feedback should disable autocentering before playing effects.

DIPROPAUTOCENTER_ON: The device should automatically center when the user releases the device.

Not all devices support the autocenter property.

DIPROP_AXISMODE
Sets the axis mode. The value being set (DIPROPAXISMODE_ABS or DIPROPAXISMODE_REL) must be specified in the dwData member of the associated DIPROPDWORD structure. See the description of the pdiph parameter for more information.

This setting applies to the entire device, so the dwHow member of the associated DIPROPDWORD structure must be set to DIPH_DEVICE.
DIPROP_BUFFERSIZE
Sets the input buffer size. The value being set must be specified in the dwData member of the associated DIPROPDWORD structure. See Remarks. This setting applies to the entire device, so the dwHow member of the associated DIPROPDWORD structure must be set to DIPH_DEVICE.
DIPROP_CALIBRATION
Predefined property that allows the application to access the information that Microsoft DirectInput uses to manipulate axes that require calibration. This property exists primarily for applications of the control panel type. Normal applications should not need to deal with calibration information.

You can access the calibration mode property for an axis by setting the dwHow member of the DIPROPHEADER structure to DIPH_BYID or to DIPH_BYOFFSET and setting the dwObj member to the object identifier (ID) or offset, respectively.

Control panel applications that set new calibration data must also invoke the IDirectInputJoyConfig::SendNotify method to notify other applications of the change in calibration. For more information about IDirectInputJoyConfig::SendNotify, see the Microsoft DirectX Driver Development Kit (DDK).

DIPROP_CALIBRATIONMODE
Enables the application to specify whether DirectInput should retrieve calibrated or uncalibrated data from an axis. By default, DirectInput retrieves calibrated data.

Setting the calibration mode for the entire device is equivalent to setting it for each axis individually.

The dwData member of the DIPROPDWORD structure can be one of the following values:

DIPROPCALIBRATIONMODE_COOKED: DirectInput should return data after applying calibration information. This is the default mode.

DIPROPCALIBRATIONMODE_RAW: DirectInput should return raw, uncalibrated data. This mode is typically used only by applications of the control panel type. Note that raw data might include negative values.

Setting a device into raw mode causes the dead zone, saturation, and range settings to be ignored.

DIPROP_CPOINTS
Sets calibration points used for the adjustment of incoming raw data. The values being set must be specified as CPOINT types in the cp array of the associated DIPROPCPOINTS structure. This setting applies to individual device objects, so the dwHow member of the associated DIPROPHEADER structure must be set to either DIPH_BYID or DIPH_BYOFFSET.
DIPROP_DEADZONE
Sets the value for the dead zone of a joystick, in the range from 0 through 10,000, where 0 indicates that there is no dead zone, 5,000 indicates that the dead zone extends over 50 percent of the physical range of the axis on both sides of center, and 10,000 indicates that the entire physical range of the axis is dead. When the axis is within the dead zone, it is reported as being at the center of its range. This setting can be applied to either the entire device or to a specific axis.
DIPROP_FFGAIN
Sets the gain for the device. This setting applies to the entire device, rather than to any particular object, so the dwHow member of the associated DIPROPDWORD structure must be DIPH_DEVICE.

The dwData member contains a gain value that is applied to all effects created on the device. The value is an integer in the range from 0 through 10,000, specifying the amount by which effect magnitudes should be scaled for the device. For example, a value of 10,000 indicates that all effect magnitudes are to be taken at face value. A value of 9,000 indicates that all effect magnitudes are to be reduced to 90 percent of their nominal magnitudes.

DirectInput always checks the gain value before setting the gain property. If the gain is outside of the range (less than zero or greater than 10,000), IDirectInputDevice8::SetProperty will return DIERR_INVALIDPARAM. Otherwise, if successful, it will return DI_OK, even if the device does not support force feedback.

Setting a gain value is useful when an application wants to scale down the strength of all force-feedback effects uniformly, based on user preferences.

Unlike other properties, the gain can be set when the device is in an acquired state.

DIPROP_INSTANCENAME
This property exists for advanced applications that want to change the friendly instance name of a device (as returned in the tszInstanceName member of the DIDEVICEINSTANCE structure) to distinguish it from similar devices that are plugged in simultaneously. Most applications should have no need to change the friendly name.

This setting applies to the entire device, so the dwHow member of the associated DIPROPDWORD structure must be set to DIPH_DEVICE.

The pdiph parameter must be a pointer to the diph member of a DIPROPSTRING structure.

DIPROP_PRODUCTNAME
This property exists for advanced applications that want to change the friendly product name of a device (as returned in the tszProductName member of the DIDEVICEINSTANCE structure) to distinguish it from similar devices which are plugged in simultaneously. Most applications should have no need to change the friendly name.

This setting applies to the entire device, so the dwHow member of the associated DIPROPDWORD structure must be set to DIPH_DEVICE.

The pdiph parameter must be a pointer to the diph member of a DIPROPSTRING structure.

Setting the product name is only useful for changing the user-defined name of an analog joystick on Microsoft Windows 98,Windows 2000, and Windows Millennium Edition (Windows Me) computers. In other cases, attempting to set this property will still return DI_OK. However, the name is not stored in a location used by IDirectInputDevice8::GetProperty.

DIPROP_RANGE
Sets the range of values an object can possibly report. The minimum and maximum values are taken from the lMin and lMax members of the associated DIPROPRANGE structure.

For some devices, this is a read-only property.

You cannot set a reverse range; lMax must be greater than lMin.

DIPROP_SATURATION
Sets the value for the saturation zones of a joystick, in the range from 0 through 10,000. The saturation level is the point at which the axis is considered to be at its most extreme position. For example, if the saturation level is set to 9,500, the axis reaches the extreme of its range when it has moved 95 percent of the physical distance from its center position (or from the dead zone). This setting can be applied to either the entire device or a specific axis.
pdiph
Address of the DIPROPHEADER structure contained within the type-specific property structure.

Return Value

If the method succeeds, the return value is DI_OK or DI_PROPNOEFFECT.

If the method fails, the return value can be one of the following error values.

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.
DIERR_OBJECTNOTFOUND | The requested object does not exist.
DIERR_UNSUPPORTED | The function called is not supported at this time. This value is equal to the E_NOTIMPL standard COM return value.

Remarks

The buffer size determines the amount of data that the buffer can hold between calls to the IDirectInputDevice8::GetDeviceData method before data is lost. This value may be set to 0 to indicate that the application does not read buffered data from the device. If the buffer size in the dwData member of the DIPROPDWORD structure is too large for the device to support it, then the largest possible buffer size is set.

See Also

IDirectInputDevice8::GetProperty


IDirectInputDevice8::Unacquire Method

Releases access to the device.

Syntax

HRESULT Unacquire(VOID);

Return Value

The return value is DI_OK is the device was unacquired, or DI_NOEFFECT if the device was not in an acquired state.


IDirectInputDevice8::WriteEffectToFile Method

Saves information about one or more force-feedback effects to a file that can be read by using IDirectInputDevice8::EnumEffectsInFile. This method is chiefly of interest to those wanting to write their own force-authoring applications.

Syntax

HRESULT WriteEffectToFile(

    LPCSTR lpszFileName,
    DWORD dwEntries,
    LPCDIFILEEFFECT rgDiFileEft,
    DWORD dwFlags
);

Parameters

lpszFileName
Name of the RIFF file.
dwEntries
Number of structures in the rgDiFileEft array.
rgDiFileEft
Array of DIFILEEFFECT structures.
dwFlags
Flags which control how the effect should be written. This can be DIFEF_DEFAULT (= 0) or the following value:
DIFEF_INCLUDENONSTANDARD
Includes effects that are not defined by Microsoft DirectInput. If this flag is not specified, only effects with globally unique identifiers (GUIDs) defined in Dinput.h, such as GUID_ConstantForce, are written.

Return Value

If the method succeeds, it returns DI_OK.

If it fails, the return value can be DIERR_INVALIDPARAM.

See Also

IDirectInputDevice8::EnumEffectsInFile


IDirectInputEffect Interface

Applications use the methods of the IDirectInputEffect interface to manage effects of force-feedback devices.

IDirectInputEffect Members

Download

Places the effect on the device. If the effect is already on the device, the existing effect is updated to match the values set by the IDirectInputEffect::SetParameters method.

Escape

Sends a hardware-specific command to the driver.

GetEffectGuid

Retrieves the globally unique identifier (GUID) for the effect represented by the IDirectInputEffect object.

GetEffectStatus

Retrieves the status of an effect.

GetParameters

Retrieves information about an effect.

Initialize

Initializes a DirectInputEffect object.

SetParameters

Sets the characteristics of an effect.

Start

Begins playing an effect. If the effect is already playing, it is restarted from the beginning. If the effect has not been downloaded or has been modified since its last download, it is downloaded before being started. This default behavior can be suppressed by passing the DIES_NODOWNLOAD flag.

Stop

Stops playing an effect.

Unload

Removes the effect from the device. If the effect is playing, it is automatically stopped before it is unloaded.

Remarks

The interface is obtained by using the IDirectInputDevice8::CreateEffect method.

The LPDIRECTINPUTEFFECT type is defined as a pointer to the IDirectInputEffect interface:

typedef struct IDirectInputEffect    *LPDIRECTINPUTEFFECT;

Interface Information

Stock Implementation | dinput.dll
Custom Implementation | No
Inherits from | IUnknown
Header | dinput.h
Minimum operating systems | Windows 98


IDirectInputEffect::Download Method

Places the effect on the device. If the effect is already on the device, the existing effect is updated to match the values set by the IDirectInputEffect::SetParameters method.

Syntax

HRESULT Download(VOID);

Return Value

If the method succeeds, the return value is DI_OK or S_FALSE.

If the method fails, the return value can be one of the following error values:

DIERR_DEVICEFULL | The device is full.
DIERR_EFFECTPLAYING | The parameters were updated in memory but were not downloaded to the device because the device does not support updating an effect while it is still playing.
DIERR_INCOMPLETEEFFECT | The effect could not be downloaded because essential information is missing. For example, no axes have been associated with the effect, or no type-specific information has been supplied.
DIERR_INPUTLOST | Access to the input device has been lost. It must be reacquired.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTEXCLUSIVEACQUIRED | The operation cannot be performed unless the device is acquired in DISCL_EXCLUSIVE mode.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

If the method returns S_FALSE, the effect has already been downloaded to the device.

It is valid to update an effect while it is playing. The semantics of such an operation are explained in the reference for IDirectInputEffect::SetParameters.


IDirectInputEffect::Escape Method

Sends a hardware-specific command to the driver.

Syntax

HRESULT Escape(

    LPDIEFFESCAPE pesc
);

Parameters

pesc
DIEFFESCAPE structure that describes the command to be sent. On success, the cbOutBuffer member contains the number of bytes of the output buffer used.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_NOTINITIALIZED | The object has not been initialized.
DIERR_DEVICEFULL | The device is full.

Remarks

Other device-specific error codes are also possible. Ask the hardware manufacturer for details.

Because each driver implements different escapes, it is the application's responsibility to ensure that it is sending the escape to the correct driver by comparing the value of the guidFFDriver member of the DIDEVICEINSTANCE structure against the value the application is expecting.


IDirectInputEffect::GetEffectGuid Method

Retrieves the globally unique identifier (GUID) for the effect represented by the IDirectInputEffect object.

Syntax

HRESULT GetEffectGuid(

    LPGUID pguid
);

Parameters

pguid
GUID structure that is filled by the method.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

Additional information about the effect can be obtained by passing the GUID to IDirectInputDevice8::GetEffectInfo.


IDirectInputEffect::GetEffectStatus Method

Retrieves the status of an effect.

Syntax

HRESULT GetEffectStatus(

    LPDWORD pdwFlags
);

Parameters

pdwFlags
Status flags for the effect. The value can be 0 or one or more of the following constants:
DIEGES_PLAYING
The effect is playing.
DIEGES_EMULATED
The effect is emulated.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTINITIALIZED | The object has not been initialized.


IDirectInputEffect::GetParameters Method

Retrieves information about an effect.

Syntax

HRESULT GetParameters(

    LPDIEFFECT peff,
    DWORD dwFlags
);

Parameters

peff
Address of a DIEFFECT structure that receives effect information. The dwSize member must be filled in by the application before calling this method.
dwFlags
Flags that specify which parts of the effect information are to be retrieved. The value can be 0 or one or more of the following constants:
DIEP_ALLPARAMS
The union of all other DIEP_* flags, indicating that all members of the DIEFFECT structure are being requested.
DIEP_ALLPARAMS_DX5
The union of all other DIEP_* flags except the DIEP_STARTDELAY flag.
DIEP_AXES
The cAxes and rgdwAxes members should receive data. The cAxes member on entry contains the size (in DWORD) of the buffer pointed to by the rgdwAxes member. If the buffer is too small, the method returns DIERR_MOREDATA and sets cAxes to the necessary size of the buffer.
DIEP_DIRECTION
The cAxes and rglDirection members should receive data. The cAxes member on entry contains the size (in DWORD) of the buffer pointed to by the rglDirection member. If the buffer is too small, the IDirectInputEffect::GetParameters method returns DIERR_MOREDATA and sets cAxes to the necessary size of the buffer.

The dwFlags member must include at least one of the coordinate system flags (DIEFF_CARTESIAN, DIEFF_POLAR, or DIEFF_SPHERICAL). Microsoft DirectInput returns the direction of the effect in one of the coordinate systems you specified, converting between coordinate systems as necessary. On exit, exactly one of the coordinate system flags is set in the dwFlags member, indicating which coordinate system DirectInput used. In particular, passing all three coordinate system flags retrieves the coordinates in exactly the same format in which they were set.
DIEP_DURATION
The dwDuration member should receive data.
DIEP_ENVELOPE
The lpEnvelope member points to a DIENVELOPE structure that should receive data. If the effect does not have an envelope associated with it, the lpEnvelope member is set to NULL.
DIEP_GAIN
The dwGain member should receive data.
DIEP_SAMPLEPERIOD
The dwSamplePeriod member should receive data.
DIEP_STARTDELAY
The dwStartDelay member should receive data.
DIEP_TRIGGERBUTTON
The dwTriggerButton member should receive data.
DIEP_TRIGGERREPEATINTERVAL
The dwTriggerRepeatInterval member should receive data.
DIEP_TYPESPECIFICPARAMS
The lpvTypeSpecificParams member points to a buffer whose size is specified by the cbTypeSpecificParams member. On return, the buffer is filled in with the type-specific data associated with the effect, and the cbTypeSpecificParams member contains the number of bytes copied. If the buffer supplied by the application is too small to contain all the type-specific data, the method returns DIERR_MOREDATA, and the cbTypeSpecificParams member contains the required size of the buffer in bytes.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_MOREDATA | Not all the requested information fitted into the buffer.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

Common errors resulting in a DIERR_INVALIDPARAM error include not setting the dwSize member of the DIEFFECT structure, passing invalid flags, or not setting up the members in the DIEFFECT structure properly in preparation for receiving the effect information. For example, if information is to be retrieved in the dwTriggerButton member, the dwFlags member must be set to either DIEFF_OBJECTIDS or DIEFF_OBJECTOFFSETS so that DirectInput knows how to describe the button.


IDirectInputEffect::Initialize Method

Initializes a DirectInputEffect object.

Syntax

HRESULT Initialize(

    HINSTANCE hinst,
    DWORD dwVersion,
    REFGUID rguid
);

Parameters

hinst
Instance handle to the application or dynamic-link library (DLL) that is creating the DirectInputEffect object. Microsoft DirectInput uses this value to determine whether the application or DLL has been certified and to establish any special behaviors that might be necessary for backward compatibility. It is an error for a DLL to pass the handle to the parent application.
dwVersion
Version number of DirectInput for which the application is designed. This value is normally DIRECTINPUT_VERSION. Passing the version number of a previous version causes DirectInput to emulate that version.
rguid
Address of the globally unique identifier (GUID) identifying the effect with which the interface is associated. The IDirectInputDevice8::EnumEffects method can be used to determine which effect GUIDs are supported by the device.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be DIERR_DEVICENOTREG.

Remarks

If this method fails, the underlying object should be considered to be an indeterminate state and needs to be reinitialized before it can be subsequently used.

If this method succeeds, all effect parameters will be invalid. You must call IDirectInputEffect::SetParameters before an effect can be downloaded or started.

The IDirectInputDevice8::CreateEffect method automatically initializes the effect after creating it. Applications normally do not need to call the IDirectInputEffect::Initialize method.


IDirectInputEffect::SetParameters Method

Sets the characteristics of an effect.

Syntax

HRESULT SetParameters(

    LPCDIEFFECT peff,
    DWORD dwFlags
);

Parameters

peff
DIEFFECT structure that contains effect information. The dwSize member must be filled in by the application before calling this method, as well as any members specified by corresponding bits in the dwFlags parameter.
dwFlags
Flags that specify which portions of the effect information are to be set and how the downloading of the parameters should be handled. The value can be 0 or one or more of the following constants:
DIEP_AXES
The cAxes and rgdwAxes members contain data.
DIEP_DIRECTION
The cAxes and rglDirection members contain data. The dwFlags member specifies (with DIEFF_CARTESIAN or DIEFF_POLAR) the coordinate system in which the values should be interpreted.
DIEP_DURATION
The dwDuration member contains data.
DIEP_ENVELOPE
The lpEnvelope member points to a DIENVELOPE structure that contains data. To detach any existing envelope from the effect, pass this flag and set the lpEnvelope member to NULL.
DIEP_GAIN
The dwGain member contains data.
DIEP_NODOWNLOAD
Suppress the automatic IDirectInputEffect::Download that is normally performed after the parameters are updated. See Remarks.
DIEP_NORESTART
Suppress the stopping and restarting of the effect to change parameters. See Remarks.
DIEP_SAMPLEPERIOD
The dwSamplePeriod member contains data.
DIEP_START
The effect is to be started (or restarted if it is currently playing) after the parameters are updated. By default, the play state of the effect is not altered.
DIEP_STARTDELAY
The dwStartDelay member contains data.
DIEP_TRIGGERBUTTON
The dwTriggerButton member contains data.
DIEP_TRIGGERREPEATINTERVAL
The dwTriggerRepeatInterval member contains data.
DIEP_TYPESPECIFICPARAMS
The lpvTypeSpecificParams and cbTypeSpecificParams members of the DIEFFECT structure contain the address and size of type-specific data for the effect.

Return Value

If the method succeeds, the return value can be DI_DOWNLOADSKIPPED, DI_EFFECTRESTARTED, DI_OK, DI_TRUNCATED, or DI_TRUNCATEDANDRESTARTED. If the method fails, the return value can be DIERR_NOTINITIALIZED, DIERR_INCOMPLETEEFFECT, DIERR_INPUTLOST, DIERR_INVALIDPARAM, or DIERR_EFFECTPLAYING.

DI_DOWNLOADSKIPPED | The parameters of the effect were successfully updated, but the effect could not be downloaded because the associated device was not acquired in exclusive mode.
DI_EFFECTRESTARTED | The effect was stopped, the parameters were updated, and the effect was restarted.
DI_OK | The operation completed successfully. This value is equal to the S_OK standard Component Object Model (COM) return value.
DI_TRUNCATED | The parameters of the effect were successfully updated, but some of them were beyond the capabilities of the device and were truncated to the nearest supported value.
DI_TRUNCATEDANDRESTARTED | Equal to DI_EFFECTRESTARTED | DI_TRUNCATED.
DIERR_NOTINITIALIZED | The object has not been initialized.
DIERR_INCOMPLETEEFFECT | The effect could not be downloaded because essential information is missing. For example, no axes have been associated with the effect, or no type-specific information has been supplied.
DIERR_INPUTLOST | Access to the input device has been lost. It must be reacquired.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard COM return value.
DIERR_EFFECTPLAYING | The parameters were updated in memory but were not downloaded to the device because the device does not support updating an effect while it is still playing.

Remarks

The dwDynamicParams member of the DIEFFECTINFO structure for the effect specifies which parameters can be dynamically updated while the effect is playing.

The IDirectInputEffect::SetParameters method automatically downloads the effect, but this behavior can be suppressed by setting the DIEP_NODOWNLOAD flag. If automatic download has been suppressed, you can manually download the effect by invoking the IDirectInputEffect::Download method.

If the effect is playing while the parameters are changed, the new parameters take effect as if they were the parameters when the effect started.

For example, suppose a periodic effect with a duration of three seconds is started. After two seconds, the direction of the effect is changed. The effect then continues for one additional second in the new direction. The envelope, phase, amplitude, and other parameters of the effect continue smoothly, as if the direction had not changed.

In the same situation, if after two seconds the duration of the effect were changed to 1.5 seconds, the effect would stop.

Normally, if the driver cannot update the parameters of a playing effect, the driver is permitted to stop the effect, update the parameters, and then restart the effect. Passing the DIEP_NORESTART flag suppresses this behavior. If the driver cannot update the parameters of an effect while it is playing, the error code DIERR_EFFECTPLAYING is returned, and the parameters are not updated.

No more than one of the DIEP_NODOWNLOAD, DIEP_START, and DIEP_NORESTART flags should be set. (It is also valid to pass none of them.)

These three flags control download and playback behavior as follows:

If DIEP_NODOWNLOAD is set, the effect parameters are updated but not downloaded to the device.

If the DIEP_START flag is set, the effect parameters are updated and downloaded to the device, and the effect is started just as if the IDirectInputEffect::Start method had been called with the dwIterations parameter set to 1 and with no flags. (Combining the update with DIEP_START is slightly faster than calling IDirectInputEffect::Start separately, because it requires less information to be transmitted to the device.)

If neither DIEP_NODOWNLOAD nor DIEP_START is set and the effect is not playing, the parameters are updated and downloaded to the device.

If neither DIEP_NODOWNLOAD nor DIEP_START is set and the effect is playing, the parameters are updated if the device supports on-the-fly updating. Otherwise the behavior depends on the state of the DIEP_NORESTART flag. If it is set, the error code DIERR_EFFECTPLAYING is returned. If it is clear, the effect is stopped, the parameters are updated, and the effect is restarted.


IDirectInputEffect::Start Method

Begins playing an effect. If the effect is already playing, it is restarted from the beginning. If the effect has not been downloaded or has been modified since its last download, it is downloaded before being started. This default behavior can be suppressed by passing the DIES_NODOWNLOAD flag.

Syntax

HRESULT Start(

    DWORD dwIterations,
    DWORD dwFlags
);

Parameters

dwIterations
Number of times to play the effect in sequence. The envelope is re-articulated with each iteration.

To play the effect exactly once, pass 1. To play the effect repeatedly until explicitly stopped, pass INFINITE. To play the effect until explicitly stopped without re-articulating the envelope, modify the effect parameters with the IDirectInputEffect::SetParameters method, and change the dwDuration member to INFINITE.
dwFlags
Flags that describe how the effect should be played by the device. The value can be 0 or one or more of the following values:
DIES_SOLO
All other effects on the device should be stopped before the specified effect is played. If this flag is omitted, the effect is mixed with existing effects already started on the device.
DIES_NODOWNLOAD
Do not automatically download the effect.

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INCOMPLETEEFFECT | The effect could not be downloaded because essential information is missing. For example, no axes have been associated with the effect, or no type-specific information has been supplied.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTEXCLUSIVEACQUIRED | The operation cannot be performed unless the device is acquired in DISCL_EXCLUSIVE mode.
DIERR_NOTINITIALIZED | The object has not been initialized.
DIERR_UNSUPPORTED | The function called is not supported at this time. This value is equal to the E_NOTIMPL standard COM return value.

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.

Not all devices support multiple iterations.


IDirectInputEffect::Stop Method

Stops playing an effect.

Syntax

HRESULT Stop(VOID);

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_NOTEXCLUSIVEACQUIRED | The operation cannot be performed unless the device is acquired in DISCL_EXCLUSIVE mode.
DIERR_NOTINITIALIZED | The object has not been initialized.

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.


IDirectInputEffect::Unload Method

Removes the effect from the device. If the effect is playing, it is automatically stopped before it is unloaded.

Syntax

HRESULT Unload(VOID);

Return Value

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INPUTLOST | Access to the input device has been lost. It must be reacquired.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard Component Object Model (COM) return value.
DIERR_NOTEXCLUSIVEACQUIRED | The operation cannot be performed unless the device is acquired in DISCL_EXCLUSIVE mode.
DIERR_NOTINITIALIZED | The object has not been initialized.


Callback Functions
Microsoft DirectX 9.0 SDK Update (October 2004)

Callback Functions

This section describes the seven functions that are prototype callback functions for use with various enumeration methods. Applications can declare one of these callback functions under any name and define it in any way, but the parameter and return types must be the same as in the prototype.

Functions

  • DIConfigureDevicesCallback
  • DIEnumCreatedEffectObjectsCallback
  • DIEnumDeviceObjectsCallback
  • DIEnumDevicesBySemanticsCallback
  • DIEnumDevicesCallback
  • DIEnumEffectsCallback
  • DIEnumEffectsInFileCallback


DIConfigureDevicesCallback Function

Application-defined callback function that is called each time the property sheet image is refreshed. This function needs to be supplied only when the application is displaying the property sheet within its own window.

Syntax

BOOL CALLBACK DIConfigureDevicesCallback(

    IUnknown *lpDDSTarget,
    LPVOID pvRef
);

Parameters

lpDDSTarget
Pointer to the IUnknown interface of the surface in the lpUnkDDSTarget member of the DICONFIGUREDEVICESPARAMS structure that was passed to IDirectInput8::ConfigureDevices.
pvRef
Application-defined value passed to IDirectInput8::ConfigureDevices as the pvRef parameter.

Return Value

Can return TRUE or FALSE. Microsoft DirectInput does not use the return value.

Function Information

Header | dinput.h
Import library | None
Minimum operating systems | Windows 98


DIEnumCreatedEffectObjectsCallback Function

Application-defined callback function that receives DirectInputDevice effects as a result of a call to the IDirectInputDevice8::EnumCreatedEffectObjects method.

Syntax

BOOL CALLBACK DIEnumCreatedEffectObjectsCallback(

    LPDIRECTINPUTEFFECT peff,
    LPVOID pvRef
);

Parameters

peff
The address of an effect object that has been created.
pvRef
The application-defined value passed to IDirectInputDevice8::EnumCreatedEffectObjects as the pvRef parameter.

Return Value

Returns DIENUM_CONTINUE to continue the enumeration or DIENUM_STOP to stop the enumeration.

Function Information

Header | dinput.h
Import library | None
Minimum operating systems | Windows 98


DIEnumDeviceObjectsCallback Function

Application-defined callback function that receives DirectInputDevice objects as a result of a call to the IDirectInputDevice8::EnumObjects method.

Syntax

BOOL CALLBACK DIEnumDeviceObjectsCallback(

    LPCDIDEVICEOBJECTINSTANCE lpddoi,
    LPVOID pvRef
);

Parameters

lpddoi
DIDEVICEOBJECTINSTANCE structure that describes the object being enumerated.
pvRef
The application-defined value passed to IDirectInputDevice8::EnumObjects as the pvRef parameter.

Return Value

Returns DIENUM_CONTINUE to continue the enumeration or DIENUM_STOP to stop the enumeration.

Function Information

Header | dinput.h
Import library | None
Minimum operating systems | Windows 98


DIEnumDevicesBySemanticsCallback Function

Application-defined callback function that receives Microsoft DirectInput devices as a result of a call to the IDirectInput8::EnumDevicesBySemantics method.

Syntax

BOOL CALLBACK DIEnumDevicesBySemanticsCallback(

    LPCDIDEVICEINSTANCE lpddi,
    LPDIRECTINPUTDEVICE8 lpdid,
    DWORD dwFlags,
    DWORD dwRemaining,
    LPVOID pvRef
);

Parameters

lpddi
Address of a DIDEVICEINSTANCE structure that describes the device instance.
lpdid
Pointer to the IDirectInputDevice8 interface for the device.
dwFlags
Flags that provide information about why the device is being enumerated. This can be a combination of action-mapping flags and one usage flag. At least one action-mapping flag is always present.

The DIEDBS_MAPPEDPRI1 and DIEDBS_MAPPEDPRI2 action-mapping flags and the DIEDBS_RECENTDEVICE and DIEDBS_NEWDEVICE usage flags are defined below.

DIEDBS_MAPPEDPRI1
The device is being enumerated because priority 1 actions can be mapped to the device.
DIEDBS_MAPPEDPRI2
The device is being enumerated because priority 2 actions can be mapped to the device.
DIEDBS_RECENTDEVICE
The device is being enumerated because the commands described by the action-mapping flags were recently used.
DIEDBS_NEWDEVICE
The device is being enumerated because the device was installed recently. Devices described by this flag have not been used with this game before.
dwRemaining
Number of devices, after this one, remaining to be enumerated.
pvRef
The application-defined value passed to IDirectInput8::EnumDevicesBySemantics as the pvRef parameter.

Return Value

Returns DIENUM_CONTINUE to continue the enumeration or DIENUM_STOP to stop the enumeration.

Remarks

If a single hardware device can function as more than one DirectInput device type, it is enumerated as each device type that it supports. For example, a keyboard with a built-in mouse is enumerated twice: once as a keyboard and once as a mouse. The product globally unique identifier (GUID) is the same for each device, however.

Function Information

Header | dinput.h
Import library | None
Minimum operating systems | Windows 98

See Also

DIEnumDevicesCallback


DIEnumDevicesCallback Function

Application-defined callback function that receives Microsoft DirectInput devices as a result of a call to the IDirectInput8::EnumDevices method.

Syntax

BOOL CALLBACK DIEnumDevicesCallback(

    LPCDIDEVICEINSTANCE lpddi,
    LPVOID pvRef
);

Parameters

lpddi
Address of a DIDEVICEINSTANCE structure that describes the device instance.
pvRef
The application-defined value passed to IDirectInput8::EnumDevices or IDirectInput8::EnumDevicesBySemantics as the pvRef parameter.

Return Value

Returns DIENUM_CONTINUE to continue the enumeration or DIENUM_STOP to stop the enumeration.

Remarks

If a single hardware device can function as more than one DirectInput device type, it is enumerated as each device type that it supports. For example, a keyboard with a built-in mouse is enumerated twice: once as a keyboard and once as a mouse. The product globally unique identifier (GUID) is the same for each device, however.

Function Information

Header | dinput.h
Import library | None
Minimum operating systems | Windows 98

See Also

DIEnumDevicesBySemanticsCallback


DIEnumEffectsCallback Function

Application-defined callback function used with the IDirectInputDevice8::EnumEffects method.

Syntax

BOOL CALLBACK DIEnumEffectsCallback(

    LPCDIEFFECTINFO pdei,
    LPVOID pvRef
);

Parameters

pdei
DIEFFECTINFO structure that describes the enumerated effect.
pvRef
The application-defined value passed to IDirectInputDevice8::EnumEffects as the pvRef parameter.

Return Value

Returns DIENUM_CONTINUE to continue the enumeration, or DIENUM_STOP to stop it.

Function Information

Header | dinput.h
Import library | None
Minimum operating systems | Windows 98


DIEnumEffectsInFileCallback Function

Application-defined callback function used with the IDirectInputDevice8::EnumEffectsInFile method.

Syntax

BOOL CALLBACK DIEnumEffectsInFileCallback(

    LPCDIFILEEFFECT lpDiFileEf,
    LPVOID pvRef
);

Parameters

lpDiFileEf
DIFILEEFFECT structure that describes the enumerated effect.
pvRef
The application-defined value passed to IDirectInputDevice8::EnumEffectsInFile as the pvRef parameter.

Return Value

Returns DIENUM_CONTINUE to continue the enumeration, or DIENUM_STOP to stop it.

Function Information

Header | dinput.h
Import library | None
Minimum operating systems | Windows 98


Functions
Microsoft DirectX 9.0 SDK Update (October 2004)

Functions

This section is a reference for Microsoft DirectInput functions other than COM interface methods and callback functions.

The following function falls into this category:

Functions

  • DirectInput8Create
  • ShowJoyCPL


DirectInput8Create Function

Creates a Microsoft DirectInput object and returns an IDirectInput8 or later interface.

Syntax

HRESULT WINAPI DirectInput8Create(

    HINSTANCE hinst,
    DWORD dwVersion,
    REFIID riidltf,
    LPVOID *ppvOut,
    LPUNKNOWN punkOuter
);

Parameters

hinst
Instance handle to the application or dynamic-link library (DLL) that is creating the DirectInput object. DirectInput uses this value to determine whether the application or DLL has been certified and to establish any special behaviors that might be necessary for backward compatibility.

It is an error for a DLL to pass the handle to the parent application. For example, an Microsoft ActiveX control embedded in a Web page that uses DirectInput must pass its own instance handle, and not the handle to the browser. This ensures that DirectInput recognizes the control and can enable any special behaviors that might be necessary.

dwVersion
Version number of DirectInput for which the application is designed. This value is normally DIRECTINPUT_VERSION. If the application defines DIRECTINPUT_VERSION before including Dinput.h, the value must be greater than 0x0800. For earlier versions, use DirectInputCreateEx, which is in Dinput.lib.
riidltf
Unique identifier of the desired interface. This value is IID_IDirectInput8A or IID_IDirectInput8W. Passing the IID_IDirectInput8 define selects the ANSI or Unicode version of the interface, depending on whether UNICODE is defined during compilation.
ppvOut
Address of a pointer to a variable to receive the interface pointer if the call succeeds.
punkOuter
Pointer to the address of the controlling object's IUnknown interface for Component Object Model (COM) aggregation, or NULL if the interface is not aggregated. Most calling applications pass NULL. If aggregation is requested, the object returned in ppvOut is a pointer to IUnknown, as required by COM aggregation.

Return Value

If the function succeeds, the return value is DI_OK.

If the function fails, the return value can be one of the following error values:

DIERR_BETADIRECTINPUTVERSION | The application was written for an unsupported prerelease version of DirectInput.
DIERR_INVALIDPARAM | An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard COM return value.
DIERR_OLDDIRECTINPUTVERSION | The application requires a newer version of DirectInput.
DIERR_OUTOFMEMORY | The DirectInput subsystem couldn't allocate sufficient memory to complete the call. This value is equal to the E_OUTOFMEMORY standard COM return value.

Remarks

The DirectInput object created by this function is implemented in Dinput8.dll. Versions of interfaces earlier than Microsoft DirectX 8.0 cannot be obtained in this implementation.

To create a DirectX 8.x interface with the DirectX 9.0 software development kit (SDK) without using CoCreateInstance World Wide Web link:

  1. Set "#define DIRECTINPUT_VERSION 0x0800" before the include statement for Dinput8.h.
  2. Call DirectInput8Create instead of DirectInputCreateEx.
  3. Link to the Dinput8.lib library instead of Dinput.lib.

To create a DirectX 8.x interface with the DirectX 8.x SDK without using CoCreateInstance:

  1. Call DirectInput8Create instead of DirectInputCreateEx.
  2. Link to the Dinput8.lib library instead of Dinput.lib.

To create a DirectX 7.0 interface from the DirectX 8.x or DirectX 9.0 SDK without using CoCreateInstance:

  1. Set "#define DIRECTINPUT_VERSION 0x0700" before the include statement for dinput.h.
  2. Call DirectInputCreateEx instead of DirectInput8Create.
  3. Link to the Dinput.lib library instead of Dinput8.lib.

To create a DirectX 7.0 interface from the DirectX 8.x or DirectX 9.0 SDK using CoCreateInstance:

  1. Call CoInitializeEx.
  2. Call CoCreateInstance using CLISID_DirectInput.
  3. Use IDirectInput7::Initialize to initialize the DirectInput object.

To create a DirectX 8.x or DirectX 9.0 interface from the DirectX 8.x or DirectX 9.0 SDK using CoCreateInstance:

  1. Call CoInitializeEx World Wide Web link.
  2. Call CoCreateInstance using CLISID_DirectInput8.
  3. Use IDirectInput8::Initialize to initialize the DirectInput object.

Calling the function with punkOuter = NULL is equivalent to creating the object through CoCreateInstance( &CLSID_DirectInput8, punkOuter, CLSCTX_INPROC_SERVER, &IID_IDirectInput8W, lplpDirectInput), then initializing it with IDirectInput8::Initialize.

Calling the function with punkOuter != NULL is equivalent to creating the object through CoCreateInstance( &CLSID_DirectInput8, punkOuter, CLSCTX_INPROC_SERVER, &IID_IUnknown, lplpDirectInput). The aggregated object must be initialized manually.

Function Information

Stock Implementation | dinput8.dll
Custom Implementation | No
Header | dinput.h
Import library | dinput8.lib
Minimum operating systems | Windows 98


ShowJoyCPL Function

Invokes the joystick control panel directly, using the passed window handle as the parent of the dialog box.

Syntax

VOID WINAPI ShowJoyCPL(

    HWND hWnd
);

Parameters

hWnd
Window handle of the parent dialog box.

Return Value

None.

Remarks

It is recommended that applications use IDirectInputDevice8::RunControlPanel instead of ShowJoyCPL.

The following typedef is provided to allow declaration and casting of an appropriately typed variable.

typedef void (WINAPI* LPFNSHOWJOYCPL)( HWND hWnd );

Example

ShowJoyCPL can be called using the function pointer returned by GetProcAddress, where hCPL is an HMODULE returned by LoadLibrary.

HMODULE hCPL;
LPFNSHOWJOYCPL pShowJoyCPL;
.
.
.
hCPL = LoadLibrary(TEXT("joy.cpl"));
pShowJoyCPL  = (LPFNSHOWJOYCPL)GetProcAddress(hCPL, TEXT("ShowJoyCPL"));

pShowJoyCPL(NULL);  //Invoke Joystick Control Panel

Function Information

Stock Implementation | joy.cpl
Custom Implementation | No
Header | dinput.h
Import library | None
Minimum operating systems | Windows XP SP1


Macros
Microsoft DirectX 9.0 SDK Update (October 2004)

Macros

This section describes the macros used in Microsoft DirectInput.

Macros

  • DIDFT_GETINSTANCE
  • DIDFT_GETTYPE
  • DIDFT_MAKEINSTANCE
  • DIEFT_GETTYPE
  • DIMAKEUSAGEDWORD
  • DISEQUENCE_COMPARE
  • GET_DIDEVICE_SUBTYPE
  • GET_DIDEVICE_TYPE

Dinput.h also defines macros for C calls to all the methods of the IDirectInput8 and IDirectInputDevice8 interfaces. These macros eliminate the need for pointers to method tables. For example, the following is a C call to the IDirectInputDevice8::Release method.

lpdid->lpVtbl->Release(lpdid));

The equivalent macro call looks like this.

idirectinputdevice9_Release(lpdid);

All these macros take the same parameters as the method calls themselves.


DIDFT_GETINSTANCE Macro

The DIDFT_GETINSTANCE macro extracts the object instance number code from a data format type.

Syntax

#define DIDFT_GETINSTANCE(n) LOWORD((n) >> 8)

Parameters

n
Microsoft DirectInput data format type. The possible values for this parameter are identical to those found in the dwType member of the DIOBJECTDATAFORMAT structure.

Macro Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

DIDFT_MAKEINSTANCE, DIDFT_GETTYPE


DIDFT_GETTYPE Macro

The DIDFT_GETTYPE macro extracts the object type code from a data format type.

Syntax

#define DIDFT_GETTYPE(n)  LOBYTE(n)

Parameters

n
Microsoft DirectInput data format type. The possible values for this parameter are identical to those found in the dwType member of the DIOBJECTDATAFORMAT structure.

Macro Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

DIDFT_GETINSTANCE


DIDFT_MAKEINSTANCE Macro

The DIDFT_MAKEINSTANCE macro creates an instance identifier of a device object for packing in the dwType member of the DIOBJECTDATAFORMAT structure.

Syntax

#define DIDFT_MAKEINSTANCE(n) ((WORD)(n) << 8)

Parameters

n
Instance of the object; for example, 1 for button 1 of a mouse.

Macro Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

DIDFT_GETINSTANCE


DIEFT_GETTYPE Macro

The DIEFT_GETTYPE macro extracts the effect type code from an effect format type.

Syntax

#define DIDFT_GETTYPE(n)  LOBYTE(n)

Parameters

n
Microsoft DirectInput effect format type. The possible values for this parameter are identical to those found in the dwEffType member of the DIEFFECTINFO structure.

Return Value

Macro Information

Header | dinput.h
Minimum operating systems | Windows 98


DIMAKEUSAGEDWORD Macro

The DIMAKEUSAGEDWORD macro combines the usage page and usage codes for a device object representing a Human Interface Device (HID), for passing to the IDirectInputDevice8::GetObjectInfo method.

Syntax

#define DIMAKEUSAGEDWORD(UsagePage, Usage) \
        ((DWORD)MAKELONG(Usage, UsagePage))

Parameters

UsagePage
Usage page of the device object.
Usage
Usage of the device object.

Macro Information

Header | dinput.h
Minimum operating systems | Windows 98


DISEQUENCE_COMPARE Macro

The DISEQUENCE_COMPARE macro compares two Microsoft DirectInput sequence numbers, compensating for wraparound.

Syntax

#define DISEQUENCE_COMPARE(dwSequence1, cmp, dwSequence2) \
                ((int)((dwSequence1) - (dwSequence2)) cmp 0)

Parameters

dwSequence1
First sequence number to compare.
cmp
One of the following comparison operators: ==, !=, <, >, <=, or >=.
dwSequence2
Second sequence number to compare.

Return Value

Returns a nonzero value if the result of the comparison specified by the cmp parameter is true, or zero otherwise.

Remarks

The following example checks whether the dwSequence1 parameter value precedes the dwSequence2 parameter value chronologically.

BOOL Sooner = (DISEQUENCE_COMPARE(dwSequence1, <, dwSequence2));

Macro Information

Header | dinput.h
Minimum operating systems | Windows 98


GET_DIDEVICE_SUBTYPE Macro

The GET_DIDEVICE_SUBTYPE macro extracts the device subtype code from a device type description code.

Syntax

#define GET_DIDEVICE_SUBTYPE(dwDevType)  HIBYTE(dwDevType)

Parameters

dwDevType
Microsoft DirectInput device type description code. The possible values for this parameter are identical to those found in the dwDevType member of the DIDEVICEINSTANCE structure.

Remarks

The interpretation of the subtype code depends on the primary type.

Macro Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

GET_DIDEVICE_TYPE, DIDEVICEINSTANCE


GET_DIDEVICE_TYPE Macro

The GET_DIDEVICE_TYPE macro extracts the device primary type code from a device type description code.

Syntax

#define GET_DIDEVICE_TYPE(dwDevType)  LOBYTE(dwDevType)

Parameters

dwDevType
Microsoft DirectInput device type description code. Possible values for this parameter are identical to those found in the dwDevType member of the DIDEVICEINSTANCE structure.

Macro Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

GET_DIDEVICE_SUBTYPE, DIDEVICEINSTANCE


Structures
Microsoft DirectX 9.0 SDK Update (October 2004)

Structures

This section contains information about the structures used with Microsoft DirectInput.

Structures

  • CPOINT
  • DIACTION
  • DIACTIONFORMAT
  • DICOLORSET
  • DICONDITION
  • DICONFIGUREDEVICESPARAMS
  • DICONSTANTFORCE
  • DICUSTOMFORCE
  • DIDATAFORMAT
  • DIDEVCAPS
  • DIDEVICEIMAGEINFO
  • DIDEVICEIMAGEINFOHEADER
  • DIDEVICEINSTANCE
  • DIDEVICEOBJECTDATA
  • DIDEVICEOBJECTINSTANCE
  • DIEFFECT
  • DIEFFECTINFO
  • DIEFFESCAPE
  • DIENVELOPE
  • DIFILEEFFECT
  • DIJOYSTATE
  • DIJOYSTATE2
  • DIMOUSESTATE
  • DIMOUSESTATE2
  • DIOBJECTDATAFORMAT
  • DIPERIODIC
  • DIPROPCPOINTS
  • DIPROPDWORD
  • DIPROPGUIDANDPATH
  • DIPROPHEADER
  • DIPROPPOINTER
  • DIPROPRANGE
  • DIPROPSTRING
  • DIRAMPFORCE

Note The memory for all Microsoft DirectX structures must be initialized to 0 before use. In addition, all structures that contain a dwSize member should set the member to the size of the structure, in bytes, before use. The following example performs these tasks on a common structure, DIDEVCAPS:
DIDEVCAPS didevcaps; // Can't use this yet

ZeroMemory(&didevcaps, sizeof(didevcaps));
didevcaps.dwSize = sizeof(didevcaps);

// Now the structure Can be used.


CPOINT Structure

Describes a calibration point. An array of CPOINT structures is contained by a DIPROPCPOINTS structure.

Syntax

typedef struct _CPOINT {
    LONG lP;
    DWORD dwLog;
} CPOINT, *PCPOINT;

Members

lP
Raw data
dwLog
Scaling value to be associated with the lP number. The percentage of the maximum value multiplied by 10000.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

Using CPOINTs


DIACTION Structure

Describes a mapping of one game action to one device semantic. An array of DIACTION structures is contained by a DIACTIONFORMAT structure.

Syntax

typedef struct _DIACTION {
    UINT_PTR    uAppData;
    DWORD       dwSemantic;
    DWORD       dwFlags;
    union {
        LPCTSTR lptszActionName;
        UINT    uResIdString;
    };
    GUID        guidInstance;
    DWORD       dwObjID;
    DWORD       dwHow;
} DIACTION, *LPDIACTION;

typedef const DIACTION *LPCDIACTION;

Members

uAppData
Address of an application-defined UINT value to be returned to the application by IDirectInputDevice8::GetDeviceData when the state of the control associated with the action changes. This value is returned in the uAppData member of the DIDEVICEOBJECTDATA structure. It is typically an identifier for the application-specific action associated with the device object, but can also be a function pointer.
dwSemantic
For a joystick, a predefined action mapping constant for this application genre representing a virtual control or a constant for a control not defined in the genre. For a keyboard, mouse, or Microsoft DirectPlay voice device, a constant that represents a particular device object. See Action Mapping Constants.
dwFlags
Flags used to request specific attributes or processing. Can be zero or one or more of the following values.
DIA_APPFIXED
The action cannot be remapped by Microsoft DirectInput.
DIA_APPMAPPED
The dwObjID member is valid, and IDirectInputDevice8::BuildActionMap will not override the application-defined mapping.
DIA_APPNOMAP
This action is not to be mapped.
DIA_FORCEFEEDBACK
The action must be mapped to an actuator or trigger.
DIA_NORANGE
The default range is not to be set for this action. This flag can be set only for absolute axis actions.
lptszActionName
Application-defined name of the action. This string is displayed by the device property sheet when IDirectInput8::ConfigureDevices is called.
uResIdString
Resource identifier for the string for this action. The module instance for this resource is specified in the hInstString member of the DIACTIONFORMAT structure that contains this structure.
guidInstance
Device instance globally unique identifier (GUID) if a specific device is requested. Otherwise GUID_NULL.
dwObjID
Control identifier. Use the DIDFT_GETINSTANCE and DIDFT_GETTYPE macros to retrieve the instance and type from this value.
dwHow
When the structure is returned by IDirectInputDevice8::BuildActionMap, this member receives a value to indicate the mapping mechanism used by DirectInput to configure the action. This memeber is ignored when the action map is passed to IDirectInputDevice8::SetActionMap. The following values are defined.
DIAH_APPREQUESTED
The mapping was configured by the application, which specified the device (guidInstance) and device object (dwObjID) when calling IDirectInputDevice8::BuildActionMap.
DIAH_DEFAULT
The mapping was determined by DirectInput in the absence of other mapping information.
DIAH_ERROR
An error occurred. The action cannot be matched to a control on the device. The action will be ignored when the action map is set.
DIAH_HWAPP
The mapping was specified by the hardware manufacturer for this game.
DIAH_HWDEFAULT
The mapping was specified by the hardware manufacturer for this genre.
DIAH_UNMAPPED
No suitable device object was found.
DIAH_USERCONFIG
The mapping was configured by the user.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

IDirectInput8::EnumDevicesBySemantics, IDirectInputDevice8::SetActionMap, IDirectInput8::ConfigureDevices, IDirectInputDevice8::BuildActionMap, Action Mapping


DIACTIONFORMAT Structure

Contains information about the calling application and acts as a container for an array of DIACTION structures that define action-to-control mappings for a genre.

Syntax

typedef struct {
    DWORD dwSize;
    DWORD dwActionSize;
    DWORD dwDataSize;
    DWORD dwNumActions;
    LPDIACTION rgoAction;
    GUID guidActionMap;
    DWORD dwGenre;
    DWORD dwBufferSize;
    LONG lAxisMin;
    LONG lAxisMax;
    HINSTANCE hInstString;
    FILETIME ftTimeStamp;
    DWORD dwCRC;
    TCHAR tszActionMap[MAX_PATH];
} DIACTIONFORMAT;

Members

dwSize
DWORD value that specifies the size of the DIACTIONFORMAT structure, in bytes.
dwActionSize
DWORD value that specifies the size of the DIACTION structure, in bytes.
dwDataSize
DWORD value that specifies the size of the device data to be returned by the device for immediate device data, in bytes. This member should be dwNumActions multiplied by four.
dwNumActions
DWORD value that specifies the number of elements in the rgoAction array.
rgoAction
Address of an array of DIACTION structures, each of which describes how an action maps to a virtual control or device object, and how the mapping information should be displayed to the user.
guidActionMap
globally unique identifier (GUID) that identifies the action map. Device manufacturers can use this value to tune mappings for a specific title.
dwGenre
DWORD value that specifies the genre of the application. For possible values, see Action Mapping Constants.
dwBufferSize
DWORD value that specifies the number of input data packets in the buffer for each device to which this action map is to be applied. The buffer size must be set to a value greater than zero in order to retrieve data by using IDirectInputDevice8::GetDeviceData. Applications that set this member to the desired buffer size before calling IDirectInputDevice8::SetActionMap do not need to set the DIPROP_BUFFERSIZE property by using IDirectInputDevice8::SetProperty.
lAxisMin
Minimum value for the range of scaled data to be returned for all axes. This value is ignored for a specific action axis if the DIA_NORANGE flag is set in DIACTION.dwFlags.

This value is valid only for axis actions and should be set to zero for all other actions. It is used as the DIPROPRANGE.lMin value to set the range property on an absolute axis when the action map is applied using IDirectInputDevice8::SetActionMap.

lAxisMax
Maximum value for the range of scaled data to be returned for all axes. This value is ignored for a specific action axis if the DIA_NORANGE flag is set in DIACTION.dwFlags.

This value is valid only for axis actions and should be set to zero for all other actions. It is used as the DIPROPRANGE.lMax value to set the range property on an absolute axis when the action map is applied using IDirectInputDevice8::SetActionMap.

hInstString
Handle of the module containing string resources for action names, as specified in the uResIdString member of the DIACTION structure for each action. Can be zero if action names are specified in the lptszActionName member of the DIACTION structure for each action.
ftTimeStamp
FILETIME structure that receives the time at which this action map was last written to disk. See Remarks.
dwCRC
Cyclic redundancy check for this map. Used internally by Microsoft DirectInput to determine when a set of mappings should be saved to disk.
tszActionMap
Null-terminated string, of maximum length MAX_PATH, that specifies the friendly name for this action map. This string appears in the drop-down list box in the default property sheet.

Remarks

The ftTimeStamp member can contain special values that apply to new and unused devices. New devices have never been enumerated for this application and have never had an action map applied to them. Unused devices have been enumerated for the application before but have never had an action map applied. New devices always have DIAFTS_NEWDEVICELOW and DIAFTS_NEWDEVICEHIGH in the low and high DWORDs respectively of the FILETIME structure. Unused devices have DIAFTS_UNUSEDDEVICELOW and DIAFTS_UNUSEDDEVICEHIGH in these positions.

Applications should not use ftTimeStamp to check for new devices. Instead, they should look for the DIEDBS_RECENTDEVICE and DIEDBS_NEWDEVICE flags in the enumeration callback. For more information, see DIEnumDevicesBySemanticsCallback.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

IDirectInput8::EnumDevicesBySemantics, IDirectInputDevice8::SetActionMap, IDirectInput8::ConfigureDevices, IDirectInputDevice8::BuildActionMap, Action Mapping


DICOLORSET Structure

Describes a set of colors used to draw the device configuration user interface. It is part of the DICONFIGUREDEVICESPARAMS structure.

Syntax

typedef struct _DICOLORSET {
    DWORD    dwSize
    D3DCOLOR cTextFore;
    D3DCOLOR cTextHighlight;
    D3DCOLOR cCalloutLine;
    D3DCOLOR cCalloutHighlight;
    D3DCOLOR cBorder;
    D3DCOLOR cControlFill;
    D3DCOLOR cHighlightFill;
    D3DCOLOR cAreaFill;
} DICOLORSET, *LPDICOLORSET;

typedef const DICOLORSET *LPCDICOLORSET;

Members

dwSize
Size of this structure, in bytes.
cTextFore
Foreground text color.
cTextHighlight
Foreground color for highlighted text.
cCalloutLine
Color used to display callout lines.
cCalloutHighlight
Color used to display callout lines.
cBorder
Border color, used to display lines around controls such as tabs and buttons.
cControlFill
Fill color for controls such as tabs and buttons.
cHighlightFill
Fill color for highlighted controls.
cAreaFill
Fill color for areas outside controls such as tabs and buttons.

Remarks

Text background color is always transparent.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

D3DCOLOR


DICONDITION Structure

Contains type-specific information for effects that are marked as DIEFT_CONDITION.

A pointer to an array of DICONDITION structures for an effect is passed in the lpvTypeSpecificParams member of the DIEFFECT structure. The number of elements in the array must be either one, or equal to the number of axes associated with the effect.

Syntax

typedef struct DICONDITION {
    LONG	 lOffset;
    LONG	 lPositiveCoefficient;
    LONG	 lNegativeCoefficient;
    DWORD	 dwPositiveSaturation;
    DWORD	 dwNegativeSaturation;
    LONG	 lDeadBand;
} DICONDITION, *LPDICONDITION;

typedef const DICONDITION *LPCDICONDITION;

Members

lOffset
Offset for the condition, in the range from –10,000 through 10,000.
lPositiveCoefficient
Coefficient constant on the positive side of the offset, in the range from –10,000 through 10,000.
lNegativeCoefficient
Coefficient constant on the negative side of the offset, in the range from –10,000 through 10,000. If the device does not support separate positive and negative coefficients, the value of lNegativeCoefficient is ignored, and the value of lPositiveCoefficient is used as both the positive and negative coefficients.
dwPositiveSaturation

Maximum force output on the positive side of the offset, in the range from 0 through 10,000.

If the device does not support force saturation, the value of this member is ignored.

dwNegativeSaturation

Maximum force output on the negative side of the offset, in the range from 0 through 10,000.

If the device does not support force saturation, the value of this member is ignored.

If the device does not support separate positive and negative saturation, the value of dwNegativeSaturation is ignored, and the value of dwPositiveSaturation is used as both the positive and negative saturation.

lDeadBand
Region around lOffset in which the condition is not active, in the range from 0 through 10,000. In other words, the condition is not active between lOffset minus lDeadBand and lOffset plus lDeadBand.

Remarks

Different types of conditions interpret the parameters differently, but the basic idea is that force resulting from a condition is equal to A(q - q0) where A is a scaling coefficient, q is some metric, and q0 is the neutral value for that metric.

The preceding simplified formula must be adjusted if a nonzero deadband is provided. If the metric is less than lOffset - lDeadBand, the resulting force is given by the following formula:

force = lNegativeCoefficient * ( q - ( lOffset - lDeadBand))

Similarly, if the metric is greater than lOffset + lDeadBand, the resulting force is given by the following formula:

force = lPositiveCoefficient * ( q - ( lOffset + lDeadBand))

A spring condition uses axis position as the metric.

A damper condition uses axis velocity as the metric.

An inertia condition uses axis acceleration as the metric.

If the number of DICONDITION structures in the array is equal to the number of axes for the effect, the first structure applies to the first axis, the second applies to the second axis, and so on. For example, a two-axis spring condition with lOffset set to 0 in both DICONDITION structures would have the same effect as the joystick self-centering spring. When a condition is defined for each axis in this way, the effect must not be rotated.

If there is a single DICONDITION structure for an effect with more than one axis, the direction along which the parameters of the DICONDITION structure are in effect is determined by the direction parameters passed in the rglDirection field of the DIEFFECT structure. For example, a friction condition rotated 45 degrees (in polar coordinates) would resist joystick motion in the northeast-southwest direction but would have no effect on joystick motion in the northwest-southeast direction.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98


DICONFIGUREDEVICESPARAMS Structure

Contains information for the device configuration property sheet. It is used by the IDirectInput8::ConfigureDevices method.

Syntax

typedef struct _DICONFIGUREDEVICESPARAMS {
    DWORD dwSize;
    DWORD dwcUsers;
    LPTSTR lptszUserNames;
    DWORD dwcFormats;
    LPDIACTIONFORMAT lprgFormats;
    HWND hwnd;
    DICOLORSET dics;
    IUnknown *lpUnkDDSTarget;
} DICONFIGUREDEVICESPARAMS, *LPDICONFIGUREDEVICESPARAMS;

Members

dwSize
Size of this structure, in bytes.
dwcUsers
Count of user names in the buffer at lptszUserNames. If lptszUserNames is NULL (to indicate that default user names should be used), the value in this member is ignored. If the dwcUsers value exceeds the number of entries actually in the buffer, the method fails, returning DIERR_INVALIDPARAM.
lptszUserNames
Pointer to a buffer containing a series of null-terminated name strings, the final element being designated by a double-null terminator. The lptszUserNames parameter can be set to NULL to instruct the use of default names. If the application passes more names than the dwcUsers count indicates, only the names within the count are used. If an application specifies names that are different from the names currently assigned to devices, ownership is revoked for all devices, a default name is created for the mismatched name, and the interface shows (No User) for all devices.
dwcFormats
Count of structures in the array at lprgFormats.
lprgFormats
Pointer to an array of DIACTIONFORMAT structures that contains action-mapping information for each genre used by the game. On input, this array contains action-to-control mappings and strings to display as callouts for each mapping. The configuration interface displays the genres in its drop-down list in the same order as in the array.
hwnd
Handle to the top-level window of the calling application. The member is needed only for applications that run in windowed mode and is otherwise ignored.
dics
DICOLORSET structure that describes the color scheme to apply to the configuration user interface. Passing a zero-initialized DICOLORSET structure causes the default color scheme to be used.
lpUnkDDSTarget
Pointer to the IUnknown interface for a Microsoft DirectDraw or Microsoft Direct3D target surface object that will be filled to contain an image of the configuration user interface. The image represents the current state of the user interface at the time that the DIEnumDevicesBySemanticsCallback function is invoked. The target surface will retain any alpha information passed as part of the DICOLORSET structure above, and also any alpha information encoded into the device image by the hardware manufacturer. The target surface object referred to by the IUnknown interface must support either IDirect3DSurface8, IDirectDrawSurface7 or IDirectDrawSurface4. The IDirect3DSurface9 interface is not supported. For more information, see IDirectInput8::ConfigureDevices. Full-screen applications using DirectDraw must have target surfaces created using the DDSCAPS_SYSTEMEMORY flag.

Applications that are not using DirectDraw and applications that are using DirectDraw but are windowed rather than using the full screen may pass NULL in this parameter. This will cause Microsoft DirectInput to use the Microsoft Windows Windows Graphics Device Interface (GDI) functions to draw the configuration user interface image. Passing NULL when using IDirect3DSurface9 surfaces will fail. For more information, see Remarks in IDirectInput8::ConfigureDevices.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98


DICONSTANTFORCE Structure

Contains type-specific information for effects that are marked as DIEFT_CONSTANTFORCE.

The structure describes a constant force effect.

A pointer to a single DICONSTANTFORCE structure for an effect is passed in the lpvTypeSpecificParams member of the DIEFFECT structure.

Syntax

typedef struct DICONSTANTFORCE {
    LONG lMagnitude;
} DICONSTANTFORCE, *LPDICONSTANTFORCE;

typedef const DICONSTANTFORCE *LPCDICONSTANTFORCE;

Members

lMagnitude
The magnitude of the effect, in the range from –10,000 through 10,000. If an envelope is applied to this effect, the value represents the magnitude of the sustain. If no envelope is applied, the value represents the amplitude of the entire effect.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98


DICUSTOMFORCE Structure

Contains type-specific information for effects that are marked as DIEFT_CUSTOMFORCE.

The structure describes a custom or user-defined force.

A pointer to a DICUSTOMFORCE structure for an effect is passed in the lpvTypeSpecificParams member of the DIEFFECT structure.

Syntax

typedef struct DICUSTOMFORCE {
    DWORD  cChannels;
    DWORD  dwSamplePeriod;
    DWORD  cSamples;
    LPLONG rglForceData;
} DICUSTOMFORCE, *LPDICUSTOMFORCE;

typedef const DICUSTOMFORCE *LPCDICUSTOMFORCE;

Members

cChannels
Number of channels (axes) affected by this force.

The first channel is applied to the first axis associated with the effect, the second to the second, and so on. If there are fewer channels than axes, nothing is associated with the extra axes.

If there is only a single channel, the effect is rotated in the direction specified by the rglDirection member of the DIEFFECT structure. If there is more than one channel, rotation is not allowed.

Not all devices support rotation of custom effects.

dwSamplePeriod
Sample period, in microseconds.
cSamples
Total number of samples in the rglForceData. It must be an integral multiple of the cChannels.
rglForceData
Pointer to an array of force values representing the custom force. If multiple channels are provided, the values are interleaved. For example, if cChannels is 3, the first element of the array belongs to the first channel, the second to the second, and the third to the third.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98


DIDATAFORMAT Structure

Describes a device's data format. This structure is used with the IDirectInputDevice8::SetDataFormat method.

Syntax

typedef struct DIDATAFORMAT {
    DWORD dwSize;
    DWORD dwObjSize;
    DWORD dwFlags;
    DWORD dwDataSize;
    DWORD dwNumObjs;
    LPDIOBJECTDATAFORMAT rgodf;
} DIDATAFORMAT, *LPDIDATAFORMAT;

typedef const DIDATAFORMAT *LPCDIDATAFORMAT;

Members

dwSize
Size of this structure, in bytes.
dwObjSize
Size of the DIOBJECTDATAFORMAT structure, in bytes.
dwFlags
Flags describing other attributes of the data format. This value can be one of the following:
DIDF_ABSAXIS
The axes are in absolute mode. Setting this flag in the data format is equivalent to manually setting the axis mode property, using the IDirectInputDevice8::SetProperty method. This cannot be combined with DIDF_RELAXIS flag.
DIDF_RELAXIS
The axes are in relative mode. Setting this flag in the data format is equivalent to manually setting the axis mode property using the IDirectInputDevice8::SetProperty method. This cannot be combined with the DIDF_ABSAXIS flag.
dwDataSize
Size of a data packet returned by the device, in bytes. This value must be a multiple of 4 and must exceed the largest offset value for an object's data within the data packet.
dwNumObjs
Number of objects in the rgodf array.
rgodf
Address to an array of DIOBJECTDATAFORMAT structures. Each structure describes how one object's data should be reported in the device data. Typical errors include placing two pieces of information in the same location and placing one piece of information in more than one location.

Remarks

Applications do not typically need to create a DIDATAFORMAT structure. An application can use one of the predefined global data format variables, c_dfDIMouse, c_dfDIMouse2, c_dfDIKeyboard, c_dfDIJoystick, or c_dfDIJoystick2.

Applications that need to create a DIDATAFORMAT structure must first call IDirectInputDevice8::EnumObjects to determine the available objects for the current device. This is because the IDirectInputDevice8::SetDataFormat method will return DIERR_INVALIDPARAM if an an object is described in the DIDATAFORMAT structure but does not exist on the current device.

The following code example sets a data format for a device that has an X-axis and a Y-axis:

// Suppose an application uses the following
// structure to read device data.

typedef struct MYDATA {
    LONG  lX;                   // X-axis goes here.
    LONG  lY;                   // Y-axis goes here.
    BYTE  bButtonA;             // One button goes here.
    BYTE  bButtonB;             // Another button goes here.
    BYTE  bPadding[2];          // Must be DWORD multiple in size.
} MYDATA;

// Then, it can use the following data format.

DIOBJECTDATAFORMAT rgodf[ ] = {
  { &GUID_XAxis, FIELD_OFFSET(MYDATA, lX),
    DIDFT_AXIS | DIDFT_ANYINSTANCE, 0, },
  { &GUID_YAxis, FIELD_OFFSET(MYDATA, lY),
    DIDFT_AXIS | DIDFT_ANYINSTANCE, 0, },
  { &GUID_Button, FIELD_OFFSET(MYDATA, bButtonA),
    DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0, },
  { &GUID_Button, FIELD_OFFSET(MYDATA, bButtonB),
    DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0, },
};
#define numObjects (sizeof(rgodf) / sizeof(rgodf[0]))

DIDATAFORMAT df = {
    sizeof(DIDATAFORMAT),       // Size of this structure
    sizeof(DIOBJECTDATAFORMAT), // Size of object data format
    DIDF_ABSAXIS,               // Absolute axis coordinates
    sizeof(MYDATA),             // Size of device data
    numObjects,                 // Number of objects
    rgodf,                      // And here they are
};

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

DIACTIONFORMAT


DIDEVCAPS Structure

Describes a Microsoft DirectInput device's capabilities. This structure is used with the IDirectInputDevice8::GetCapabilities method.

Syntax

typedef struct DIDEVCAPS {
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwDevType;
    DWORD dwAxes;
    DWORD dwButtons;
    DWORD dwPOVs;
    DWORD dwFFSamplePeriod;
    DWORD dwFFMinTimeResolution;
    DWORD dwFirmwareRevision;
    DWORD dwHardwareRevision;
    DWORD dwFFDriverVersion;
} DIDEVCAPS, *LPDIDEVCAPS;

Members

dwSize
Size of this structure, in bytes. This member must be initialized by the application before a call to the IDirectInputDevice8::GetCapabilities method.
dwFlags
Flags associated with the device. This value can be a combination of the following:
DIDC_ALIAS
The device is a duplicate of another DirectInput device. Alias devices are by default not enumerated by IDirectInput8::EnumDevices.
DIDC_ATTACHED
The device is physically attached to the user's computer.
DIDC_DEADBAND
The device supports deadband for at least one force-feedback condition.
DIDC_EMULATED
If this flag is set, the data is coming from a user mode device interface, such as a Human Interface Device (HID), or by some other ring 3 means. If it is not set, the data is coming directly from a kernel mode driver.
DIDC_FORCEFEEDBACK
The device supports force feedback.
DIDC_FFFADE
The force-feedback system supports the fade parameter for at least one effect. If the device does not support fade, the fade level and fade time members of the DIENVELOPE structure are ignored by the device.

After a call to the IDirectInputDevice8::GetEffectInfo method, an individual effect sets the DIEFT_FFFADE flag if fade is supported for that effect.

DIDC_FFATTACK
The force-feedback system supports the attack parameter for at least one effect. If the device does not support attack, the attack level and attack time members of the DIENVELOPE structure are ignored by the device.

After a call to the IDirectInputDevice8::GetEffectInfo method, an individual effect sets the DIEFT_FFATTACK flag if attack is supported for that effect.

DIDC_HIDDEN
Fictitious device created by a device driver so that it can generate keyboard and mouse events. Such devices are not normally enumerated by IDirectInput8::EnumDevices or configured by IDirectInput8::ConfigureDevices.
DIDC_PHANTOM
Placeholder. Phantom devices are by default not enumerated by IDirectInput8::EnumDevices.
DIDC_POLLEDDATAFORMAT
At least one object in the current data format is polled, rather than interrupt-driven. For these objects, the application must explicitly call the IDirectInputDevice8::Poll method to obtain data.
DIDC_POLLEDDEVICE
At least one object on the device is polled, rather than interrupt-driven. For these objects, the application must explicitly call the IDirectInputDevice8::Poll method to obtain data. HID devices can contain a mixture of polled and nonpolled objects.
DIDC_POSNEGCOEFFICIENTS
The force-feedback system supports two coefficient values for conditions (one for the positive displacement of the axis and one for the negative displacement of the axis) for at least one condition. If the device does not support both coefficients, the negative coefficient in the DICONDITION structure is ignored.

After a call to the IDirectInputDevice8::GetEffectInfo method, an individual condition sets the DIEFT_POSNEGCOEFFICIENTS flag if separate positive and negative coefficients are supported for that condition.

DIDC_POSNEGSATURATION
The force-feedback system supports a maximum saturation for both positive and negative force output for at least one condition. If the device does not support both saturation values, the negative saturation in the DICONDITION structure is ignored.

After a call to the IDirectInputDevice8::GetEffectInfo method, an individual condition sets the DIEFT_POSNEGSATURATION flag if separate positive and negative saturation are supported for that condition.

DIDC_SATURATION
The force-feedback system supports the saturation of condition effects for at least one condition. If the device does not support saturation, the force generated by a condition is limited only by the maximum force that the device can generate.

After a call to the IDirectInputDevice8::GetEffectInfo method, an individual condition sets the DIEFT_SATURATION flag if saturation is supported for that condition.

DIDC_STARTDELAY
The force-feedback system supports the start delay parameter for at least one effect. If the device does not support start delays, the dwStartDelay member of the DIEFFECT structure is ignored.
dwDevType
Device type specifier. This member can contain values identical to those in the dwDevType member of the DIDEVICEINSTANCE structure.
dwAxes
Number of axes available on the device.
dwButtons
Number of buttons available on the device.
dwPOVs
Number of point-of-view controllers available on the device.
dwFFSamplePeriod
Minimum time between playback of consecutive raw force commands, in microseconds.
dwFFMinTimeResolution
Minimum time, in microseconds, that the device can resolve. The device rounds any times to the nearest supported increment. For example, if the value of dwFFMinTimeResolution is 1000, the device would round any times to the nearest millisecond.
dwFirmwareRevision
Firmware revision of the device.
dwHardwareRevision
Hardware revision of the device.
dwFFDriverVersion
Version number of the device driver.

Remarks

The semantics of version numbers are left to the manufacturer of the device. The only guarantee is that newer versions have larger numbers.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

DIDEVICEINSTANCE


DIDEVICEIMAGEINFO Structure

Carries information required to display a device image or an overlay image with a callout. This structure is passed to the IDirectInputDevice8::GetImageInfo method as an array within a DIDEVICEIMAGEINFOHEADER structure.

Syntax

typedef struct _DIDEVICEIMAGEINFO {
    TCHAR tszImagePath[MAX_PATH];
    DWORD dwFlags;
    DWORD dwViewID;
    RECT rcOverlay;
    DWORD dwObjID;
    DWORD dwcValidPts;
    POINT rgptCalloutLine[5];
    RECT rcCalloutRect;
    DWORD dwTextAlign;
} DIDEVICEIMAGEINFO, *LPDIDEVICEIMAGEINFO;

Members

tszImagePath
Fully qualified path to the file that contains an image of the device. The file format is given in dwFlags. If no image is available for the device, this member will be set to NULL. If so, the application is responsible for enumerating controls on the device and displaying a default listing of actions to device controls (similar to the method used by most applications before Microsoft DirectX 8.0).
dwFlags
Flag that describes the intended use of the image.
DIDIFT_CONFIGURATION
The file is used to display the current configuration of actions on the device. Overlay image coordinates are relative to the upper-left corner of the configuration image.
DIDIFT_OVERLAY
The file (if provided) is an overlay for a configuration image. The dwViewID, rcOverlay, dwObjID, rgptCalloutLine, rcCalloutRect, and dwTextAlign members are valid and contain data used to display the overlay and callout information for a single control on the device. If no file is provided (null path string), all other pertinent members are relevant except rcOverlay.
dwViewID
For device view images (DIDIFT_CONFIGURATION), this is the identifier (ID) of the device view. For device control overlays (DIDIFT_OVERLAY), this value refers to the device view (by ID) over which an image and callout information should be displayed.
rcOverlay
Rectangle, using coordinates relative to the top-left pixel of the device configuration image, in which the overlay image should be painted. This member is valid only if the DIDIFT_OVERLAY flag is present in dwFlags.
dwObjID
Control identifier, as a combination of DIDFT_* flags and an instance value, to which an overlay image corresponds for this device. Applications use the DIDFT_GETINSTANCE and DIDFT_GETTYPE macros to decode this value to its constituent parts. This member is valid only if the DIDIFT_OVERLAY flag is present in dwFlags.
dwcValidPts
Number of points in the array at rgptCalloutLine.
rgptCalloutLine
Array of POINT structures that specify coordinates of the points describing a callout line. A callout line connects a device control to a caption for the game action. Each line can have from one to four segments. This member is valid only if the DIDIFT_OVERLAY flag is present in dwFlags.
rcCalloutRect
RECT structure that describes the rectangle in which the game action string is displayed. If the string cannot fit within the rectangle, the application is responsible for handling clipping. This member is valid only if the DIDIFT_OVERLAY flag is present in dwFlags.
dwTextAlign
DWORD value that specifies the alignment of the text in the rectangle described by the rcCalloutRect member. Must be one horizontal alignment flag combined with one vertical alignment flag. This member is valid only if the DIDIFT_OVERLAY flag is present in dwFlags.
The following horizontal alignment flags are defined.
DIDAL_LEFTALIGNED
Text is aligned on the left border.
DIDAL_CENTERED
Text is horizontally centered.
DIDAL_RIGHTALIGNED
Text is aligned on the right border.
The following vertical alignment flags are defined.
DIDAL_MIDDLE
The text is vertically centered.
DIDAL_TOPALIGNED
The text is aligned on the top border.
DIDAL_BOTTOMALIGNED
The text is aligned on the bottom border.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98


DIDEVICEIMAGEINFOHEADER Structure

Contains information about device images. Used in the IDirectInputDevice8::GetImageInfo method.

Syntax

typedef struct _DIDEVICEIMAGEINFOHEADER {
    DWORD dwSize;
    DWORD dwSizeImageInfo;
    DWORD dwcViews;
    DWORD dwcButtons;
    DWORD dwcAxes;
    DWORD dwcPOVs;
    DWORD dwBufferSize;
    DWORD dwBufferUsed;
    DIDEVICEIMAGEINFO *lprgImageInfoArray;
} DIDEVICEIMAGEINFOHEADER, *LPDIDEVICEIMAGEINFOHEADER;

Members

dwSize
DWORD value that specifies the size of this structure, in bytes. Must be initialized before the structure can be used.
dwSizeImageInfo
DWORD value that specifies the size of the DIDEVICEIMAGEINFO structure, in bytes. Must be initialized before this structure can be used.
dwcViews
DWORD variable that receives the number of views of this device.
dwcButtons
DWORD variable that receives the number of buttons on the device.
dwcAxes
DWORD variable that receives the number of axes on the device.
dwcPOVs
DWORD variable that receives the number of point-of-view controllers on the device.
dwBufferSize
DWORD value that specifies the size, in bytes, of the buffer at lprgImageInfoArray. When set to zero, the IDirectInputDevice8::GetImageInfo method ignores all other members and returns the minimum buffer size required to hold information for all images.
dwBufferUsed
DWORD value that receives the size, in bytes, of the memory used in the buffer at lprgImageInfoArray. When dwBufferSize is set to zero, the IDirectInputDevice8::GetImageInfo method sets this member to the minimum size needed to hold information for all images.
lprgImageInfoArray
Pointer to a buffer that receives an array of DIDEVICEIMAGEINFO structures describing all the device images and views, overlay images, and callout-string coordinates.

Remarks

The buffer at lprgImageInfoArray must be large enough to hold all required image information structures. Applications can query for the required size by calling the IDirectInputDevice8::GetImageInfo method with the dwBufferSize member set to zero. After the call, dwBufferUsed contains the amount of memory, in bytes, that was modified.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98


DIDEVICEINSTANCE Structure

Describes an instance of a Microsoft DirectInput device. This structure is used with the IDirectInput8::EnumDevices, IDirectInput8::EnumDevicesBySemantics, and IDirectInputDevice8::GetDeviceInfo methods.

Syntax

typedef struct DIDEVICEINSTANCE {
    DWORD dwSize;
    GUID  guidInstance;
    GUID  guidProduct;
    DWORD dwDevType;
    TCHAR tszInstanceName[MAX_PATH];
    TCHAR tszProductName[MAX_PATH];
    GUID  guidFFDriver;
    WORD  wUsagePage;
    WORD  wUsage;
} DIDEVICEINSTANCE, *LPDIDEVICEINSTANCE;

typedef const DIDEVICEINSTANCE  *LPCDIDEVICEINSTANCE;

Members

dwSize
Size of this structure, in bytes. This member must be initialized before the structure is used.
guidInstance
Unique identifier for the instance of the device. An application can save the instance globally unique identifier (GUID) into a configuration file and use it at a later time. Instance GUIDs are specific to a particular computer. An instance GUID obtained from one computer is unrelated to instance GUIDs on another.
guidProduct
Unique identifier for the product. This identifier is established by the manufacturer of the device.
dwDevType
Device type specifier. The least-significant byte of the device type description code specifies the device type. The next-significant byte specifies the device subtype. This value can also be combined with DIDEVTYPE_HID, which specifies a Human Interface Device (HID).
tszInstanceName
Friendly name for the instance. For example, "Joystick 1."
tszProductName
Friendly name for the product.
guidFFDriver
Unique identifier for the driver being used for force feedback. The driver's manufacturer establishes this identifier.
wUsagePage
If the device is a Human Interface Device (HID), this member contains the HID usage page code.
wUsage
If the device is a Human Interface Device (HID), this member contains the HID usage code.

Remarks

The following device types and subtypes are defined for use in the dwDevType member.

  • DI8DEVTYPE_1STPERSON

    First-person action game device. The following subtypes are defined.

    • DI8DEVTYPE1STPERSON_LIMITED

      Device that does not provide the minimum number of device objects for action mapping.

    • DI8DEVTYPE1STPERSON_SHOOTER

      Device designed for first-person shooter games.

    • DI8DEVTYPE1STPERSON_SIXDOF

      Device with six degrees of freedom; that is, three lateral axes and three rotational axes.

    • DI8DEVTYPE1STPERSON_UNKNOWN

      Unknown subtype.

  • DI8DEVTYPE_DEVICE

    Device that does not fall into another category.

  • DI8DEVTYPE_DEVICECTRL

    Input device used to control another type of device from within the context of the application. The following subtypes are defined.

    • DI8DEVTYPEDEVICECTRL_COMMSSELECTION

      Control used to make communications selections.

    • DI8DEVTYPEDEVICECTRL_COMMSSELECTION_HARDWIRED

      Device that must use its default configuration and cannot be remapped.

    • DI8DEVTYPEDEVICECTRL_UNKNOWN

      Unknown subtype.

  • DI8DEVTYPE_DRIVING

    Device for steering. The following subtypes are defined.

    • DI8DEVTYPEDRIVING_COMBINEDPEDALS

      Steering device that reports acceleration and brake pedal values from a single axis.

    • DI8DEVTYPEDRIVING_DUALPEDALS

      Steering device that reports acceleration and brake pedal values from separate axes.

    • DI8DEVTYPEDRIVING_HANDHELD

      Hand-held steering device.

    • DI8DEVTYPEDRIVING_LIMITED

      Steering device that does not provide the minimum number of device objects for action mapping.

    • DI8DEVTYPEDRIVING_THREEPEDALS

      Steering device that reports acceleration, brake, and clutch pedal values from separate axes.

  • DI8DEVTYPE_FLIGHT

    Controller for flight simulation. The following subtypes are defined.

    • DI8DEVTYPEFLIGHT_LIMITED

      Flight controller that does not provide the minimum number of device objects for action mapping.

    • DI8DEVTYPEFLIGHT_RC

      Flight device based on a remote control for model aircraft.

    • DI8DEVTYPEFLIGHT_STICK

      Joystick.

    • DI8DEVTYPEFLIGHT_YOKE

      Yoke.

  • DI8DEVTYPE_GAMEPAD

    Gamepad. The following subtypes are defined.

    • DI8DEVTYPEGAMEPAD_LIMITED

      Gamepad that does not provide the minimum number of device objects for action mapping.

    • DI8DEVTYPEGAMEPAD_STANDARD

      Standard gamepad that provides the minimum number of device objects for action mapping.

    • DI8DEVTYPEGAMEPAD_TILT

      Gamepad that can report x-axis and y-axis data based on the attitude of the controller.

  • DI8DEVTYPE_JOYSTICK

    Joystick. The following subtypes are defined.

    • DI8DEVTYPEJOYSTICK_LIMITED

      Joystick that does not provide the minimum number of device objects for action mapping.

    • DI8DEVTYPEJOYSTICK_STANDARD

      Standard joystick that provides the minimum number of device objects for action mapping.

  • DI8DEVTYPE_KEYBOARD

    Keyboard or keyboard-like device. The following subtypes are defined.

    • DI8DEVTYPEKEYBOARD_UNKNOWN

      Subtype could not be determined.

    • DI8DEVTYPEKEYBOARD_PCXT

      IBM PC/XT 83-key keyboard.

    • DI8DEVTYPEKEYBOARD_OLIVETTI

      Olivetti 102-key keyboard.

    • DI8DEVTYPEKEYBOARD_PCAT

      IBM PC/AT 84-key keyboard.

    • DI8DEVTYPEKEYBOARD_PCENH

      IBM PC Enhanced 101/102-key or Microsoft Natural keyboard keyboard.

    • DI8DEVTYPEKEYBOARD_NOKIA1050

      Nokia 1050 keyboard.

    • DI8DEVTYPEKEYBOARD_NOKIA9140

      Nokia 9140 keyboard.

    • DI8DEVTYPEKEYBOARD_NEC98

      Japanese NEC PC98 keyboard.

    • DI8DEVTYPEKEYBOARD_NEC98LAPTOP

      Japanese NEC PC98 laptop keyboard.

    • DI8DEVTYPEKEYBOARD_NEC98106

      Japanese NEC PC98 106-key keyboard.

    • DI8DEVTYPEKEYBOARD_JAPAN106

      Japanese 106-key keyboard.

    • DI8DEVTYPEKEYBOARD_JAPANAX

      Japanese AX keyboard.

    • DI8DEVTYPEKEYBOARD_J3100

      Japanese J3100 keyboard.

  • DI8DEVTYPE_MOUSE

    A mouse or mouse-like device (such as a trackball). The following subtypes are defined.

    • DI8DEVTYPEMOUSE_ABSOLUTE

      Mouse that returns absolute axis data.

    • DI8DEVTYPEMOUSE_FINGERSTICK

      Fingerstick.

    • DI8DEVTYPEMOUSE_TOUCHPAD

      Touchpad.

    • DI8DEVTYPEMOUSE_TRACKBALL

      Trackball.

    • DI8DEVTYPEMOUSE_TRADITIONAL

      Traditional mouse.

    • DI8DEVTYPEMOUSE_UNKNOWN

      Subtype could not be determined.

  • DI8DEVTYPE_REMOTE

    Remote-control device. The following subtype is defined.

    • DI8DEVTYPEREMOTE_UNKNOWN

      Subtype could not be determined.

  • DI8DEVTYPE_SCREENPOINTER

    Screen pointer. The following subtypes are defined.

    • DI8DEVTYPESCREENPTR_UNKNOWN

      Unknown subtype.

    • DI8DEVTYPESCREENPTR_LIGHTGUN

      Light gun.

    • DI8DEVTYPESCREENPTR_LIGHTPEN

      Light pen.

    • DI8DEVTYPESCREENPTR_TOUCH

      Touch screen.

  • DI8DEVTYPE_SUPPLEMENTAL

    Specialized device with functionality unsuitable for the main control of an application, such as pedals used with a wheel. The following subtypes are defined.

    • DI8DEVTYPESUPPLEMENTAL_2NDHANDCONTROLLER

      Secondary handheld controller.

    • DI8DEVTYPESUPPLEMENTAL_COMBINEDPEDALS

      Device whose primary function is to report acceleration and brake pedal values from a single axis.

    • DI8DEVTYPESUPPLEMENTAL_DUALPEDALS

      Device whose primary function is to report acceleration and brake pedal values from separate axes.

    • DI8DEVTYPESUPPLEMENTAL_HANDTRACKER

      Device that tracks hand movement.

    • DI8DEVTYPESUPPLEMENTAL_HEADTRACKER

      Device that tracks head movement.

    • DI8DEVTYPESUPPLEMENTAL_RUDDERPEDALS

      Device with rudder pedals.

    • DI8DEVTYPESUPPLEMENTAL_SHIFTER

      Device that reports gear selection from an axis.

    • DI8DEVTYPESUPPLEMENTAL_SHIFTSTICKGATE

      Device that reports gear selection from button states.

    • DI8DEVTYPESUPPLEMENTAL_SPLITTHROTTLE

      Device whose primary function is to report at least two throttle values. It may have other controls.

    • DI8DEVTYPESUPPLEMENTAL_THREEPEDALS

      Device whose primary function is to report acceleration, brake, and clutch pedal values from separate axes.

    • DI8DEVTYPESUPPLEMENTAL_THROTTLE

      Device whose primary function is to report a single throttle value. It may have other controls.

    • DI8DEVTYPESUPPLEMENTAL_UNKNOWN

      Unknown subtype.

Versions of DirectInput earlier than Microsoft DirectX 8.0 have a somewhat different scheme of device types and subtypes. See the DIDEVTYPExxx defines in Dinput.h.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98


DIDEVICEOBJECTDATA Structure

Contains buffered device information. This structure is used with the IDirectInputDevice8::GetDeviceData and the IDirectInputDevice8::SendDeviceData methods.

Syntax

typedef struct DIDEVICEOBJECTDATA {
    DWORD    dwOfs;
    DWORD    dwData;
    DWORD    dwTimeStamp;
    DWORD    dwSequence;
    UINT_PTR uAppData;
} DIDEVICEOBJECTDATA, *LPDIDEVICEOBJECTDATA;

typedef const DIDEVICEOBJECTDATA *LPCDIDEVICEOBJECTDATA;

Members

dwOfs
For IDirectInputDevice8::GetDeviceData, the offset into the current data format of the object whose data is being reported; that is, the location in which the dwData would have been stored if the data had been obtained by a call to the IDirectInputDevice8::GetDeviceState method. If the device is accessed as a mouse, keyboard, or joystick, the dwOfs member is one of the mouse device constants, keyboard device constants, or joystick device constants. If a custom data format has been set, it is an offset relative to the custom data format.

This member can be ignored if Action Mapping is being used. Instead, retrieve the action value from uAppData.

For IDirectInputDevice8::SendDeviceData, the instance identifier (ID) of the object to which the data is being sent, as obtained from the dwType member of a DIDEVICEOBJECTINSTANCE structure.

dwData
Data obtained from or sent to the device.

For axis input, if the device is in relative axis mode, the relative axis motion is reported. If the device is in absolute axis mode, the absolute axis coordinate is reported.

For button input, only the low byte of dwData is significant. The high bit of the low byte is set if the button was pressed; it is clear if the button was released.

dwTimeStamp
System time at which the input event was generated, in milliseconds. This value wraps around approximately every 50 days. See Remarks.

When the structure is used with the IDirectInputDevice8::SendDeviceData method, this member must be 0.

dwSequence
Microsoft DirectInput sequence number for this event. All input events are assigned an increasing sequence number. This enables events from different devices to be sorted chronologically. Because this value can wrap around, care must be taken when comparing two sequence numbers. The DISEQUENCE_COMPARE macro can be used to perform this comparison safely.

When the structure is used with the IDirectInputDevice8::SendDeviceData method, this member must be 0.

uAppData
Application-defined action value assigned to this object in the last call to IDirectInputDevice8::SetActionMap. This is the value in the uAppData member of the DIACTION structure associated with the object. Ignore this value if you are not using action mapping.

When the structure is used with the IDirectInputDevice8::SendDeviceData method, this member must be zero.

Remarks

The system time returned in dwTimeStamp comes from the same clock used by the Microsoft Win32 GetTickCount or timeGetTime functions, but it produces potentially more precise values. For example, on Microsoft Windows 95, the GetTickCount timer is updated only every 55 milliseconds, but the dwTimeStamp value is accurate to within 1 millisecond. Therefore, if you call GetTickCount and it returns n, and you then receive an event with a timestamp of n + n1, you cannot assume that the event took place exactly n1 milliseconds after the call to GetTickCount.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98


DIDEVICEOBJECTINSTANCE Structure

Describes a device object instance. This structure is used with the IDirectInputDevice8::EnumObjects method to provide the DIEnumDeviceObjectsCallback callback function with information about a particular object associated with a device, such as an axis or button. It is also used with the IDirectInputDevice8::GetObjectInfo method to retrieve information about a device object.

Syntax

typedef struct DIDEVICEOBJECTINSTANCE {
    DWORD dwSize;
    GUID  guidType;
    DWORD dwOfs;
    DWORD dwType;
    DWORD dwFlags;
    TCHAR tszName[MAX_PATH];
    DWORD dwFFMaxForce;
    DWORD dwFFForceResolution;
    WORD  wCollectionNumber;
    WORD  wDesignatorIndex;
    WORD  wUsagePage;
    WORD  wUsage;
    DWORD dwDimension;
    WORD  wExponent;
    WORD  wReportId;
} DIDEVICEOBJECTINSTANCE, *LPDIDEVICEOBJECTINSTANCE;

typedef const DIDEVICEOBJECTINSTANCE *LPCDIDEVICEOBJECTINSTANCE;

Members

dwSize
Size of the structure, in bytes. During enumeration, the application can inspect this value to determine how many members of the structure are valid. When the structure is passed to the IDirectInputDevice8::GetObjectInfo method, this member must be initialized to sizeof(DIDEVICEOBJECTINSTANCE).
guidType
Unique identifier that indicates the object type. This member is optional. If present, it can be one of the following values:
GUID_XAxis
The horizontal axis. For example, it can represent the left-right motion of a mouse.
GUID_YAxis
The vertical axis. For example, it can represent the forward-backward motion of a mouse.
GUID_ZAxis
The z-axis. For example, it can represent the rotation of a mouse wheel or the movement of a joystick throttle control.
GUID_RxAxis
Rotation around the x-axis.
GUID_RyAxis
Rotation around the y-axis.
GUID_RzAxis
Rotation around the z-axis (often a rudder control).
GUID_Slider
A slider axis.
GUID_Button
A mouse button.
GUID_Key
A keyboard key.
GUID_POV
A point-of-view indicator.
GUID_Unknown
Unknown.
dwOfs
Offset in the native data format of the device. The native data format corresponds to the raw device data. The dwOfs member does not correspond to the device constant, such as DIJOFS_BUTTON0, for this object.
dwType
Device type that describes the object. It is a combination of DIDFT_* flags that describe the object type (axis, button, and so on) and contains the object instance number in the middle 16 bits. Use the DIDFT_GETINSTANCE macro to extract the object instance number. For the DIDFT_* flags, see IDirectInputDevice8::EnumObjects.
dwFlags
Flags describing other attributes of the data format. This value can be one of the following:
DIDOI_ASPECTACCEL
The object reports acceleration information.
DIDOI_ASPECTFORCE
The object reports force information.
DIDOI_ASPECTMASK
The bits that are used to report aspect information. An object can represent at most one aspect.
DIDOI_ASPECTPOSITION
The object reports position information.
DIDOI_ASPECTVELOCITY
The object reports velocity information.
DIDOI_FFACTUATOR
The object can have force-feedback effects applied to it.
DIDOI_FFEFFECTTRIGGER
The object can trigger playback of force-feedback effects.
DIDOI_GUIDISUSAGE
The pguid member of the DIOBJECTDATAFORMAT structure contains the desired usage page and usage in a packed DWORD. See DIMAKEUSAGEDWORD.
DIDOI_POLLED
The object does not return data until the IDirectInputDevice8::Poll method is called.
tszName
Name of the object; for example, "X-Axis" or "Right Shift."
dwFFMaxForce
The magnitude of the maximum force that can be created by the actuator associated with this object. Force is expressed in newtons and measured in relation to where the hand would be during normal operation of the device.
dwFFForceResolution
The force resolution of the actuator associated with this object. The returned value represents the number of gradations, or subdivisions, of the maximum force that can be expressed by the force-feedback system from 0 (no force) to maximum force.
wCollectionNumber
The Human Interface Device (HID) link collection to which the object belongs.
wDesignatorIndex
An index that refers to a designator in the HID physical descriptor. This number can be passed to functions in the HID parsing library (Hidpi.h) to obtain additional information about the device object.
wUsagePage
The Human Interface Device (HID) usage page associated with the object, if known. HIDs always report a usage page. Non-HID devices can optionally report a usage page; if they do not, the value of this member is 0.
wUsage
The HID usage associated with the object, if known. HIDs always report a usage. Non-HIDs can optionally report a usage; if they do not, the value of this member is 0.
dwDimension
A Human Interface Device (HID) code for the dimensional units in which the object's value is reported, if known, or 0 if not known.
wExponent
The exponent to associate with the dimension, if known. Dimensional units are always integral, so an exponent might be needed to convert them to nonintegral types.
wReportId
Reserved.

Remarks

Warning The value in dwOfs is the offset within the raw data returned by the device, regardless of whether the data format has been set for the device.

Applications can use the wUsagePage and wUsage members to obtain additional information about how the object was designed to be used. For example, if wUsagePage has the value 0x02 (vehicle controls) and wUsage has the value 0xB9 (elevator trim), the object was designed to be the elevator trim control on a flight stick. A flight simulator application can use this information to provide more reasonable defaults for objects on the device. HID usage codes are determined by the USB standards committee.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98


DIEFFECT Structure

Used by the IDirectInputDevice8::CreateEffect method to initialize a new IDirectInputEffect object. It is also used by the IDirectInputEffect::SetParameters and IDirectInputEffect::GetParameters methods.

Syntax

typedef struct DIEFFECT {
    DWORD   dwSize;
    DWORD   dwFlags;
    DWORD   dwDuration;
    DWORD   dwSamplePeriod;
    DWORD   dwGain;
    DWORD   dwTriggerButton;
    DWORD   dwTriggerRepeatInterval;
    DWORD   cAxes;
    LPDWORD rgdwAxes;
    LPLONG  rglDirection;
    LPDIENVELOPE lpEnvelope;
    DWORD   cbTypeSpecificParams;
    LPVOID  lpvTypeSpecificParams;
    DWORD   dwStartDelay;
} DIEFFECT, *LPDIEFFECT;

typedef const DIEFFECT *LPCDIEFFECT;

Members

dwSize
Specifies the size, in bytes, of the structure. This member must be initialized before the structure is used.
dwFlags
Flags associated with the effect. This value can be a combination of one or more of the following values:
DIEFF_CARTESIAN
The values of rglDirection are to be interpreted as Cartesian coordinates.
DIEFF_OBJECTIDS
The values of dwTriggerButton and rgdwAxes are object identifiers as obtained by IDirectInputDevice8::EnumObjects.
DIEFF_OBJECTOFFSETS
The values of dwTriggerButton and rgdwAxes are data format offsets.
DIEFF_POLAR
The values of rglDirection are to be interpreted as polar coordinates.
DIEFF_SPHERICAL
The values of rglDirection are to be interpreted as spherical coordinates.
dwDuration
The total duration of the effect, in microseconds. If this value is INFINITE, the effect has infinite duration. If an envelope has been applied to the effect, the attack is applied, followed by an infinite sustain.
dwSamplePeriod
The period at which the device should play back the effect, in microseconds. A value of 0 indicates that the default playback sample rate should be used.

If the device is not capable of playing back the effect at the specified rate, it chooses the supported rate that is closest to the requested value.

Setting a custom dwSamplePeriod can be used for special effects. For example, playing a sine wave at an artificially large sample period results in a rougher texture.

dwGain
The gain to be applied to the effect, in the range from 0 through 10,000. The gain is a scaling factor applied to all magnitudes of the effect and its envelope.
dwTriggerButton
The identifier or offset of the button to be used to trigger playback of the effect. The flags DIEFF_OBJECTIDS and DIEFF_OBJECTOFFSETS determine the semantics of the value. If this member is set to DIEB_NOTRIGGER, no trigger button is associated with the effect.
dwTriggerRepeatInterval
The interval, in microseconds, between the end of one playback and the start of the next when the effect is triggered by a button press and the button is held down. Setting this value to INFINITE suppresses repetition.

Support for trigger repeat for an effect is indicated by the presence of the DIEP_TRIGGERREPEATINTERVAL flag in the dwStaticParams member of the DIEFFECTINFO structure.

cAxes
Number of axes involved in the effect. This member must be filled in by the calling application if changing or setting the axis list or the direction list.

The number of axes for an effect cannot be changed once it has been set.

rgdwAxes
Pointer to a DWORD array (of cAxes elements) containing identifiers or offsets identifying the axes to which the effect is to be applied. The flags DIEFF_OBJECTIDS and DIEFF_OBJECTOFFSETS determine the semantics of the values in the array.

The list of axes associated with an effect cannot be changed once it has been set.

No more than 32 axes can be associated with a single effect.

rglDirection
Pointer to a LONG array (of cAxes elements) containing either Cartesian coordinates, polar coordinates, or spherical coordinates. The flags DIEFF_CARTESIAN, DIEFF_POLAR, and DIEFF_SPHERICAL determine the semantics of the values in the array.

If Cartesian, each value in rglDirection is associated with the corresponding axis in rgdwAxes.

If polar, the angle is measured in hundredths of degrees from the (0, –1) direction, rotated in the direction of (1, 0). This usually means that north is away from the user, and east is to the user's right. The last element is not used.

If spherical, the first angle is measured in hundredths of a degree from the (1, 0) direction, rotated in the direction of (0, 1). The second angle (if the number of axes is three or more) is measured in hundredths of a degree toward (0, 0, 1). The third angle (if the number of axes is four or more) is measured in hundredths of a degree toward (0, 0, 0, 1), and so on. The last element is not used.

lpEnvelope
Optional pointer to a DIENVELOPE structure that describes the envelope to be used by this effect. Not all effect types use envelope. If no envelope is to be applied, the member should be set to NULL.
cbTypeSpecificParams
Number of bytes of additional type-specific parameters for the corresponding effect type.
lpvTypeSpecificParams
Pointer to type-specific parameters, or NULL if there are no type-specific parameters.

If the effect is of type DIEFT_CONDITION, this member contains a pointer to an array of DICONDITION structures that define the parameters for the condition. A single structure may be used, in which case the condition is applied in the direction specified in the rglDirection array. Otherwise, there must be one structure for each axis, in the same order as the axes in rgdwAxes array. If a structure is supplied for each axis, the effect should not be rotated; you should use the following values in the rglDirection array:

  • DIEFF_SPHERICAL: 0, 0, ...
  • DIEFF_POLAR: 9000, 0, ...
  • DIEFF_CARTESIAN: 1, 0, ...

If the effect is of type DIEFT_CUSTOMFORCE, this member contains a pointer to a DICUSTOMFORCE structure that defines the parameters for the custom force.

If the effect is of type DIEFT_PERIODIC, this member contains a pointer to a DIPERIODIC structure that defines the parameters for the effect.

If the effect is of type DIEFT_CONSTANTFORCE, this member contains a pointer to a DICONSTANTFORCE structure that defines the parameters for the constant force.

If the effect is of type DIEFT_RAMPFORCE, this member contains a pointer to a DIRAMPFORCE structure that defines the parameters for the ramp force.

dwStartDelay
Time (in microseconds) that the device should wait after an IDirectInputEffect::Start call before playing the effect. If this value is 0, effect playback begins immediately. This member is not present in versions prior to Microsoft DirectX 7.0.

Remarks

Note The rglDirection array must contain cAxes entries, even if polar or spherical coordinates are given. In these cases, the last element in the rglDirection array is reserved and must be 0.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98


DIEFFECTINFO Structure

Used by the IDirectInputDevice8::EnumEffects and IDirectInputDevice8::GetEffectInfo methods to return information about a particular effect supported by a device.

Syntax

typedef struct DIEFFECTINFO {
    DWORD dwSize;
    GUID  guid;
    DWORD dwEffType;
    DWORD dwStaticParams;
    DWORD dwDynamicParams;
    TCHAR tszName[MAX_PATH];
} DIEFFECTINFO, *LPDIEFFECTINFO;

typedef const DIEFFECTINFO  *LPCDIEFFECTINFO;

Members

dwSize
Size of the structure in bytes. During enumeration, the application can inspect this value to determine how many members of the structure are valid. This member must be initialized before the structure is passed to the IDirectInputDevice8::GetEffectInfo method.
guid
Identifier of the effect.
dwEffType
Zero or more of the following values:
DIEFT_ALL
Valid only for IDirectInputDevice8::EnumEffects. Enumerate all effects, regardless of type. This flag cannot be combined with any of the other flags.
DIEFT_CONDITION
The effect represents a condition. When creating or modifying a condition, the lpvTypeSpecificParams member of the DIEFFECT structure must point to an array of DICONDITION structures (one per axis), and the cbTypeSpecificParams member must be set to cAxis * sizeof(DICONDITION).

Not all devices support all the parameters of conditions. Check the effect capability flags to determine which capabilities are available.

The flag can be passed to IDirectInputDevice8::EnumEffects to restrict the enumeration to conditions.

DIEFT_CONSTANTFORCE
The effect represents a constant-force effect. When creating or modifying a constant-force effect, the lpvTypeSpecificParams member of the DIEFFECT must point to a DICONSTANTFORCE structure, and the cbTypeSpecificParams member must be set to sizeof(DICONSTANTFORCE).

The flag can be passed to IDirectInputDevice8::EnumEffects to restrict the enumeration to constant-force effects.

DIEFT_CUSTOMFORCE
The effect represents a custom-force effect. When creating or modifying a custom-force effect, the lpvTypeSpecificParams member of the DIEFFECT structure must point to a DICUSTOMFORCE structure, and the cbTypeSpecificParams member must be set to sizeof(DICUSTOMFORCE).

The flag can be passed to IDirectInputDevice8::EnumEffects to restrict the enumeration to custom-force effects.

DIEFT_DEADBAND
The effect generator for this condition effect supports the lDeadBand parameter.
DIEFT_FFATTACK
The effect generator for this effect supports the attack envelope parameter. If the effect generator does not support attack, the attack level and attack time parameters of the DIENVELOPE structure are ignored by the effect.

If neither DIEFT_FFATTACK nor DIEFT_FFFADE is set, the effect does not support an envelope, and any provided envelope is ignored.

DIEFT_FFFADE
The effect generator for this effect supports the fade parameter. If the effect generator does not support fade, the fade level and fade time parameters of the DIENVELOPE structure are ignored by the effect.

If neither DIEFT_FFATTACK nor DIEFT_FFFADE is set, the effect does not support an envelope, and any provided envelope is ignored.

DIEFT_HARDWARE
The effect represents a hardware-specific effect. For additional information about using a hardware-specific effect, consult the hardware documentation.

The flag can be passed to the IDirectInputDevice8::EnumEffects method to restrict the enumeration to hardware-specific effects.

DIEFT_PERIODIC
The effect represents a periodic effect. When creating or modifying a periodic effect, the lpvTypeSpecificParams member of the DIEFFECT structure must point to a DIPERIODICstructure, and the cbTypeSpecificParams member must be set to sizeof(DIPERIODIC).

The flag can be passed to IDirectInputDevice8::EnumEffects to restrict the enumeration to periodic effects.

DIEFT_POSNEGCOEFFICIENTS
The effect generator for this effect supports two coefficient values for conditions, one for the positive displacement of the axis and one for the negative displacement of the axis. If the device does not support both coefficients, the negative coefficient in the DICONDITION structure is ignored, and the positive coefficient is used in both directions.
DIEFT_POSNEGSATURATION
The effect generator for this effect supports a maximum saturation for both positive and negative force output. If the device does not support both saturation values, the negative saturation in the DICONDITION structure is ignored, and the positive saturation is used in both directions.
DIEFT_RAMPFORCE
The effect represents a ramp-force effect. When creating or modifying a ramp-force effect, the lpvTypeSpecificParams member of the DIEFFECT structure must point to a DIRAMPFORCE structure, and the cbTypeSpecificParams member must be set to sizeof(DIRAMPFORCE).

The flag can be passed to IDirectInputDevice8::EnumEffects to restrict the enumeration to ramp-force effects.

DIEFT_SATURATION
The effect generator for this effect supports the saturation of condition effects. If the effect generator does not support saturation, the force generated by a condition is limited only by the maximum force that the device can generate.
DIEFT_STARTDELAY
The effect has a delay before it plays rather than beginning immediately. This can be used to offset effects so that they play in sequence.
dwStaticParams
Zero or more DIEP_* values describing the parameters supported by the effect. For example, if DIEP_ENVELOPE is set, the effect supports an envelope. For a list of possible values, see IDirectInputEffect::GetParameters.

It is not an error for an application to attempt to use effect parameters that are not supported by the device. The unsupported parameters are ignored.

This information is provided to enable the application to tailor its use of force feedback to the capabilities of the specific device.

dwDynamicParams
Zero or more DIEP_* values denoting parameters of the effect that can be modified while the effect is playing. For a list of possible values, see IDirectInputEffect::GetParameters.

If an application attempts to change a parameter while the effect is playing and the driver does not support modifying that effect dynamically, the driver is permitted to stop the effect, update the parameters, then restart it. For more information, see IDirectInputEffect::SetParameters.

tszName
Name of the effect; for example, "Sawtooth up" or "Constant force".

Remarks

Use the DIEFT_GETTYPE macro to extract the effect type from the dwEffType flags.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98


DIEFFESCAPE Structure

Used by the IDirectInputDevice8::Escape and IDirectInputEffect::Escape methods to pass hardware-specific data directly to the device driver.

Syntax

typedef struct DIEFFESCAPE {
    DWORD dwSize;
    DWORD dwCommand;
    LPVOID lpvInBuffer;
    DWORD cbInBuffer;
    LPVOID lpvOutBuffer;
    DWORD cbOutBuffer;
} DIEFFESCAPE, *LPDIEFFESCAPE;

Members

dwSize
Size of the structure in bytes. This member must be initialized before the structure is used.
dwCommand
Driver-specific command number. Consult the driver documentation for a list of valid commands.
lpvInBuffer
Buffer containing the data required to perform the operation.
cbInBuffer
Size, in bytes, of the lpvInBuffer buffer.
lpvOutBuffer
Buffer in which the operation's output data is returned.
cbOutBuffer
On entry, the size in bytes of the lpvOutBuffer buffer. On exit, the number of bytes actually produced by the command.

Remarks

Because each driver implements different escapes, it is the application's responsibility to ensure that it is talking to the correct driver by comparing the guidFFDriver member in the DIDEVICEINSTANCE structure against the value the application is expecting.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98


DIENVELOPE Structure

Used by the DIEFFECT structure to specify the optional envelope parameters for an effect. The sustain level for the envelope is represented by the dwMagnitude member of the DIPERIODIC structure and the lMagnitude member of the DICONSTANTFORCE structure. The sustain time is represented by dwDuration member of the DIEFFECT structure.

Syntax

typedef struct DIENVELOPE {
    DWORD dwSize;
    DWORD dwAttackLevel;
    DWORD dwAttackTime;
    DWORD dwFadeLevel;
    DWORD dwFadeTime;
} DIENVELOPE, *LPDIENVELOPE;

typedef const DIENVELOPE *LPCDIENVELOPE;

Members

dwSize
Size, in bytes, of the structure. This member must be initialized before the structure is used.
dwAttackLevel
Amplitude for the start of the envelope, relative to the baseline, in the range from 0 through 10,000. If the effect's type-specific data does not specify a baseline, the amplitude is relative to 0.
dwAttackTime
The time, in microseconds, to reach the sustain level.
dwFadeLevel
Amplitude for the end of the envelope, relative to the baseline, in the range from 0 through 10,000. If the effect's type-specific data does not specify a baseline, the amplitude is relative to 0.
dwFadeTime
The time, in microseconds, to reach the fade level.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98


DIFILEEFFECT Structure

Describes data for a force-feedback effect stored in a file. It is used in conjunction with the IDirectInputDevice8::EnumEffectsInFile and IDirectInputDevice8::WriteEffectToFile methods.

Syntax

typedef struct DIFILEEFFECT {
    DWORD dwSize;
    GUID GuidEffect;
    LPCDIEFFECT lpDiEffect;
    CHAR szFriendlyName[MAX_PATH];
} DIFILEEFFECT, *LPDIFILEEFFECT;

Members

dwSize
Size, in bytes, of the structure. This member must be initialized before the structure is used.
GuidEffect
Unique identifier of the effect type. This can be one of the standard globally unique identifiers (GUIDs) defined in Dinput.h, such as GUID_ConstantForce, or one created by the designer.
lpDiEffect
Pointer to a DIEFFECT structure containing information about the effect.
szFriendlyName
Name of the effect.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98


DIJOYSTATE Structure

Describes the state of a joystick device. This structure is used with the IDirectInputDevice8::GetDeviceState method.

Syntax

typedef struct DIJOYSTATE {
    LONG lX;
    LONG lY;
    LONG lZ;
    LONG lRx;
    LONG lRy;
    LONG lRz;
    LONG rglSlider[2];
    DWORD rgdwPOV[4];
    BYTE rgbButtons[32];
} DIJOYSTATE, *LPDIJOYSTATE;

Members

lX
X-axis, usually the left-right movement of a stick.
lY
Y-axis, usually the forward-backward movement of a stick.
lZ
Z-axis, often the throttle control. If the joystick does not have this axis, the value is 0.
lRx
X-axis rotation. If the joystick does not have this axis, the value is 0.
lRy
Y-axis rotation. If the joystick does not have this axis, the value is 0.
lRz
Z-axis rotation (often called the rudder). If the joystick does not have this axis, the value is 0.
rglSlider
Two additional axes, formerly called the u-axis and v-axis, whose semantics depend on the joystick. Use the IDirectInputDevice8::GetObjectInfo method to obtain semantic information about these values.
rgdwPOV
Direction controllers, such as point-of-view hats. The position is indicated in hundredths of a degree clockwise from north (away from the user). The center position is normally reported as –1; but see Remarks. For indicators that have only five positions, the value for a controller is –1, 0, 9,000, 18,000, or 27,000.
rgbButtons
Array of buttons. The high-order bit of the byte is set if the corresponding button is down, and clear if the button is up or does not exist.

Remarks

You must prepare the device for joystick-style access by calling the IDirectInputDevice8::SetDataFormat method, passing the c_dfDIJoystick global data format variable.

If an axis is in relative mode, the appropriate member contains the change in position. If it is in absolute mode, the member contains the absolute axis position.

Some drivers report the centered position of the POV indicator as 65,535. Determine whether the indicator is centered as follows:

BOOL POVCentered = (LOWORD(dwPOV) == 0xFFFF);

Note Under Microsoft DirectX 7.0, sliders on some joysticks could be assigned to the Z axis, with subsequent code retrieving data from that member. Using DirectX 8.0 and later, those same sliders will be assigned to the rglSlider array. This should be taken into account when porting applications to later versions of DirectX. Make any necessary alterations to ensure that slider data is retrieved from the rglSlider array.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

DIJOYSTATE2


DIJOYSTATE2 Structure

Describes the state of a joystick device with extended capabilities. This structure is used with the IDirectInputDevice8::GetDeviceState method.

Syntax

typedef struct {
    LONG lX;
    LONG lY;
    LONG lZ;
    LONG lRx;
    LONG lRy;
    LONG lRz;
    LONG rglSlider[2];
    DWORD rgdwPOV[4];
    BYTE rgbButtons[128];
    LONG lVX;
    LONG lVY;
    LONG lVZ;
    LONG lVRx;
    LONG lVRy;
    LONG lVRz;
    LONG rglVSlider[2];
    LONG lAX;
    LONG lAY;
    LONG lAZ;
    LONG lARx;
    LONG lARy;
    LONG lARz;
    LONG rglASlider[2];
    LONG lFX;
    LONG lFY;
    LONG lFZ;
    LONG lFRx;
    LONG lFRy;
    LONG lFRz;
    LONG rglFSlider[2];
} DIJOYSTATE2, *LPDIJOYSTATE2;

Members

lX
X-axis, usually the left-right movement of a stick.
lY
Y-axis, usually the forward-backward movement of a stick.
lZ
Z-axis, often the throttle control. If the joystick does not have this axis, the value is 0.
lRx
X-axis rotation. If the joystick does not have this axis, the value is 0.
lRy
Y-axis rotation. If the joystick does not have this axis, the value is 0.
lRz
Z-axis rotation (often called the rudder). If the joystick does not have this axis, the value is 0.
rglSlider
Two additional axis values (formerly called the u-axis and v-axis) whose semantics depend on the joystick. Use the IDirectInputDevice8::GetObjectInfo method to obtain semantic information about these values.
rgdwPOV
Direction controllers, such as point-of-view hats. The position is indicated in hundredths of a degree clockwise from north (away from the user). The center position is normally reported as–1; but see Remarks. For indicators that have only five positions, the value for a controller is –1, 0, 9,000, 18,000, or 27,000.
rgbButtons
Array of buttons. The high-order bit of the byte is set if the corresponding button is down, and clear if the button is up or does not exist.
lVX
X-axis velocity.
lVY
Y-axis velocity.
lVZ
Z-axis velocity.
lVRx
X-axis angular velocity.
lVRy
Y-axis angular velocity.
lVRz
Z-axis angular velocity.
rglVSlider
Extra axis velocities.
lAX
X-axis acceleration.
lAY
Y-axis acceleration.
lAZ
Z-axis acceleration.
lARx
X-axis angular acceleration.
lARy
Y-axis angular acceleration.
lARz
Z-axis angular acceleration.
rglASlider
Extra axis accelerations.
lFX
X-axis force.
lFY
Y-axis force.
lFZ
Z-axis force.
lFRx
X-axis torque.
lFRy
Y-axis torque.
lFRz
Z-axis torque.
rglFSlider
Extra axis forces.

Remarks

You must prepare the device for access to a joystick with extended capabilities by calling the IDirectInputDevice8::SetDataFormat method, passing the c_dfDIJoystick2 global data format variable.

If an axis is in relative mode, the appropriate member contains the change in position. If it is in absolute mode, the member contains the absolute axis position.

Some drivers report the centered position of the POV indicator as 65,535. Determine whether the indicator is centered as follows:

BOOL POVCentered = (LOWORD(dwPOV) == 0xFFFF);

Note Under Microsoft DirectX 7.0, sliders on some joysticks could be assigned to the Z axis, with subsequent code retrieving data from that member. Using DirectX 8.0 and later, those same sliders will be assigned to the rglSlider array. This should be taken into account when porting applications to later versions of DirectX. Make any necessary alterations to ensure that slider data is retrieved from the rglSlider array.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

DIJOYSTATE


DIMOUSESTATE Structure

Describes the state of a mouse device that has up to four buttons, or another device that is being accessed as if it were a mouse device. This structure is used with the IDirectInputDevice8::GetDeviceState method.

Syntax

typedef struct DIMOUSESTATE {
    LONG lX;
    LONG lY;
    LONG lZ;
    BYTE rgbButtons[4];
} DIMOUSESTATE, *LPDIMOUSESTATE;

Members

lX
X-axis.
lY
Y-axis.
lZ
Z-axis, typically a wheel. If the mouse does not have a z-axis, the value is 0.
rgbButtons
Array of buttons. The high-order bit of the byte is set if the corresponding button is down.

Remarks

You must prepare the device for mouse-style access by calling the IDirectInputDevice8::SetDataFormat method, passing the c_dfDIMouse global data format variable.

The mouse is a relative-axis device, so the absolute axis positions for mouse axes are accumulated relative motion. Therefore, the value of the absolute axis position is not meaningful except in comparison with other absolute axis positions.

If an axis is in relative mode, the appropriate member contains the change in position. If it is in absolute mode, the member contains the absolute axis position.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

DIMOUSESTATE2


DIMOUSESTATE2 Structure

Describes the state of a mouse device that has up to eight buttons, or another device that is being accessed as if it were a mouse device. This structure is used with the IDirectInputDevice8::GetDeviceState method.

Syntax

typedef struct DIMOUSESTATE2 {
    LONG lX;
    LONG lY;
    LONG lZ;
    BYTE rgbButtons[8];
} DIMOUSESTATE2, *LPDIMOUSESTATE2;

Members

lX
X-axis.
lY
Y-axis.
lZ
Z-axis, typically a wheel. If the mouse does not have a z-axis, the value is 0.
rgbButtons
Array of buttons. The high-order bit of the byte is set if the corresponding button is down.

Remarks

You must prepare the device for mouse-style access by calling the IDirectInputDevice8::SetDataFormat method, passing the c_dfDIMouse2 global data format variable.

The mouse is a relative-axis device, so the absolute axis positions for mouse axes are accumulated relative motion. Therefore, the value of the absolute axis position is not meaningful except in comparison with other absolute axis positions.

If an axis is in relative mode, the appropriate member contains the change in position. If it is in absolute mode, the member contains the absolute axis position.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

DIMOUSESTATE


DIOBJECTDATAFORMAT Structure

Describes a device object's data format for use with the IDirectInputDevice8::SetDataFormat method.

Syntax

typedef struct DIOBJECTDATAFORMAT {
    const GUID * pguid;
    DWORD        dwOfs;
    DWORD        dwType;
    DWORD        dwFlags;
} DIOBJECTDATAFORMAT, *LPDIOBJECTDATAFORMAT;

typedef const DIOBJECTDATAFORMAT *LPCDIOBJECTDATAFORMAT;

Members

pguid
Unique identifier for the axis, button, or other input source. When requesting a data format, making this member NULL indicates that any type of object is permissible.
dwOfs
Offset within the data packet where the data for the input source is stored. This value must be a multiple of 4 for DWORD size data, such as axes. It can be byte-aligned for buttons.
dwType
Device type that describes the object. It is a combination of the following flags describing the object type (axis, button, and so forth) and containing the object-instance number in the middle 16 bits. When requesting a data format, the instance portion must be set to DIDFT_ANYINSTANCE to indicate that any instance is permissible, or to DIDFT_MAKEINSTANCE(n) to restrict the request to instance n. See the examples under Remarks.
DIDFT_ABSAXIS
The object selected by the IDirectInputDevice8::SetDataFormat method must be an absolute axis.
DIDFT_AXIS
The object selected by the IDirectInputDevice8::SetDataFormat method must be an absolute or relative axis.
DIDFT_BUTTON
The object selected by the IDirectInputDevice8::SetDataFormat method must be a push button or a toggle button.
DIDFT_FFACTUATOR
The object selected by the IDirectInputDevice8::SetDataFormat method must contain a force-feedback actuator; in other words, it must be possible to apply forces to the object.
DIDFT_FFEFFECTTRIGGER
The object selected by the IDirectInputDevice8::SetDataFormat method must be a valid force-feedback effect trigger.
DIDFT_POV
The object selected by the IDirectInputDevice8::SetDataFormat method must be a point-of-view controller.
DIDFT_PSHBUTTON
The object selected by the IDirectInputDevice8::SetDataFormat method must be a push button.
DIDFT_RELAXIS
The object selected by IDirectInputDevice8::SetDataFormat must be a relative axis.
DIDFT_TGLBUTTON
The object selected by IDirectInputDevice8::SetDataFormat must be a toggle button.
DIDFT_VENDORDEFINED
The object selected by IDirectInputDevice8::SetDataFormat must be of a type defined by the manufacturer.
dwFlags
Zero or more of the following values:
DIDOI_ASPECTACCEL
The object selected by IDirectInputDevice8::SetDataFormat must report acceleration information.
DIDOI_ASPECTFORCE
The object selected by IDirectInputDevice8::SetDataFormat must report force information.
DIDOI_ASPECTPOSITION
The object selected by IDirectInputDevice8::SetDataFormat must report position information.
DIDOI_ASPECTVELOCITY
The object selected by IDirectInputDevice8::SetDataFormat must report velocity information.

Remarks

A data format is made up of several DIOBJECTDATAFORMAT structures, one for each object (axis, button, and so on). An array of these structures is contained in the DIDATAFORMAT structure that is passed to IDirectInputDevice8::SetDataFormat. An application typically does not need to create an array of DIOBJECTDATAFORMAT structures; rather, it can use one of the predefined data formats, c_dfDIMouse, c_dfDIMouse2, c_dfDIKeyboard, c_dfDIJoystick, or c_dfDIJoystick2, which have predefined settings for DIOBJECTDATAFORMAT.

The following object data format specifies that Microsoft DirectInput should choose the first available axis and report its value in the DWORD at offset 4 in the device data.

DIOBJECTDATAFORMAT dfAnyAxis = {
    0,                              // Wildcard
    4,                              // Offset
    DIDFT_AXIS | DIDFT_ANYINSTANCE, // Any axis is okay.
    0,                              // Ignore aspect
};

The following object data format specifies that the x-axis of the device should be stored in the DWORD at offset 12 in the device data. If the device has more than one x-axis, the first available one should be selected.

DIOBJECTDATAFORMAT dfAnyXAxis = {
    &GUID_XAxis,                    // Must be an x-axis
    12,                             // Offset
    DIDFT_AXIS | DIDFT_ANYINSTANCE, // Any x-axis is okay.
    0,                              // Ignore aspect
};

The following object data format specifies that DirectInput should choose the first available button and report its value in the high bit of the byte at offset 16 in the device data.

DIOBJECTDATAFORMAT dfAnyButton = {
    0,                                // Wildcard
    16,                               // Offset
    DIDFT_BUTTON | DIDFT_ANYINSTANCE, // Any button is okay.
    0,                                // Ignore aspect
};

The following object data format specifies that button 0 of the device should be reported as the high bit of the byte stored at offset 18 in the device data.

If the device does not have a button 0, the attempt to set this data format fails.

DIOBJECTDATAFORMAT dfButton0 = {
    0,                                    // Wildcard
    18,                                   // Offset
    DIDFT_BUTTON | DIDFT_MAKEINSTANCE(0), // Button zero
    0,                                    // Ignore aspect
};

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98


DIPERIODIC Structure

Contains type-specific information for effects that are marked as DIEFT_PERIODIC.

The structure describes a periodic effect.

A pointer to a single DIPERIODIC structure for an effect is passed in the lpvTypeSpecificParams member of the DIEFFECT structure.

Syntax

typedef struct DIPERIODIC {
    DWORD dwMagnitude;
    LONG  lOffset;
    DWORD dwPhase;
    DWORD dwPeriod;
} DIPERIODIC, *LPDIPERIODIC;

typedef const DIPERIODIC *LPCDIPERIODIC;

Members

dwMagnitude
Magnitude of the effect, in the range from 0 through 10,000. If an envelope is applied to this effect, the value represents the magnitude of the sustain. If no envelope is applied, the value represents the amplitude of the entire effect.
lOffset
Offset of the effect. The range of forces generated by the effect is lOffset minus dwMagnitude to lOffset plus dwMagnitude. The value of the lOffset member is also the baseline for any envelope that is applied to the effect.
dwPhase
Position in the cycle of the periodic effect at which playback begins, in the range from 0 through 35,999. See Remarks.
dwPeriod
Period of the effect, in microseconds.

Remarks

A device driver cannot provide support for all values in the dwPhase member. In this case, the value is rounded off to the nearest supported value.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98


DIPROPCPOINTS Structure

Sets calibration points for the current instance.

Syntax

typedef struct DIPROPCPOINTS {
    DIPROPHEADER diph;
    DWORD  dwCPointsNum;
    CPOINT cp[MAXCPOINTSNUM];
} DIPROPCPOINTS, *LPDIPROPCPOINTS;

typedef const DIPROPCPOINTS *LPCDIPROPCPOINTS;

Members

diph
DIPROPHEADER structure.
dwCPointsNum
Number of stored calibration points. No more than 8 calibration points may be used.
cp
Array of calibration points.

Remarks

The diph member must be initialized as follows:
Member | Value
dwSize | sizeof(DIPROPCPOINTS)
dwHeaderSize | sizeof(DIPROPHEADER)
dwObj If the dwHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved.

If the dwHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. For example, if the c_dfDIMouse data format is selected, it must be one of the DIMOFS_* values.

If the dwHow member is DIPH_BYUSAGE, the device must be a Human Interface Device (HID). The device object will be identified by the HID usage page and usage values in packed form.

This property can be applied only to individual device objects, so DIPH_DEVICE cannot be used.

dwHow | Specifies how the dwObj member should be interpreted. See the preceding description of the dwObj member for details.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98


DIPROPDWORD Structure

Used to access DWORD properties.

Syntax

typedef struct DIPROPDWORD {
    DIPROPHEADER diph;
    DWORD        dwData;
} DIPROPDWORD, *LPDIPROPDWORD;

typedef const DIPROPDWORD *LPCDIPROPDWORD;

Members

diph
DIPROPHEADER structure.
dwData
Property-specific value being set or retrieved.

Remarks

The diph member must be initialized as follows:
Member | Value
dwSize | sizeof(DIPROPDWORD)
dwHeaderSize | sizeof(DIPROPHEADER)
dwObj If the dwHow member is DIPH_DEVICE, this member must be 0.

If the dwHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved.

If the dwHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. For example, if the c_dfDIMouse data format is selected, it must be one of the DIMOFS_* values.

If the dwHow member is DIPH_BYUSAGE, the device must be a Human Interface Device (HID). The device object will be identified by the HID usage page and usage values in packed form.

dwHow | Specifies how the dwObj member should be interpreted. See the preceding description of the dwObj member for details.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

IDirectInputDevice8::GetProperty, IDirectInputDevice8::SetProperty


DIPROPGUIDANDPATH Structure

Used to access properties whose values represent a globally unique identifier (GUID) and a path.

Syntax

typedef struct DIPROPGUIDANDPATH {
    DIPROPHEADER diph;
    GUID         guidClass;
    WCHAR        wszPath[MAX_PATH];
} DIPROPGUIDANDPATH, *LPDIPROPGUIDANDPATH;

typedef const DIPROPGUIDANDPATH *LPCDIPROPGUIDANDPATH;

Members

diph
DIPROPHEADER structure.
guidClass
Class GUID for the object.
wszPath
Returned path for the object. This is a Unicode string.

Remarks

The diph member must be initialized as follows:
Member | Value
dwSize | sizeof(DIPROPGUIDANDPATH).
dwHeaderSize | sizeof(DIPROPHEADER).
dwObj | For this structure, this member must be set to 0.
dwHow | Specifies how the dwObj member should be interpreted. For this structure, dwHow should be DIPH_DEVICE.

The DIPROP_GUIDANDPATH property associated with the DIPROPGUIDANDPATH structure enables advanced applications to perform operations on a Human Interface Device (HID) that are not supported by Microsoft DirectInput.

The application calls the IDirectInputDevice8::GetProperty method with DIPROP_GUIDANDPATH as the rguidProp parameter. The class GUID of the device is returned in the guidClass member of the DIPROPGUIDANDPATH structure, and the device interface path is returned in the wszPath member. The application can then call the CreateFile function on this path to access the device directly.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98


DIPROPHEADER Structure

Serves as a header for all property structures.

Syntax

typedef struct DIPROPHEADER {
    DWORD    dwSize;
    DWORD    dwHeaderSize;
    DWORD    dwObj;
    DWORD    dwHow;
} DIPROPHEADER, *LPDIPROPHEADER;

typedef const DIPROPHEADER *LPCDIPROPHEADER;

Members

dwSize
Size of the enclosing structure. This member must be initialized before the structure is used.
dwHeaderSize
Size of the DIPROPHEADER structure.
dwObj
Object for which the property is to be accessed. The value set for this member depends on the value specified in the dwHow member.
dwHow
Value that specifies how the dwObj member should be interpreted. This value can be one of the following:
DIPH_DEVICE
The dwObj member must be 0.
DIPH_BYOFFSET
The dwObj member is the offset into the current data format of the object whose property is being accessed.
DIPH_BYUSAGE
The dwObj member is the HID usage page and usage values in packed form.
DIPH_BYID
The dwObj member is the object type/instance identifier. This identifier is returned in the dwType member of the DIDEVICEOBJECTINSTANCE structure returned from a previous call to the IDirectInputDevice8::EnumObjects member.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98


DIPROPPOINTER Structure

Used in setting and retrieving data values of type UINT_PTR. This is typically a value associated with an application-specific action associated with a device object in an action map, but can also be a function pointer.

Syntax

typedef struct DIPROPPOINTER {
    DIPROPHEADER diph;
    UINT_PTR     uData;
} DIPROPPOINTER, *LPDIPROPPOINTER;

typedef const DIPROPPOINTER *LPCDIPROPPOINTER;

Members

diph
DIPROPHEADER structure.
uData
Application-defined value of type UINT_PTR, which represents the uAppData value (from an action map) that is associated with a device control.

Remarks

The diph member must be initialized as follows:
Member | Value
dwSize | sizeof(DIPROPPOINTER)
dwHeaderSize | sizeof(DIPROPHEADER)
dwObj If the dwHow member is DIPH_DEVICE, this member must be 0.

If the dwHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved.

If the dwHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. For example, if the c_dfDIMouse data format is selected, it must be one of the DIMOFS_* values.

If the dwHow member is DIPH_BYUSAGE, the device must be a Human Interface Device (HID). The device object will be identified by the HID usage page and usage values in packed form.

dwHow | Specifies how the dwObj member should be interpreted. See the preceding description of the dwObj member for details.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98


DIPROPRANGE Structure

Contains information about the range of an object within a device. This structure is used with the DIPROP_RANGE flag set in the IDirectInputDevice8::GetProperty and IDirectInputDevice8::SetProperty methods.

Syntax

typedef struct DIPROPRANGE {
    DIPROPHEADER diph;
    LONG         lMin;
    LONG         lMax;
} DIPROPRANGE, *LPDIPROPRANGE;

typedef const DIPROPRANGE *LPCDIPROPRANGE;

Members

diph
DIPROPHEADER structure.
lMin
Lower limit of the range. If the range of the device is unrestricted, this value is DIPROPRANGE_NOMIN when the IDirectInputDevice8::GetProperty method returns.
lMax
Upper limit of the range. If the range of the device is unrestricted, this value is DIPROPRANGE_NOMAX when the IDirectInputDevice8::GetProperty method returns.

Remarks

The diph member must be initialized as follows:
Member | Value
dwSize | sizeof(DIPROPRANGE)
dwHeaderSize | sizeof(DIPROPHEADER)
dwObj If the dwHow member is DIPH_DEVICE, this member must be 0.

If the dwHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved.

If the dwHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. For example, if the c_dfDIMouse data format is selected, it must be one of the DIMOFS_* values.Identifier of the object whose property is being retrieved or set.

If the dwHow member is DIPH_BYUSAGE, the device must be a Human Interface Device (HID). The device object will be identified by the HID usage page and usage values in packed form.

dwHow | Specifies how the dwObj member should be interpreted. See the preceding description of the dwObj member for details.

The range values for devices whose ranges are unrestricted wraparound.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98

See Also

IDirectInputDevice8::GetProperty, IDirectInputDevice8::SetProperty


DIPROPSTRING Structure

Gets and retrieves properties as strings.

Syntax

typedef struct DIPROPSTRING {
    DIPROPHEADER diph;
    WCHAR        wsz[MAX_PATH];
} DIPROPSTRING, * LPDIPROPSTRING;;

typedef const DIPROPSTRING *LPCDIPROPSTRING;

Members

diph
DIPROPHEADER structure.
wsz
Unicode string that specifies or retrieves the property.

Remarks

The diph member must be initialized as follows:
Member | Value
dwSize | sizeof(DIPROPSTRING)
dwHeaderSize | sizeof(DIPROPHEADER)
dwObj If the dwHow member is DIPH_DEVICE, this member must be 0.

If the dwHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved.

If the dwHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. For example, if the c_dfDIMouse data format is selected, it must be one of the DIMOFS_* values.

If the dwHow member is DIPH_BYUSAGE, the device must be a Human Interface Device (HID). The device object will be identified by the HID usage page and usage values in packed form.

dwHow | Specifies how the dwObj member should be interpreted. See the preceding description of the dwObj member for details.

The DIPROP_INSTANCENAME and DIPROP_PRODUCTNAME properties associated with the DIPROPSTRING structure enable advanced applications to perform operations on a Human Interface Device (HID) that are not supported by Microsoft DirectInput.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98


DIRAMPFORCE Structure

Contains type-specific information for effects that are marked as DIEFT_RAMPFORCE. The structure describes a ramp force effect.

A pointer to a single DIRAMPFORCE structure for an effect is passed in the lpvTypeSpecificParams member of the DIEFFECT structure.

Syntax

typedef struct DIRAMPFORCE {
    LONG lStart;
    LONG lEnd;
} DIRAMPFORCE, *LPDIRAMPFORCE;

typedef const DIRAMPFORCE *LPCDIRAMPFORCE;

Members

lStart
Magnitude at the start of the effect, in the range from –10,000 through 10,000.
lEnd
Magnitude at the end of the effect, in the range from –10,000 through 10,000.

Remarks

The dwDuration for a ramp force effect cannot be INFINITE.

Structure Information

Header | dinput.h
Minimum operating systems | Windows 98


Device Constants
Microsoft DirectX 9.0 SDK Update (October 2004)

Device Constants

This section is a reference for constants used to interpret data for keys, buttons, and axes.

Constants

  • DirectInput and Japanese Keyboards
  • Joystick Device Constants
  • Keyboard Device
  • Mouse Device


DirectInput and Japanese Keyboards
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectInput and Japanese Keyboards

This topic lists keys that are available on Japanese keyboards but not on standard U.S. keyboards, as well as keys that are available on U.S. keyboards but not on the various Japanese keyboards.

On Microsoft Windows 2000 and with some keyboards (such as the NEC PC-98) using other operating systems, the DIK_CAPSLOCK, DIK_KANJI, and DIK_KANA keys are toggle buttons and not push buttons. These generate a down event when first pressed, then generate an up event when pressed a second time.

Japanese Keyboard | Additional keys | Missing keys
DOS/V 106, NEC PC-98 106 | DIK_AT, DIK_CIRCUMFLEX, DIK_COLON, DIK_CONVERT, DIK_KANA, DIK_KANJI, DIK_NOCONVERT, DIK_YEN | DIK_APOSTROPHE, DIK_EQUALS, DIK_GRAVE
NEC PC-98 | DIK_AT, DIK_CIRCUMFLEX, DIK_COLON, DIK_F13, DIK_F14, DIK_F15, DIK_KANA, DIK_KANJI, DIK_NOCONVERT, DIK_NUMPADCOMMA, DIK_NUMPADEQUALS, DIK_STOP, DIK_UNDERLINE, DIK_YEN | DIK_APOSTROPHE, DIK_BACKSLASH, DIK_EQUALS, DIK_GRAVE, DIK_NUMLOCK, DIK_NUMPADENTER, DIK_RCONTROL, DIK_RMENU, DIK_RSHIFT, DIK_SCROLL
AX | DIK_AX, DIK_CONVERT, DIK_KANJI, DIK_NOCONVERT, DIK_YEN | DIK_RCONTROL, DIK_RMENU
J-3100 | DIK_KANA, DIK_KANJI, DIK_NOLABEL, DIK_YEN | DIK_RCONTROL, DIK_RMENU


Joystick Device Constants
Microsoft DirectX 9.0 SDK Update (October 2004)

Joystick Device Constants

Joystick device constants represent offsets within a joystick device's data packet, the DIJOYSTATE structure. The data at a given offset is associated with a device object; that is, a button or axis. Typically, these values are used in the dwOfs member of the DIDEVICEOBJECTDATA, DIOBJECTDATAFORMAT or DIDEVICEOBJECTINSTANCE structures.

The following macros return a constant indicating the offset of the data for a particular button or axis relative to the beginning of the DIJOYSTATE structure.

Constant | Device object
DIJOFS_BUTTON0 to DIJOFS_BUTTON31 or DIJOFS_BUTTON(n) | Button
DIJOFS_POV(n) | Point-of-view indicator
DIJOFS_RX | X-axis rotation
DIJOFS_RY | Y-axis rotation
DIJOFS_RZ | Z-axis rotation (rudder)
DIJOFS_X | X-axis
DIJOFS_Y | Y-axis
DIJOFS_Z | Z-axis
DIJOFS_SLIDER(n) | Slider axis


Keyboard Device Enumerated Type

Keyboard device constants, defined in Dinput.h, represent offsets within a keyboard device's data packet, a 256-byte array.

Syntax

typedef enum {
    DIK_0,
    DIK_1,
    DIK_2,
    DIK_3,
    DIK_4,
    DIK_5,
    DIK_6,
    DIK_7,
    DIK_8,
    DIK_9,
    DIK_A,
    DIK_ABNT_C1,
    DIK_ABNT_C2,
    DIK_ADD,
    DIK_APOSTROPHE,
    DIK_APPS,
    DIK_AT,
    DIK_AX,
    DIK_B,
    DIK_BACK,
    DIK_BACKSLASH,
    DIK_C,
    DIK_CALCULATOR,
    DIK_CAPITAL,
    DIK_COLON,
    DIK_COMMA,
    DIK_CONVERT,
    DIK_D,
    DIK_DECIMAL,
    DIK_DELETE,
    DIK_DIVIDE,
    DIK_DOWN,
    DIK_E,
    DIK_END,
    DIK_EQUALS,
    DIK_ESCAPE,
    DIK_F,
    DIK_F1,
    DIK_F2,
    DIK_F3,
    DIK_F4,
    DIK_F5,
    DIK_F6,
    DIK_F7,
    DIK_F8,
    DIK_F9,
    DIK_F10,
    DIK_F11,
    DIK_F12,
    DIK_F13,
    DIK_F14,
    DIK_F15,
    DIK_G,
    DIK_GRAVE,
    DIK_H,
    DIK_HOME,
    DIK_I,
    DIK_INSERT,
    DIK_J,
    DIK_K,
    DIK_KANA,
    DIK_KANJI,
    DIK_L,
    DIK_LBRACKET,
    DIK_LCONTROL,
    DIK_LEFT,
    DIK_LMENU,
    DIK_LSHIFT,
    DIK_LWIN,
    DIK_M,
    DIK_MAIL,
    DIK_MEDIASELECT,
    DIK_MEDIASTOP,
    DIK_MINUS,
    DIK_MULTIPLY,
    DIK_MUTE,
    DIK_MYCOMPUTER,
    DIK_N,
    DIK_NEXT,
    DIK_NEXTTRACK,
    DIK_NOCONVERT,
    DIK_NUMLOCK,
    DIK_NUMPAD0,
    DIK_NUMPAD1,
    DIK_NUMPAD2,
    DIK_NUMPAD3,
    DIK_NUMPAD4,
    DIK_NUMPAD5,
    DIK_NUMPAD6,
    DIK_NUMPAD7,
    DIK_NUMPAD8,
    DIK_NUMPAD9,
    DIK_NUMPADCOMMA,
    DIK_NUMPADENTER,
    DIK_NUMPADEQUALS,
    DIK_O,
    DIK_OEM_102,
    DIK_P,
    DIK_PAUSE,
    DIK_PERIOD,
    DIK_PLAYPAUSE,
    DIK_POWER,
    DIK_PREVTRACK,
    DIK_PRIOR,
    DIK_Q,
    DIK_R,
    DIK_RBRACKET,
    DIK_RCONTROL,
    DIK_RETURN,
    DIK_RIGHT,
    DIK_RMENU,
    DIK_RSHIFT,
    DIK_RWIN,
    DIK_S,
    DIK_SCROLL,
    DIK_SEMICOLON,
    DIK_SLASH,
    DIK_SLEEP,
    DIK_SPACE,
    DIK_STOP,
    DIK_SUBTRACT,
    DIK_SYSRQ,
    DIK_T,
    DIK_TAB,
    DIK_U,
    DIK_UNDERLINE,
    DIK_UNLABELED,
    DIK_UP,
    DIK_V,
    DIK_VOLUMEDOWN,
    DIK_VOLUMEUP,
    DIK_W,
    DIK_WAKE,
    DIK_WEBBACK,
    DIK_WEBFAVORITES,
    DIK_WEBFORWARD,
    DIK_WEBHOME,
    DIK_WEBREFRESH,
    DIK_WEBSEARCH,
    DIK_WEBSTOP,
    DIK_X,
    DIK_Y,
    DIK_YEN,
    DIK_Z
} Keyboard Device;

Constants

DIK_0

On main keyboard

DIK_1

On main keyboard

DIK_2

On main keyboard

DIK_3

On main keyboard

DIK_4

On main keyboard

DIK_5

On main keyboard

DIK_6

On main keyboard

DIK_7

On main keyboard

DIK_8

On main keyboard

DIK_9

On main keyboard

DIK_A

DIK_ABNT_C1

On numeric pad of Brazilian keyboards

DIK_ABNT_C2

On numeric pad of Brazilian keyboards

DIK_ADD

PLUS SIGN (+) on numeric keypad

DIK_APOSTROPHE

DIK_APPS

Application key

DIK_AT

On Japanese keyboard

DIK_AX

On Japanese keyboard

DIK_B

DIK_BACK

BACKSPACE

DIK_BACKSLASH

DIK_C

DIK_CALCULATOR

DIK_CAPITAL

CAPS LOCK

DIK_COLON

On Japanese keyboard

DIK_COMMA

DIK_CONVERT

On Japanese keyboard

DIK_D

DIK_DECIMAL

PERIOD (decimal point) on numeric keypad

DIK_DELETE

DIK_DIVIDE

Forward slash (/) on numeric keypad

DIK_DOWN

DOWN ARROW

DIK_E

DIK_END

DIK_EQUALS

On main keyboard

DIK_ESCAPE

DIK_F

DIK_F1

DIK_F2

DIK_F3

DIK_F4

DIK_F5

DIK_F6

DIK_F7

DIK_F8

DIK_F9

DIK_F10

DIK_F11

DIK_F12

DIK_F13

On NEC PC-98 Japanese keyboard

DIK_F14

On NEC PC-98 Japanese keyboard

DIK_F15

On NEC PC-98 Japanese keyboard

DIK_G

DIK_GRAVE

Grave accent (`)

DIK_H

DIK_HOME

DIK_I

DIK_INSERT

DIK_J

DIK_K

DIK_KANA

On Japanese keyboard

DIK_KANJI

On Japanese keyboard

DIK_L

DIK_LBRACKET

Left square bracket [

DIK_LCONTROL

Left CTRL

DIK_LEFT

LEFT ARROW

DIK_LMENU

Left ALT

DIK_LSHIFT

Left SHIFT

DIK_LWIN

Left Microsoft Windows logo key

DIK_M

DIK_MAIL

DIK_MEDIASELECT

Media Select key, which displays a selection of supported media players on the system

DIK_MEDIASTOP

DIK_MINUS

On main keyboard

DIK_MULTIPLY

Asterisk (*) on numeric keypad

DIK_MUTE

DIK_MYCOMPUTER

DIK_N

DIK_NEXT

PAGE DOWN

DIK_NEXTTRACK

Next track

DIK_NOCONVERT

On Japanese keyboard

DIK_NUMLOCK

DIK_NUMPAD0

DIK_NUMPAD1

DIK_NUMPAD2

DIK_NUMPAD3

DIK_NUMPAD4

DIK_NUMPAD5

DIK_NUMPAD6

DIK_NUMPAD7

DIK_NUMPAD8

DIK_NUMPAD9

DIK_NUMPADCOMMA

On numeric keypad of NEC PC-98 Japanese keyboard

DIK_NUMPADENTER

DIK_NUMPADEQUALS

On numeric keypad of NEC PC-98 Japanese keyboard

DIK_O

DIK_OEM_102

On British and German keyboards

DIK_P

DIK_PAUSE

DIK_PERIOD

On main keyboard

DIK_PLAYPAUSE

DIK_POWER

DIK_PREVTRACK

Previous track; circumflex on Japanese keyboard

DIK_PRIOR

PAGE UP

DIK_Q

DIK_R

DIK_RBRACKET

Right square bracket ]

DIK_RCONTROL

Right CTRL

DIK_RETURN

ENTER on main keyboard

DIK_RIGHT

RIGHT ARROW

DIK_RMENU

Right ALT

DIK_RSHIFT

Right SHIFT

DIK_RWIN

Right Windows logo key

DIK_S

DIK_SCROLL

SCROLL LOCK

DIK_SEMICOLON

DIK_SLASH

Forward slash (/) on main keyboard

DIK_SLEEP

DIK_SPACE

SPACEBAR

DIK_STOP

On NEC PC-98 Japanese keyboard

DIK_SUBTRACT

MINUS SIGN (-) on numeric keypad

DIK_SYSRQ

DIK_T

DIK_TAB

DIK_U

DIK_UNDERLINE

On NEC PC-98 Japanese keyboard

DIK_UNLABELED

On Japanese keyboard

DIK_UP

UP ARROW

DIK_V

DIK_VOLUMEDOWN

DIK_VOLUMEUP

DIK_W

DIK_WAKE

DIK_WEBBACK

DIK_WEBFAVORITES

Displays the Microsoft Internet Explorer Favorites list, the Windows Favorites folder, or the Netscape Bookmarks list.

DIK_WEBFORWARD

DIK_WEBHOME

DIK_WEBREFRESH

DIK_WEBSEARCH

DIK_WEBSTOP

DIK_X

DIK_Y

DIK_YEN

On Japanese keyboard

DIK_Z

Remarks

The following alternate names are available:

Alternate name | Regular name | Note
DIK_BACKSPACE | DIK_BACK | BACKSPACE
DIK_CAPSLOCK | DIK_CAPITAL | CAPS LOCK
DIK_CIRCUMFLEX | DIK_PREVTRACK | On Japanese keyboard
DIK_DOWNARROW | DIK_DOWN | On arrow keypad
DIK_LALT | DIK_LMENU | Left ALT
DIK_LEFTARROW | DIK_LEFT | On arrow keypad
DIK_NUMPADMINUS | DIK__SUBTRACT | MINUS SIGN (-) on numeric keypad
DIK_NUMPADPERIOD | DIK_DECIMAL | PERIOD (decimal point) on numeric keypad
DIK_NUMPADPLUS | DIK_ADD | PLUS SIGN (+) on numeric keypad
DIK_NUMPADSLASH | DIK__DIVIDE | Forward slash (/) on numeric keypad
DIK_NUMPADSTAR | DIK_MULTIPLY | Asterisk (*) on numeric keypad
DIK_PGDN | DIK_NEXT | On arrow keypad
DIK_PGUP | DIK_PRIOR | On arrow keypad
DIK_RALT | DIK_RMENU | Right ALT
DIK_RIGHTARROW | DIK_RIGHT | On arrow keypad
DIK_UPARROW | DIK_UP | On arrow keypad

For information about Japanese keyboards, see DirectInput and Japanese Keyboards.

The data at a given offset is associated with a keyboard key. Typically, these values are used in the dwOfs member of the DIDEVICEOBJECTDATA, DIOBJECTDATAFORMAT or DIDEVICEOBJECTINSTANCE structures, or as indices when accessing data within the array using array notation.

Enumerated Type Information

Minimum operating systems Windows 98, Windows NT 2000, Windows XP


Mouse Device Enumerated Type

Mouse device constants, defined in Dinput.h, represent offsets within a mouse device's data packet, the DIMOUSESTATE or DIMOUSESTATE2 structure.

Syntax

typedef enum {
    DIMOFS_BUTTON0,
    DIMOFS_BUTTON1,
    DIMOFS_BUTTON2,
    DIMOFS_BUTTON3,
    DIMOFS_BUTTON4,
    DIMOFS_BUTTON5,
    DIMOFS_BUTTON6,
    DIMOFS_BUTTON7,
    DIMOFS_X,
    DIMOFS_Y,
    DIMOFS_Z
} Mouse Device;

Constants

DIMOFS_BUTTON0

DIMOFS_BUTTON1

DIMOFS_BUTTON2

DIMOFS_BUTTON3

DIMOFS_BUTTON4

DIMOUSESTATE2 only

DIMOFS_BUTTON5

DIMOUSESTATE2 only

DIMOFS_BUTTON6

DIMOUSESTATE2 only

DIMOFS_BUTTON7

DIMOUSESTATE2 only

DIMOFS_X

DIMOFS_Y

DIMOFS_Z

Remarks

The data at a given offset is associated with a device object (button or axis). Typically, these values are used in the dwOfs member of the DIDEVICEOBJECTDATA, DIOBJECTDATAFORMAT or DIDEVICEOBJECTINSTANCE structures.

Enumerated Type Information

Minimum operating systems Windows 98, Windows NT 2000, Windows XP


Action Mapping Constants
Microsoft DirectX 9.0 SDK Update (October 2004)

Action Mapping Constants

This section is a reference to the constants defined in Dinput.h for application genres and controls mapped to actions within each genre.

The control constants, such as DIAXIS_FIGHTINGH_MOVE, are used in the dwSemantic member of the DIACTION structure to associate the control with an action in the application.

The constants for the genres, such as DIVIRTUAL_FIGHTING_HAND2HAND, are used in the dwGenre member of the DIACTIONFORMAT structure.

Action mapping constants are provided for application genres in the following categories.

  • Action Genres
  • Arcade Genres
  • CAD Genres
  • Control Genres
  • Driving Genres
  • Flight Genres
  • Sports Genres
  • Strategy Genres

The dwSemantic member of the DIACTION structure member can map the action to a particular device object rather than a virtual control. Device object constants are provided in the following categories.

Constants

  • Any-Control
  • DirectPlay Voice Mapping
  • Keyboard Mapping
  • Mouse Mapping


Action Genres
Microsoft DirectX 9.0 SDK Update (October 2004)

Action Genres

The following genres contain controls for fighting and action games.

Constants

  • Hand-to-Hand
  • Shooting
  • Third-Person Action


Hand-to-Hand
Microsoft DirectX 9.0 SDK Update (October 2004)

Hand-to-Hand

The DIVIRTUAL_FIGHTING_HAND2HAND genre contains controls for a first-person fighting game without guns.

Priority 1 Controls
DIAXIS_FIGHTINGH_LATERAL
DIAXIS_FIGHTINGH_MOVE
DIBUTTON_FIGHTINGH_BLOCK
DIBUTTON_FIGHTINGH_CROUCH
DIBUTTON_FIGHTINGH_JUMP
DIBUTTON_FIGHTINGH_KICK
DIBUTTON_FIGHTINGH_MENU
DIBUTTON_FIGHTINGH_PUNCH
DIBUTTON_FIGHTINGH_SPECIAL1
DIBUTTON_FIGHTINGH_SPECIAL2

Priority 2 Controls
DIAXIS_FIGHTINGH_ROTATE
DIBUTTON_FIGHTINGH_BACKWARD_LINK
DIBUTTON_FIGHTINGH_DEVICE
DIBUTTON_FIGHTINGH_DISPLAY
DIBUTTON_FIGHTINGH_DODGE
DIBUTTON_FIGHTINGH_FORWARD_LINK
DIBUTTON_FIGHTINGH_LEFT_LINK
DIBUTTON_FIGHTINGH_RIGHT_LINK
DIBUTTON_FIGHTINGH_PAUSE
DIBUTTON_FIGHTINGH_SELECT
DIHATSWITCH_FIGHTINGH_SLIDE


Shooting
Microsoft DirectX 9.0 SDK Update (October 2004)

Shooting

The DIVIRTUAL_FIGHTING_FPS genre contains controls for a first-person fighting game with guns.

Priority 1 Controls
DIAXIS_FPS_LOOKUPDOWN
DIAXIS_FPS_MOVE
DIAXIS_FPS_ROTATE
DIBUTTON_FPS_APPLY
DIBUTTON_FPS_CROUCH
DIBUTTON_FPS_FIRE
DIBUTTON_FPS_JUMP
DIBUTTON_FPS_MENU
DIBUTTON_FPS_SELECT
DIBUTTON_FPS_STRAFE
DIBUTTON_FPS_WEAPONS

Priority 2 Controls
DIAXIS_FPS_SIDESTEP
DIBUTTON_FPS_BACKWARD_LINK
DIBUTTON_FPS_DEVICE
DIBUTTON_FPS_DISPLAY
DIBUTTON_FPS_DODGE
DIBUTTON_FPS_FIRESECONDARY
DIBUTTON_FPS_FORWARD_LINK
DIBUTTON_FPS_GLANCE_DOWN_LINK
DIBUTTON_FPS_GLANCE_UP_LINK
DIBUTTON_FPS_GLANCEL
DIBUTTON_FPS_GLANCER
DIBUTTON_FPS_PAUSE
DIBUTTON_FPS_ROTATE_LEFT_LINK
DIBUTTON_FPS_ROTATE_RIGHT_LINK
DIHATSWITCH_FPS_GLANCE


Third-Person Action
Microsoft DirectX 9.0 SDK Update (October 2004)

Third-Person Action

The DIVIRTUAL_FIGHTING_THIRDPERSON genre contains controls for a third-person action game.

Priority 1 Controls
DIAXIS_TPS_MOVE
DIAXIS_TPS_TURN
DIBUTTON_TPS_ACTION
DIBUTTON_TPS_JUMP
DIBUTTON_TPS_MENU
DIBUTTON_TPS_RUN
DIBUTTON_TPS_SELECT
DIBUTTON_TPS_USE

Priority 2 Controls
DIAXIS_TPS_STEP
DIBUTTON_TPS_BACKWARD_LINK
DIBUTTON_TPS_DEVICE
DIBUTTON_TPS_DODGE
DIBUTTON_TPS_FORWARD_LINK
DIBUTTON_TPS_GLANCE_DOWN_LINK
DIBUTTON_TPS_GLANCE_LEFT_LINK
DIBUTTON_TPS_GLANCE_RIGHT_LINK
DIBUTTON_TPS_GLANCE_UP_LINK
DIBUTTON_TPS_INVENTORY
DIBUTTON_TPS_PAUSE
DIBUTTON_TPS_STEPLEFT
DIBUTTON_TPS_STEPRIGHT
DIBUTTON_TPS_TURN_LEFT_LINK
DIBUTTON_TPS_TURN_RIGHT_LINK
DIBUTTON_TPS_VIEW
DIHATSWITCH_TPS_GLANCE


Arcade Genres
Microsoft DirectX 9.0 SDK Update (October 2004)

Arcade Genres

The following genres contain controls for arcade-type games in which the object is to move a figure through a dangerous environment.

Constants

  • Platform
  • Side-to-Side


Platform
Microsoft DirectX 9.0 SDK Update (October 2004)

Platform

The DIVIRTUAL_ARCADE_PLATFORM genre contains controls for an arcade-style game.

Priority 1 Controls
DIAXIS_ARCADEP_LATERAL
DIAXIS_ARCADEP_MOVE
DIBUTTON_ARCADEP_CROUCH
DIBUTTON_ARCADEP_FIRE
DIBUTTON_ARCADEP_JUMP
DIBUTTON_ARCADEP_MENU
DIBUTTON_ARCADEP_SELECT
DIBUTTON_ARCADEP_SPECIAL

Priority 2 Controls
DIBUTTON_ARCADEP_BACK_LINK
DIBUTTON_ARCADEP_DEVICE
DIBUTTON_ARCADEP_FIRESECONDARY
DIBUTTON_ARCADEP_FORWARD_LINK
DIBUTTON_ARCADEP_LEFT_LINK
DIBUTTON_ARCADEP_PAUSE
DIBUTTON_ARCADEP_RIGHT_LINK
DIBUTTON_ARCADEP_VIEW_DOWN_LINK
DIBUTTON_ARCADEP_VIEW_LEFT_LINK
DIBUTTON_ARCADEP_VIEW_RIGHT_LINK
DIBUTTON_ARCADEP_VIEW_UP_LINK
DIHATSWITCH_ARCADEP_VIEW


Side-to-Side
Microsoft DirectX 9.0 SDK Update (October 2004)

Side-to-Side

The DIVIRTUAL_ARCADE_SIDE2SIDE genre contains controls for a two-dimensional arcade-style game.

Priority 1 Controls
DIAXIS_ARCADES_LATERAL
DIAXIS_ARCADES_MOVE
DIBUTTON_ARCADES_ATTACK
DIBUTTON_ARCADES_CARRY
DIBUTTON_ARCADES_MENU
DIBUTTON_ARCADES_SELECT
DIBUTTON_ARCADES_SPECIAL
DIBUTTON_ARCADES_THROW

Priority 2 Controls
DIBUTTON_ARCADES_BACK_LINK
DIBUTTON_ARCADES_DEVICE
DIBUTTON_ARCADES_FORWARD_LINK
DIBUTTON_ARCADES_LEFT_LINK
DIBUTTON_ARCADES_PAUSE
DIBUTTON_ARCADES_RIGHT_LINK
DIBUTTON_ARCADES_VIEW_DOWN_LINK
DIBUTTON_ARCADES_VIEW_LEFT_LINK
DIBUTTON_ARCADES_VIEW_RIGHT_LINK
DIBUTTON_ARCADES_VIEW_UP_LINK
DIHATSWITCH_ARCADES_VIEW


CAD Genres
Microsoft DirectX 9.0 SDK Update (October 2004)

CAD Genres

The following genres contain controls for computer-assisted drafting applications.

Constants

  • 2-D Object
  • 3-D Model
  • 3-D Navigation
  • 3-D Object


2-D Object
Microsoft DirectX 9.0 SDK Update (October 2004)

2-D Object

The DIVIRTUAL_CAD_2DCONTROL genre contains controls to select and move objects in a two-dimensional drafting environment.

Priority 1 Controls
DIAXIS_2DCONTROL_LATERAL
DIAXIS_2DCONTROL_MOVE
DIAXIS_2DCONTROL_INOUT
DIBUTTON_2DCONTROL_MENU
DIBUTTON_2DCONTROL_SELECT
DIBUTTON_2DCONTROL_SPECIAL
DIBUTTON_2DCONTROL_SPECIAL1
DIBUTTON_2DCONTROL_SPECIAL2

Priority 2 Controls
DIAXIS_2DCONTROL_ROTATEZ
DIBUTTON_2DCONTROL_DEVICE
DIBUTTON_2DCONTROL_DISPLAY
DIBUTTON_2DCONTROL_PAUSE
DIHATSWITCH_2DCONTROL_HATSWITCH


3-D Model
Microsoft DirectX 9.0 SDK Update (October 2004)

3-D Model

The DIVIRTUAL_CAD_MODEL genre contains controls for modeling three-dimensional objects.

Priority 1 Controls
DIAXIS_CADM_LATERAL
DIAXIS_CADM_MOVE
DIAXIS_CADM_INOUT
DIBUTTON_CADM_MENU
DIBUTTON_CADM_SELECT
DIBUTTON_CADM_SPECIAL
DIBUTTON_CADM_SPECIAL1
DIBUTTON_CADM_SPECIAL2

Priority 2 Controls
DIAXIS_CADM_ROTATEX
DIAXIS_CADM_ROTATEY
DIAXIS_CADM_ROTATEZ
DIBUTTON_CADM_DEVICE
DIBUTTON_CADM_DISPLAY
DIBUTTON_CADM_PAUSE
DIHATSWITCH_CADM_HATSWITCH


3-D Navigation
Microsoft DirectX 9.0 SDK Update (October 2004)

3-D Navigation

The DIVIRTUAL_CAD_FLYBY genre contains control for fly-through navigation of three-dimensional environments.

Priority 1 Controls
DIAXIS_CADF_LATERAL
DIAXIS_CADF_MOVE
DIAXIS_CADF_INOUT
DIBUTTON_CADF_MENU
DIBUTTON_CADF_SELECT
DIBUTTON_CADF_SPECIAL
DIBUTTON_CADF_SPECIAL1
DIBUTTON_CADF_SPECIAL2

Priority 2 Controls
DIAXIS_CADF_ROTATEX
DIAXIS_CADF_ROTATEY
DIAXIS_CADF_ROTATEZ
DIBUTTON_CADF_DEVICE
DIBUTTON_CADF_DISPLAY
DIBUTTON_CADF_PAUSE
DIHATSWITCH_CADF_HATSWITCH


3-D Object
Microsoft DirectX 9.0 SDK Update (October 2004)

3-D Object

The DIVIRTUAL_CAD_3DCONTROL genre contains controls to select and move objects in a three-dimensional drafting environment.

Priority 1 Controls
DIAXIS_3DCONTROL_LATERAL
DIAXIS_3DCONTROL_MOVE
DIAXIS_3DCONTROL_INOUT
DIBUTTON_3DCONTROL_MENU
DIBUTTON_3DCONTROL_SELECT
DIBUTTON_3DCONTROL_SPECIAL
DIBUTTON_3DCONTROL_SPECIAL1
DIBUTTON_3DCONTROL_SPECIAL2

Priority 2 Controls
DIAXIS_3DCONTROL_ROTATEX
DIAXIS_3DCONTROL_ROTATEY
DIAXIS_3DCONTROL_ROTATEZ
DIBUTTON_3DCONTROL_DEVICE
DIBUTTON_3DCONTROL_DISPLAY
DIBUTTON_3DCONTROL_PAUSE
DIHATSWITCH_3DCONTROL_HATSWITCH


Control Genres
Microsoft DirectX 9.0 SDK Update (October 2004)

Control Genres

The following genres contain controls for use with browsers and remote-control devices.

Constants

  • Browser
  • Remote Control


Browser
Microsoft DirectX 9.0 SDK Update (October 2004)

Browser

The DIVIRTUAL_BROWSER_CONTROL genre contains controls for a browser.

Priority 1 Controls
DIAXIS_BROWSER_LATERAL
DIAXIS_BROWSER_MOVE
DIAXIS_BROWSER_VIEW
DIBUTTON_BROWSER_MENU
DIBUTTON_BROWSER_REFRESH
DIBUTTON_BROWSER_SELECT

Priority 2 Controls
DIBUTTON_BROWSER_DEVICE
DIBUTTON_BROWSER_FAVORITES
DIBUTTON_BROWSER_HISTORY
DIBUTTON_BROWSER_HOME
DIBUTTON_BROWSER_NEXT
DIBUTTON_BROWSER_PAUSE
DIBUTTON_BROWSER_PREVIOUS
DIBUTTON_BROWSER_PRINT
DIBUTTON_BROWSER_SEARCH
DIBUTTON_BROWSER_STOP


Remote Control
Microsoft DirectX 9.0 SDK Update (October 2004)

Remote Control

The DIVIRTUAL_REMOTE_CONTROL genre contains controls for remote-control devices used with equipment such as media players.

Priority 1 Controls
DIAXIS_REMOTE_SLIDER
DIBUTTON_REMOTE_CHANGE
DIBUTTON_REMOTE_CUE
DIBUTTON_REMOTE_MENU
DIBUTTON_REMOTE_MUTE
DIBUTTON_REMOTE_PLAY
DIBUTTON_REMOTE_RECORD
DIBUTTON_REMOTE_REVIEW
DIBUTTON_REMOTE_SELECT

Priority 2 Controls
DIAXIS_REMOTE_SLIDER2
DIBUTTON_REMOTE_ADJUST
DIBUTTON_REMOTE_CABLE
DIBUTTON_REMOTE_CD
DIBUTTON_REMOTE_DEVICE
DIBUTTON_REMOTE_DIGIT0
DIBUTTON_REMOTE_DIGIT1
DIBUTTON_REMOTE_DIGIT2
DIBUTTON_REMOTE_DIGIT3
DIBUTTON_REMOTE_DIGIT4
DIBUTTON_REMOTE_DIGIT5
DIBUTTON_REMOTE_DIGIT6
DIBUTTON_REMOTE_DIGIT7
DIBUTTON_REMOTE_DIGIT8
DIBUTTON_REMOTE_DIGIT9
DIBUTTON_REMOTE_DVD
DIBUTTON_REMOTE_PAUSE
DIBUTTON_REMOTE_TUNER
DIBUTTON_REMOTE_TV
DIBUTTON_REMOTE_VCR


Driving Genres
Microsoft DirectX 9.0 SDK Update (October 2004)

Driving Genres

The following genres are used in games where the players control vehicles in racing or combat.

Constants

  • Combat Racing
  • Mechanical Fighting
  • Racing
  • Tank


Combat Racing
Microsoft DirectX 9.0 SDK Update (October 2004)

Combat Racing

The DIVIRTUAL_DRIVING_COMBAT genre contains controls for a vehicle race game with combat.

Priority 1 Controls
DIAXIS_DRIVINGC_ACCELERATE
DIAXIS_DRIVINGC_BRAKE
DIAXIS_DRIVINGC_STEER
DIBUTTON_DRIVINGC_FIRE
DIBUTTON_DRIVINGC_MENU
DIBUTTON_DRIVINGC_TARGET
DIBUTTON_DRIVINGC_WEAPONS

Priority 2 Controls
DIAXIS_DRIVINGC_ACCEL_AND_BRAKE
DIBUTTON_DRIVINGC_ACCELERATE_LINK
DIBUTTON_DRIVINGC_AIDS
DIBUTTON_DRIVINGC_BRAKE
DIBUTTON_DRIVINGC_DASHBOARD
DIBUTTON_DRIVINGC_DEVICE
DIBUTTON_DRIVINGC_FIRESECONDARY
DIBUTTON_DRIVINGC_GLANCE_LEFT_LINK
DIBUTTON_DRIVINGC_GLANCE_RIGHT_LINK
DIBUTTON_DRIVINGC_PAUSE
DIBUTTON_DRIVINGC_SHIFTDOWN
DIBUTTON_DRIVINGC_SHIFTUP
DIBUTTON_DRIVINGC_STEER_LEFT_LINK
DIBUTTON_DRIVINGC_STEER_RIGHT_LINK
DIHATSWITCH_DRIVINGC_GLANCE


Mechanical Fighting
Microsoft DirectX 9.0 SDK Update (October 2004)

Mechanical Fighting

The DIVIRTUAL_DRIVING_MECHA genre contains controls for a walking vehicle in a mechanized-warfare game.

Priority 1 Controls
DIAXIS_MECHA_ROTATE
DIAXIS_MECHA_STEER
DIAXIS_MECHA_THROTTLE
DIAXIS_MECHA_TORSO
DIBUTTON_MECHA_FIRE
DIBUTTON_MECHA_JUMP
DIBUTTON_MECHA_MENU
DIBUTTON_MECHA_REVERSE
DIBUTTON_MECHA_TARGET
DIBUTTON_MECHA_WEAPONS
DIBUTTON_MECHA_ZOOM

Priority 2 Controls
DIBUTTON_MECHA_BACK_LINK
DIBUTTON_MECHA_CENTER
DIBUTTON_MECHA_DEVICE
DIBUTTON_MECHA_FASTER_LINK
DIBUTTON_MECHA_FIRESECONDARY
DIBUTTON_MECHA_FORWARD_LINK
DIBUTTON_MECHA_LEFT_LINK
DIBUTTON_MECHA_PAUSE
DIBUTTON_MECHA_RIGHT_LINK
DIBUTTON_MECHA_ROTATE_LEFT_LINK
DIBUTTON_MECHA_ROTATE_RIGHT_LINK
DIBUTTON_MECHA_SLOWER_LINK
DIBUTTON_MECHA_VIEW
DIHATSWITCH_MECHA_GLANCE


Racing
Microsoft DirectX 9.0 SDK Update (October 2004)

Racing

The DIVIRTUAL_DRIVING_RACE genre contains controls for an auto-racing game without combat.

Priority 1 Controls
DIAXIS_DRIVINGR_ACCELERATE
DIAXIS_DRIVINGR_BRAKE
DIAXIS_DRIVINGR_STEER
DIBUTTON_DRIVINGR_MENU
DIBUTTON_DRIVINGR_SHIFTDOWN
DIBUTTON_DRIVINGR_SHIFTUP
DIBUTTON_DRIVINGR_VIEW

Priority 2 Controls
DIAXIS_DRIVINGR_ACCEL_AND_BRAKE
DIBUTTON_DRIVINGR_ACCELERATE_LINK
DIBUTTON_DRIVINGR_AIDS
DIBUTTON_DRIVINGR_BOOST
DIBUTTON_DRIVINGR_BRAKE
DIBUTTON_DRIVINGR_DASHBOARD
DIBUTTON_DRIVINGR_DEVICE
DIBUTTON_DRIVINGR_GLANCE_LEFT_LINK
DIBUTTON_DRIVINGR_GLANCE_RIGHT_LINK
DIBUTTON_DRIVINGR_MAP
DIBUTTON_DRIVINGR_PIT
DIBUTTON_DRIVINGR_PAUSE
DIBUTTON_DRIVINGR_STEER_LEFT_LINK
DIBUTTON_DRIVINGR_STEER_RIGHT_LINK
DIHATSWITCH_DRIVINGR_GLANCE


Tank
Microsoft DirectX 9.0 SDK Update (October 2004)

Tank

The DIVIRTUAL_DRIVING_TANK genre contains controls for a military tank simulation.

Priority 1 Controls
DIAXIS_DRIVINGT_ACCELERATE
DIAXIS_DRIVINGT_BARREL
DIAXIS_DRIVINGT_ROTATE
DIAXIS_DRIVINGT_STEER
DIBUTTON_DRIVINGT_FIRE
DIBUTTON_DRIVINGT_MENU
DIBUTTON_DRIVINGT_TARGET
DIBUTTON_DRIVINGT_WEAPONS

Priority 2 Controls
DIAXIS_DRIVINGT_ACCEL_AND_BRAKE
DIAXIS_DRIVINGT_BRAKE
DIBUTTON_DRIVINGT_ACCELERATE_LINK
DIBUTTON_DRIVINGT_BARREL_UP_LINK
DIBUTTON_DRIVINGT_BARREL_DOWN_LINK
DIBUTTON_DRIVINGT_BRAKE
DIBUTTON_DRIVINGT_DASHBOARD
DIBUTTON_DRIVINGT_DEVICE
DIBUTTON_DRIVINGT_FIRESECONDARY
DIBUTTON_DRIVINGT_GLANCE_LEFT_LINK
DIBUTTON_DRIVINGT_GLANCE_RIGHT_LINK
DIBUTTON_DRIVINGT_PAUSE
DIBUTTON_DRIVINGT_ROTATE_LEFT_LINK
DIBUTTON_DRIVINGT_ROTATE_RIGHT_LINK
DIBUTTON_DRIVINGT_STEER_LEFT_LINK
DIBUTTON_DRIVINGT_STEER_RIGHT_LINK
DIBUTTON_DRIVINGT_VIEW
DIHATSWITCH_DRIVINGT_GLANCE


Flight Genres
Microsoft DirectX 9.0 SDK Update (October 2004)

Flight Genres

The following genres are used in games and simulations where the players control aircraft or spaceships.

Constants

  • Air Combat
  • Civilian Flight
  • Helicopter Combat
  • Space Combat


Air Combat
Microsoft DirectX 9.0 SDK Update (October 2004)

Air Combat

The DIVIRTUAL_FLYING_MILITARY genre contains controls for a fixed-wing aerial combat simulation.

Priority 1 Controls
DIAXIS_FLYINGM_BANK
DIAXIS_FLYINGM_PITCH
DIAXIS_FLYINGM_THROTTLE
DIBUTTON_FLYINGM_FIRE
DIBUTTON_FLYINGM_MENU
DIBUTTON_FLYINGM_TARGET
DIBUTTON_FLYINGM_WEAPONS

Priority 2 Controls
DIAXIS_FLYINGM_BRAKE
DIAXIS_FLYINGM_FLAPS
DIAXIS_FLYINGM_RUDDER
DIBUTTON_FLYINGM_BRAKE_LINK
DIBUTTON_FLYINGM_COUNTER
DIBUTTON_FLYINGM_DEVICE
DIBUTTON_FLYINGM_DISPLAY
DIBUTTON_FLYINGM_FASTER_LINK
DIBUTTON_FLYINGM_FIRESECONDARY
DIBUTTON_FLYINGM_FLAPSDOWN
DIBUTTON_FLYINGM_FLAPSUP
DIBUTTON_FLYINGM_GEAR
DIBUTTON_FLYINGM_GLANCE_DOWN_LINK
DIBUTTON_FLYINGM_GLANCE_LEFT_LINK
DIBUTTON_FLYINGM_GLANCE_RIGHT_LINK
DIBUTTON_FLYINGM_GLANCE_UP_LINK
DIBUTTON_FLYINGM_PAUSE
DIBUTTON_FLYINGM_SLOWER_LINK
DIBUTTON_FLYINGM_VIEW
DIHATSWITCH_FLYINGM_GLANCE


Civilian Flight
Microsoft DirectX 9.0 SDK Update (October 2004)

Civilian Flight

The DIVIRTUAL_FLYING_CIVILIAN genre contains controls for noncombat flight simulations.

Priority 1 Controls
DIAXIS_FLYINGC_BANK
DIAXIS_FLYINGC_PITCH
DIAXIS_FLYINGC_THROTTLE
DIBUTTON_FLYINGC_DISPLAY
DIBUTTON_FLYINGC_GEAR
DIBUTTON_FLYINGC_MENU
DIBUTTON_FLYINGC_VIEW

Priority 2 Controls
DIAXIS_FLYINGC_BRAKE
DIAXIS_FLYINGC_FLAPS
DIAXIS_FLYINGC_RUDDER
DIBUTTON_FLYINGC_BRAKE_LINK
DIBUTTON_FLYINGC_DEVICE
DIBUTTON_FLYINGC_FASTER_LINK
DIBUTTON_FLYINGC_FLAPSDOWN
DIBUTTON_FLYINGC_FLAPSUP
DIBUTTON_FLYINGC_GLANCE_DOWN_LINK
DIBUTTON_FLYINGC_GLANCE_LEFT_LINK
DIBUTTON_FLYINGC_GLANCE_RIGHT_LINK
DIBUTTON_FLYINGC_GLANCE_UP_LINK
DIBUTTON_FLYINGC_PAUSE
DIBUTTON_FLYINGC_SLOWER_LINK
DIHATSWITCH_FLYINGC_GLANCE


Helicopter Combat
Microsoft DirectX 9.0 SDK Update (October 2004)

Helicopter Combat

The DIVIRTUAL_FLYING_HELICOPTER genre contains controls for a combat helicopter simulation.

Priority 1 Controls
DIAXIS_FLYINGH_BANK
DIAXIS_FLYINGH_COLLECTIVE
DIAXIS_FLYINGH_PITCH
DIBUTTON_FLYINGH_FIRE
DIBUTTON_FLYINGH_MENU
DIBUTTON_FLYINGH_TARGET
DIBUTTON_FLYINGH_WEAPONS

Priority 2 Controls
DIAXIS_FLYINGH_THROTTLE
DIAXIS_FLYINGH_TORQUE
DIBUTTON_FLYINGH_COUNTER
DIBUTTON_FLYINGH_DEVICE
DIBUTTON_FLYINGH_FASTER_LINK
DIBUTTON_FLYINGH_FIRESECONDARY
DIBUTTON_FLYINGH_GEAR
DIBUTTON_FLYINGH_GLANCE_DOWN_LINK
DIBUTTON_FLYINGH_GLANCE_LEFT_LINK
DIBUTTON_FLYINGH_GLANCE_RIGHT_LINK
DIBUTTON_FLYINGH_GLANCE_UP_LINK
DIBUTTON_FLYINGH_PAUSE
DIBUTTON_FLYINGH_SLOWER_LINK
DIBUTTON_FLYINGH_VIEW
DIHATSWITCH_FLYINGH_GLANCE


Space Combat
Microsoft DirectX 9.0 SDK Update (October 2004)

Space Combat

The DIVIRTUAL_SPACESIM genre contains controls for a spaceship combat simulation.

Priority 1 Controls
DIAXIS_SPACESIM_LATERAL
DIAXIS_SPACESIM_MOVE
DIAXIS_SPACESIM_THROTTLE
DIBUTTON_SPACESIM_FIRE
DIBUTTON_SPACESIM_MENU
DIBUTTON_SPACESIM_TARGET
DIBUTTON_SPACESIM_WEAPONS

Priority 2 Controls
DIAXIS_SPACESIM_CLIMB
DIAXIS_SPACESIM_ROTATE
DIBUTTON_SPACESIM_BACKWARD_LINK
DIBUTTON_SPACESIM_DEVICE
DIBUTTON_SPACESIM_DISPLAY
DIBUTTON_SPACESIM_FASTER_LINK
DIBUTTON_SPACESIM_FIRESECONDARY
DIBUTTON_SPACESIM_FORWARD_LINK
DIBUTTON_SPACESIM_GEAR
DIBUTTON_SPACESIM_GLANCE_DOWN_LINK
DIBUTTON_SPACESIM_GLANCE_LEFT_LINK
DIBUTTON_SPACESIM_GLANCE_RIGHT_LINK
DIBUTTON_SPACESIM_GLANCE_UP_LINK
DIBUTTON_SPACESIM_LEFT_LINK
DIBUTTON_SPACESIM_LOWER
DIBUTTON_SPACESIM_PAUSE
DIBUTTON_SPACESIM_RAISE
DIBUTTON_SPACESIM_RIGHT_LINK
DIBUTTON_SPACESIM_SLOWER_LINK
DIBUTTON_SPACESIM_TURN_LEFT_LINK
DIBUTTON_SPACESIM_TURN_RIGHT_LINK
DIBUTTON_SPACESIM_VIEW
DIHATSWITCH_SPACESIM_GLANCE


Sports Genres
Microsoft DirectX 9.0 SDK Update (October 2004)

Sports Genres

The following genres contain controls for sports games and simulations.

Constants

  • Baseball Batting
  • Baseball Fielding
  • Baseball Pitching
  • Basketball Defense
  • Basketball Offense
  • Fishing
  • Football Defense
  • Football Offense
  • Football Play
  • Football Quarterback
  • Golf
  • Hockey Defense
  • Hockey Goalie
  • Hockey Offense
  • Hunting
  • Mountain Biking
  • Racquet
  • Skiing
  • Soccer Defense
  • Soccer Offense


Baseball Batting
Microsoft DirectX 9.0 SDK Update (October 2004)

Baseball Batting

The DIVIRTUAL_SPORTS_BASEBALL_BAT genre contains controls for a batter in a baseball game.

Priority 1 Controls
DIAXIS_BASEBALLB_LATERAL
DIAXIS_BASEBALLB_MOVE
DIBUTTON_BASEBALLB_BUNT
DIBUTTON_BASEBALLB_BURST
DIBUTTON_BASEBALLB_CONTACT
DIBUTTON_BASEBALLB_MENU
DIBUTTON_BASEBALLB_NORMAL
DIBUTTON_BASEBALLB_POWER
DIBUTTON_BASEBALLB_SELECT
DIBUTTON_BASEBALLB_SLIDE
DIBUTTON_BASEBALLB_STEAL

Priority 2 Controls
DIBUTTON_BASEBALLB_BOX
DIBUTTON_BASEBALLB_BACK_LINK
DIBUTTON_BASEBALLB_DEVICE
DIBUTTON_BASEBALLB_FORWARD_LINK
DIBUTTON_BASEBALLB_LEFT_LINK
DIBUTTON_BASEBALLB_NOSTEAL
DIBUTTON_BASEBALLB_PAUSE
DIBUTTON_BASEBALLB_RIGHT_LINK


Baseball Fielding
Microsoft DirectX 9.0 SDK Update (October 2004)

Baseball Fielding

The DIVIRTUAL_SPORTS_BASEBALL_FIELD genre contains controls for fielders in a baseball game.

Priority 1 Controls
DIAXIS_BASEBALLF_LATERAL
DIAXIS_BASEBALLF_MOVE
DIBUTTON_BASEBALLF_BURST
DIBUTTON_BASEBALLF_DIVE
DIBUTTON_BASEBALLF_JUMP
DIBUTTON_BASEBALLF_MENU
DIBUTTON_BASEBALLF_NEAREST
DIBUTTON_BASEBALLF_THROW1
DIBUTTON_BASEBALLF_THROW2

Priority 2 Controls
DIBUTTON_BASEBALLF_AIM_LEFT_LINK
DIBUTTON_BASEBALLF_AIM_RIGHT_LINK
DIBUTTON_BASEBALLF_BACK_LINK
DIBUTTON_BASEBALLF_DEVICE
DIBUTTON_BASEBALLF_FORWARD_LINK
DIBUTTON_BASEBALLF_PAUSE
DIBUTTON_BASEBALLF_SHIFTIN
DIBUTTON_BASEBALLF_SHIFTOUT


Baseball Pitching
Microsoft DirectX 9.0 SDK Update (October 2004)

Baseball Pitching

The DIVIRTUAL_SPORTS_BASEBALL_PITCH genre contains controls for a pitcher in a baseball game.

Priority 1 Controls
DIAXIS_BASEBALLP_LATERAL
DIAXIS_BASEBALLP_MOVE
DIBUTTON_BASEBALLP_BASE
DIBUTTON_BASEBALLP_FAKE
DIBUTTON_BASEBALLP_MENU
DIBUTTON_BASEBALLP_PITCH
DIBUTTON_BASEBALLP_SELECT
DIBUTTON_BASEBALLP_THROW

Priority 2 Controls
DIBUTTON_BASEBALLP_BACK_LINK
DIBUTTON_BASEBALLP_DEVICE
DIBUTTON_BASEBALLP_FORWARD_LINK
DIBUTTON_BASEBALLP_LEFT_LINK
DIBUTTON_BASEBALLP_LOOK
DIBUTTON_BASEBALLP_PAUSE
DIBUTTON_BASEBALLP_RIGHT_LINK
DIBUTTON_BASEBALLP_WALK


Basketball Defense
Microsoft DirectX 9.0 SDK Update (October 2004)

Basketball Defense

The DIVIRTUAL_SPORTS_BASKETBALL_DEFENSE genre contains controls for defensive moves in a basketball game.

Priority 1 Controls
DIAXIS_BBALLD_LATERAL
DIAXIS_BBALLD_MOVE
DIBUTTON_BBALLD_BURST
DIBUTTON_BBALLD_FAKE
DIBUTTON_BBALLD_JUMP
DIBUTTON_BBALLD_MENU
DIBUTTON_BBALLD_PLAY
DIBUTTON_BBALLD_PLAYER
DIBUTTON_BBALLD_SPECIAL
DIBUTTON_BBALLD_STEAL

Priority 2 Controls
DIBUTTON_BBALLD_BACK_LINK
DIBUTTON_BBALLD_DEVICE
DIBUTTON_BBALLD_FORWARD_LINK
DIBUTTON_BBALLD_LEFT_LINK
DIBUTTON_BBALLD_PAUSE
DIBUTTON_BBALLD_RIGHT_LINK
DIBUTTON_BBALLD_SUBSTITUTE
DIBUTTON_BBALLD_TIMEOUT
DIHATSWITCH_BBALLD_GLANCE


Basketball Offense
Microsoft DirectX 9.0 SDK Update (October 2004)

Basketball Offense

The DIVIRTUAL_SPORTS_BASKETBALL_OFFENSE genre contains controls for the player who has the ball in a basketball game.

Priority 1 Controls
DIAXIS_BBALLO_LATERAL
DIAXIS_BBALLO_MOVE
DIBUTTON_BBALLO_BURST
DIBUTTON_BBALLO_CALL
DIBUTTON_BBALLO_DUNK
DIBUTTON_BBALLO_FAKE
DIBUTTON_BBALLO_MENU
DIBUTTON_BBALLO_PASS
DIBUTTON_BBALLO_PLAYER
DIBUTTON_BBALLO_SHOOT
DIBUTTON_BBALLO_SPECIAL

Priority 2 Controls
DIBUTTON_BBALLO_BACK_LINK
DIBUTTON_BBALLO_DEVICE
DIBUTTON_BBALLO_FORWARD_LINK
DIBUTTON_BBALLO_JAB
DIBUTTON_BBALLO_LEFT_LINK
DIBUTTON_BBALLO_PAUSE
DIBUTTON_BBALLO_PLAY
DIBUTTON_BBALLO_POST
DIBUTTON_BBALLO_RIGHT_LINK
DIBUTTON_BBALLO_SCREEN
DIBUTTON_BBALLO_SUBSTITUTE
DIBUTTON_BBALLO_TIMEOUT
DIHATSWITCH_BBALLO_GLANCE


Fishing
Microsoft DirectX 9.0 SDK Update (October 2004)

Fishing

The DIVIRTUAL_SPORTS_FISHING genre contains controls for a sport-fishing simulation.

Priority 1 Controls
DIAXIS_FISHING_LATERAL
DIAXIS_FISHING_MOVE
DIBUTTON_FISHING_BAIT
DIBUTTON_FISHING_BINOCULAR
DIBUTTON_FISHING_CAST
DIBUTTON_FISHING_MAP
DIBUTTON_FISHING_MENU
DIBUTTON_FISHING_TYPE

Priority 2 Controls
DIAXIS_FISHING_ROTATE
DIBUTTON_FISHING_BACK_LINK
DIBUTTON_FISHING_CROUCH
DIBUTTON_FISHING_DEVICE
DIBUTTON_FISHING_DISPLAY
DIBUTTON_FISHING_FORWARD_LINK
DIBUTTON_FISHING_JUMP
DIBUTTON_FISHING_LEFT_LINK
DIBUTTON_FISHING_PAUSE
DIBUTTON_FISHING_RIGHT_LINK
DIBUTTON_FISHING_ROTATE_LEFT_LINK
DIBUTTON_FISHING_ROTATE_RIGHT_LINK
DIHATSWITCH_FISHING_GLANCE


Football Defense
Microsoft DirectX 9.0 SDK Update (October 2004)

Football Defense

The DIVIRTUAL_SPORTS_FOOTBALL_DEFENSE genre contains controls for the defensive side in a North American football game.

Priority 1 Controls
DIAXIS_FOOTBALLD_LATERAL
DIAXIS_FOOTBALLD_MOVE
DIBUTTON_FOOTBALLD_FAKE
DIBUTTON_FOOTBALLD_JUMP
DIBUTTON_FOOTBALLD_MENU
DIBUTTON_FOOTBALLD_PLAY
DIBUTTON_FOOTBALLD_SELECT
DIBUTTON_FOOTBALLD_SUPERTACKLE
DIBUTTON_FOOTBALLD_TACKLE

Priority 2 Controls
DIBUTTON_FOOTBALLD_AUDIBLE
DIBUTTON_FOOTBALLD_BACK_LINK
DIBUTTON_FOOTBALLD_BULLRUSH
DIBUTTON_FOOTBALLD_DEVICE
DIBUTTON_FOOTBALLD_FORWARD_LINK
DIBUTTON_FOOTBALLD_LEFT_LINK
DIBUTTON_FOOTBALLD_PAUSE
DIBUTTON_FOOTBALLD_RIGHT_LINK
DIBUTTON_FOOTBALLD_RIP
DIBUTTON_FOOTBALLD_SPIN
DIBUTTON_FOOTBALLD_SUBSTITUTE
DIBUTTON_FOOTBALLD_SWIM
DIBUTTON_FOOTBALLD_ZOOM


Football Offense
Microsoft DirectX 9.0 SDK Update (October 2004)

Football Offense

The DIVIRTUAL_SPORTS_FOOTBALL_OFFENSE genre contains controls for the ball carrier in a North American football game.

Priority 1 Controls
DIAXIS_FOOTBALLO_LATERAL
DIAXIS_FOOTBALLO_MOVE
DIBUTTON_FOOTBALLO_JUMP
DIBUTTON_FOOTBALLO_LEFTARM
DIBUTTON_FOOTBALLO_MENU
DIBUTTON_FOOTBALLO_RIGHTARM
DIBUTTON_FOOTBALLO_SPIN
DIBUTTON_FOOTBALLO_THROW

Priority 2 Controls
DIBUTTON_FOOTBALLO_BACK_LINK
DIBUTTON_FOOTBALLO_DEVICE
DIBUTTON_FOOTBALLO_DIVE
DIBUTTON_FOOTBALLO_FORWARD_LINK
DIBUTTON_FOOTBALLO_JUKE
DIBUTTON_FOOTBALLO_LEFT_LINK
DIBUTTON_FOOTBALLO_PAUSE
DIBUTTON_FOOTBALLO_RIGHT_LINK
DIBUTTON_FOOTBALLO_SHOULDER
DIBUTTON_FOOTBALLO_SUBSTITUTE
DIBUTTON_FOOTBALLO_TURBO
DIBUTTON_FOOTBALLO_ZOOM


Football Play
Microsoft DirectX 9.0 SDK Update (October 2004)

Football Play

The DIVIRTUAL_SPORTS_FOOTBALL_FIELD genre contains general controls for a North American football game.

Priority 1 Controls
DIBUTTON_FOOTBALLP_HELP
DIBUTTON_FOOTBALLP_MENU
DIBUTTON_FOOTBALLP_PLAY
DIBUTTON_FOOTBALLP_SELECT

Priority 2 Controls
DIBUTTON_FOOTBALLP_DEVICE
DIBUTTON_FOOTBALLP_PAUSE


Football Quarterback
Microsoft DirectX 9.0 SDK Update (October 2004)

Football Quarterback

The DIVIRTUAL_SPORTS_FOOTBALL_QBCK genre contains controls for the quarterback in a North American football game.

Priority 1 Controls
DIAXIS_FOOTBALLQ_LATERAL
DIAXIS_FOOTBALLQ_MOVE
DIBUTTON_FOOTBALLQ_FAKE
DIBUTTON_FOOTBALLQ_JUMP
DIBUTTON_FOOTBALLQ_MENU
DIBUTTON_FOOTBALLQ_PASS
DIBUTTON_FOOTBALLQ_SELECT
DIBUTTON_FOOTBALLQ_SLIDE
DIBUTTON_FOOTBALLQ_SNAP

Priority 2 Controls
DIBUTTON_FOOTBALLQ_AUDIBLE
DIBUTTON_FOOTBALLQ_BACK_LINK
DIBUTTON_FOOTBALLQ_DEVICE
DIBUTTON_FOOTBALLQ_FAKESNAP
DIBUTTON_FOOTBALLQ_FORWARD_LINK
DIBUTTON_FOOTBALLQ_LEFT_LINK
DIBUTTON_FOOTBALLQ_MOTION
DIBUTTON_FOOTBALLQ_PAUSE
DIBUTTON_FOOTBALLQ_RIGHT_LINK


Golf
Microsoft DirectX 9.0 SDK Update (October 2004)

Golf

The DIVIRTUAL_SPORTS_GOLF genre contains controls for a golf game.

Priority 1 Controls
DIAXIS_GOLF_LATERAL
DIAXIS_GOLF_MOVE
DIBUTTON_GOLF_DOWN
DIBUTTON_GOLF_FLYBY
DIBUTTON_GOLF_MENU
DIBUTTON_GOLF_SELECT
DIBUTTON_GOLF_SWING
DIBUTTON_GOLF_TERRAIN
DIBUTTON_GOLF_UP

Priority 2 Controls
DIBUTTON_GOLF_BACK_LINK
DIBUTTON_GOLF_DEVICE
DIBUTTON_GOLF_FORWARD_LINK
DIBUTTON_GOLF_LEFT_LINK
DIBUTTON_GOLF_PAUSE
DIBUTTON_GOLF_RIGHT_LINK
DIBUTTON_GOLF_SUBSTITUTE
DIBUTTON_GOLF_TIMEOUT
DIBUTTON_GOLF_ZOOM
DIHATSWITCH_GOLF_SCROLL


Hockey Defense
Microsoft DirectX 9.0 SDK Update (October 2004)

Hockey Defense

The DIVIRTUAL_SPORTS_HOCKEY_DEFENSE genre contains controls for defensive moves in a hockey game.

Priority 1 Controls
DIAXIS_HOCKEYD_LATERAL
DIAXIS_HOCKEYD_MOVE
DIBUTTON_HOCKEYD_BLOCK
DIBUTTON_HOCKEYD_BURST
DIBUTTON_HOCKEYD_FAKE
DIBUTTON_HOCKEYD_MENU
DIBUTTON_HOCKEYD_PLAYER
DIBUTTON_HOCKEYD_STEAL

Priority 2 Controls
DIBUTTON_HOCKEYD_BACK_LINK
DIBUTTON_HOCKEYD_DEVICE
DIBUTTON_HOCKEYO_FORWARD_LINK
DIBUTTON_HOCKEYO_LEFT_LINK
DIBUTTON_HOCKEYD_PAUSE
DIBUTTON_HOCKEYO_RIGHT_LINK
DIBUTTON_HOCKEYD_STRATEGY
DIBUTTON_HOCKEYD_SUBSTITUTE
DIBUTTON_HOCKEYD_TIMEOUT
DIBUTTON_HOCKEYD_ZOOM
DIHATSWITCH_HOCKEYD_SCROLL


Hockey Goalie
Microsoft DirectX 9.0 SDK Update (October 2004)

Hockey Goalie

The DIVIRTUAL_SPORTS_HOCKEY_GOALIE genre contains controls for a goalkeeper in a hockey game.

Priority 1 Controls
DIAXIS_HOCKEYG_LATERAL
DIAXIS_HOCKEYG_MOVE
DIBUTTON_HOCKEYG_BLOCK
DIBUTTON_HOCKEYG_MENU
DIBUTTON_HOCKEYG_PASS
DIBUTTON_HOCKEYG_POKE
DIBUTTON_HOCKEYG_STEAL

Priority 2 Controls
DIBUTTON_HOCKEYG_BACK_LINK
DIBUTTON_HOCKEYG_DEVICE
DIBUTTON_HOCKEYG_FORWARD_LINK
DIBUTTON_HOCKEYG_LEFT_LINK
DIBUTTON_HOCKEYG_PAUSE
DIBUTTON_HOCKEYG_RIGHT_LINK
DIBUTTON_HOCKEYG_STRATEGY
DIBUTTON_HOCKEYG_SUBSTITUTE
DIBUTTON_HOCKEYG_TIMEOUT
DIBUTTON_HOCKEYG_ZOOM
DIHATSWITCH_HOCKEYG_SCROLL


Hockey Offense
Microsoft DirectX 9.0 SDK Update (October 2004)

Hockey Offense

The DIVIRTUAL_SPORTS_HOCKEY_OFFENSE genre contains controls for offensive moves in a hockey game.

Priority 1 Controls
DIAXIS_HOCKEYO_LATERAL
DIAXIS_HOCKEYO_MOVE
DIBUTTON_HOCKEYO_BURST
DIBUTTON_HOCKEYO_FAKE
DIBUTTON_HOCKEYO_MENU
DIBUTTON_HOCKEYO_PASS
DIBUTTON_HOCKEYO_SHOOT
DIBUTTON_HOCKEYO_SPECIAL

Priority 2 Controls
DIBUTTON_HOCKEYO_BACK_LINK
DIBUTTON_HOCKEYO_DEVICE
DIBUTTON_HOCKEYO_FORWARD_LINK
DIBUTTON_HOCKEYO_LEFT_LINK
DIBUTTON_HOCKEYO_PAUSE
DIBUTTON_HOCKEYO_RIGHT_LINK
DIBUTTON_HOCKEYO_STRATEGY
DIBUTTON_HOCKEYO_SUBSTITUTE
DIBUTTON_HOCKEYO_TIMEOUT
DIBUTTON_HOCKEYO_ZOOM
DIHATSWITCH_HOCKEYO_SCROLL


Hunting
Microsoft DirectX 9.0 SDK Update (October 2004)

Hunting

The DIVIRTUAL_SPORTS_HUNTING genre contains controls for a hunting simulation.

Priority 1 Controls
DIAXIS_HUNTING_LATERAL
DIAXIS_HUNTING_MOVE
DIBUTTON_HUNTING_AIM
DIBUTTON_HUNTING_BINOCULAR
DIBUTTON_HUNTING_CALL
DIBUTTON_HUNTING_FIRE
DIBUTTON_HUNTING_MAP
DIBUTTON_HUNTING_MENU
DIBUTTON_HUNTING_SPECIAL
DIBUTTON_HUNTING_WEAPON

Priority 2 Controls
DIAXIS_HUNTING_ROTATE
DIBUTTON_HUNTING_BACK_LINK
DIBUTTON_HUNTING_CROUCH
DIBUTTON_HUNTING_DEVICE
DIBUTTON_HUNTING_DISPLAY
DIBUTTON_HUNTING_FIRESECONDARY
DIBUTTON_HUNTING_FORWARD_LINK
DIBUTTON_HUNTING_JUMP
DIBUTTON_HUNTING_LEFT_LINK
DIBUTTON_HUNTING_PAUSE
DIBUTTON_HUNTING_RIGHT_LINK
DIBUTTON_HUNTING_ROTATE_LEFT_LINK
DIBUTTON_HUNTING_ROTATE_RIGHT_LINK
DIHATSWITCH_HUNTING_GLANCE


Mountain Biking
Microsoft DirectX 9.0 SDK Update (October 2004)

Mountain Biking

The DIVIRTUAL_SPORTS_BIKING_MOUNTAIN contains controls for a mountain-bike game.

Priority 1 Controls
DIAXIS_BIKINGM_PEDAL
DIAXIS_BIKINGM_TURN
DIBUTTON_BIKINGM_CAMERA
DIBUTTON_BIKINGM_JUMP
DIBUTTON_BIKINGM_MENU
DIBUTTON_BIKINGM_SELECT
DIBUTTON_BIKINGM_SPECIAL1
DIBUTTON_BIKINGM_SPECIAL2

Priority 2 Controls
DIAXIS_BIKINGM_BRAKE
DIBUTTON_BIKINGM_BRAKE_BUTTON_LINK
DIBUTTON_BIKINGM_DEVICE
DIBUTTON_BIKINGM_FASTER_LINK
DIBUTTON_BIKINGM_LEFT_LINK
DIBUTTON_BIKINGM_PAUSE
DIBUTTON_BIKINGM_RIGHT_LINK
DIBUTTON_BIKINGM_SLOWER_LINK
DIBUTTON_BIKINGM_ZOOM
DIHATSWITCH_BIKINGM_SCROLL


Racquet
Microsoft DirectX 9.0 SDK Update (October 2004)

Racquet

The DIVIRTUAL_SPORTS_RACQUET genre includes racquet games such as tennis, table tennis, and squash.

Priority 1 Controls
DIAXIS_RACQUET_LATERAL
DIAXIS_RACQUET_MOVE
DIBUTTON_RACQUET_BACKSWING
DIBUTTON_RACQUET_MENU
DIBUTTON_RACQUET_SELECT
DIBUTTON_RACQUET_SMASH
DIBUTTON_RACQUET_SPECIAL
DIBUTTON_RACQUET_SWING

Priority 2 Controls
DIBUTTON_RACQUET_BACK_LINK
DIBUTTON_RACQUET_DEVICE
DIBUTTON_RACQUET_FORWARD_LINK
DIBUTTON_RACQUET_LEFT_LINK
DIBUTTON_RACQUET_PAUSE
DIBUTTON_RACQUET_RIGHT_LINK
DIBUTTON_RACQUET_SUBSTITUTE
DIBUTTON_RACQUET_TIMEOUT
DIHATSWITCH_RACQUET_GLANCE


Skiing
Microsoft DirectX 9.0 SDK Update (October 2004)

Skiing

The DIVIRTUAL_SPORTS_SKIING contains controls for skiing games as well as for similar sports simulations such as snowboarding and skateboarding.

Priority 1 Controls
DIAXIS_SKIING_SPEED
DIAXIS_SKIING_TURN
DIBUTTON_SKIING_CAMERA
DIBUTTON_SKIING_CROUCH
DIBUTTON_SKIING_JUMP
DIBUTTON_SKIING_MENU
DIBUTTON_SKIING_SELECT
DIBUTTON_SKIING_SPECIAL1
DIBUTTON_SKIING_SPECIAL2

Priority 2 Controls
DIBUTTON_SKIING_DEVICE
DIBUTTON_SKIING_FASTER_LINK
DIBUTTON_SKIING_LEFT_LINK
DIBUTTON_SKIING_PAUSE
DIBUTTON_SKIING_RIGHT_LINK
DIBUTTON_SKIING_SLOWER_LINK
DIBUTTON_SKIING_ZOOM
DIHATSWITCH_SKIING_GLANCE


Soccer Defense
Microsoft DirectX 9.0 SDK Update (October 2004)

Soccer Defense

The DIVIRTUAL_SPORTS_SOCCER_DEFENSE contains controls for defensive moves in a soccer (international football) game.

Priority 1 Controls
DIAXIS_SOCCERD_LATERAL
DIAXIS_SOCCERD_MOVE
DIBUTTON_SOCCERD_BLOCK
DIBUTTON_SOCCERD_FAKE
DIBUTTON_SOCCERD_MENU
DIBUTTON_SOCCERD_PLAYER
DIBUTTON_SOCCERD_SELECT
DIBUTTON_SOCCERD_SLIDE
DIBUTTON_SOCCERD_SPECIAL
DIBUTTON_SOCCERD_STEAL

Priority 2 Controls
DIBUTTON_SOCCERD_BACK_LINK
DIBUTTON_SOCCERD_CLEAR
DIBUTTON_SOCCERD_DEVICE
DIBUTTON_SOCCERD_FORWARD_LINK
DIBUTTON_SOCCERD_FOUL
DIBUTTON_SOCCERD_GOALIECHARGE
DIBUTTON_SOCCERD_HEAD
DIBUTTON_SOCCERD_LEFT_LINK
DIBUTTON_SOCCERD_PAUSE
DIBUTTON_SOCCERD_RIGHT_LINK
DIBUTTON_SOCCERD_SUBSTITUTE
DIHATSWITCH_SOCCERD_GLANCE


Soccer Offense
Microsoft DirectX 9.0 SDK Update (October 2004)

Soccer Offense

The DIVIRTUAL_SPORTS_SOCCER_OFFENSE contains controls for offensive moves in a soccer (international football) game.

Priority 1 Controls
DIAXIS_SOCCERO_BEND
DIAXIS_SOCCERO_LATERAL
DIAXIS_SOCCERO_MOVE
DIBUTTON_SOCCERO_FAKE
DIBUTTON_SOCCERO_MENU
DIBUTTON_SOCCERO_PASS
DIBUTTON_SOCCERO_PLAYER
DIBUTTON_SOCCERO_SELECT
DIBUTTON_SOCCERO_SHOOT
DIBUTTON_SOCCERO_SPECIAL1

Priority 2 Controls
DIBUTTON_SOCCERO_BACK_LINK
DIBUTTON_SOCCERO_CONTROL
DIBUTTON_SOCCERO_DEVICE
DIBUTTON_SOCCERO_FORWARD_LINK
DIBUTTON_SOCCERO_HEAD
DIBUTTON_SOCCERO_LEFT_LINK
DIBUTTON_SOCCERO_PASSTHRU
DIBUTTON_SOCCERO_PAUSE
DIBUTTON_SOCCERO_RIGHT_LINK
DIBUTTON_SOCCERO_SHOOTHIGH
DIBUTTON_SOCCERO_SHOOTLOW
DIBUTTON_SOCCERO_SPRINT
DIBUTTON_SOCCERO_SUBSTITUTE
DIHATSWITCH_SOCCERO_GLANCE


Strategy Genres
Microsoft DirectX 9.0 SDK Update (October 2004)

Strategy Genres

The following genres contain controls for strategy, role-playing, and adventure games.

Constants

  • Role-Playing
  • Turn-Based


Role-Playing
Microsoft DirectX 9.0 SDK Update (October 2004)

Role-Playing

The DIVIRTUAL_STRATEGY_ROLEPLAYING genre contains controls for a role-playing or adventure game in which navigation, problem-solving, and fighting with weapons and magic are common activities.

Priority 1 Controls
DIAXIS_STRATEGYR_LATERAL
DIAXIS_STRATEGYR_MOVE
DIBUTTON_STRATEGYR_APPLY
DIBUTTON_STRATEGYR_ATTACK
DIBUTTON_STRATEGYR_CAST
DIBUTTON_STRATEGYR_CROUCH
DIBUTTON_STRATEGYR_GET
DIBUTTON_STRATEGYR_JUMP
DIBUTTON_STRATEGYR_MENU
DIBUTTON_STRATEGYR_SELECT

Priority 2 Controls
DIAXIS_STRATEGYR_ROTATE
DIBUTTON_STRATEGYR_BACK_LINK
DIBUTTON_STRATEGYR_DEVICE
DIBUTTON_STRATEGYR_DISPLAY
DIBUTTON_STRATEGYR_FORWARD_LINK
DIBUTTON_STRATEGYR_LEFT_LINK
DIBUTTON_STRATEGYR_MAP
DIBUTTON_STRATEGYR_PAUSE
DIBUTTON_STRATEGYR_RIGHT_LINK
DIBUTTON_STRATEGYR_ROTATE_LEFT_LINK
DIBUTTON_STRATEGYR_ROTATE_RIGHT_LINK
DIHATSWITCH_STRATEGYR_GLANCE


Turn-Based
Microsoft DirectX 9.0 SDK Update (October 2004)

Turn-Based

The DIVIRTUAL_STRATEGY_TURN genre contains controls for a turn-based strategy game.

Priority 1 Controls
DIAXIS_STRATEGYT_LATERAL
DIAXIS_STRATEGYT_MOVE
DIBUTTON_STRATEGYT_APPLY
DIBUTTON_STRATEGYT_INSTRUCT
DIBUTTON_STRATEGYT_MENU
DIBUTTON_STRATEGYT_SELECT
DIBUTTON_STRATEGYT_TEAM
DIBUTTON_STRATEGYT_TURN

Priority 2 Controls
DIBUTTON_STRATEGYT_BACK_LINK
DIBUTTON_STRATEGYT_DEVICE
DIBUTTON_STRATEGYT_DISPLAY
DIBUTTON_STRATEGYT_FORWARD_LINK
DIBUTTON_STRATEGYT_LEFT_LINK
DIBUTTON_STRATEGYT_MAP
DIBUTTON_STRATEGYT_PAUSE
DIBUTTON_STRATEGYT_RIGHT_LINK
DIBUTTON_STRATEGYT_ZOOM


Any-Control Enumerated Type

The following constants are used in the dwSemantic member of the DIACTION structure to map an action to any matching control on the device.

Syntax

typedef enum {
    DIAXIS_ANY_1,
    DIAXIS_ANY_2,
    DIAXIS_ANY_3,
    DIAXIS_ANY_3,
    DIAXIS_ANY_A_1,
    DIAXIS_ANY_A_1,
    DIAXIS_ANY_B_1,
    DIAXIS_ANY_B_2,
    DIAXIS_ANY_C_1,
    DIAXIS_ANY_C_2,
    DIAXIS_ANY_R_1,
    DIAXIS_ANY_R_2,
    DIAXIS_ANY_S_1,
    DIAXIS_ANY_S_2,
    DIAXIS_ANY_U_1,
    DIAXIS_ANY_U_2,
    DIAXIS_ANY_V_1,
    DIAXIS_ANY_V_2,
    DIAXIS_ANY_X_1,
    DIAXIS_ANY_X_2,
    DIAXIS_ANY_Y_1,
    DIAXIS_ANY_Y_2,
    DIAXIS_ANY_Z_1,
    DIAXIS_ANY_Z_2,
    DIBUTTON_ANY,
    DIPOV_ANY_1,
    DIPOV_ANY_2,
    DIPOV_ANY_3,
    DIPOV_ANY_4
} Any-Control;

Constants

DIAXIS_ANY_1

Any axis

DIAXIS_ANY_2

Any axis

DIAXIS_ANY_3

Any axis

DIAXIS_ANY_3

Any axis

DIAXIS_ANY_A_1

Any accelerator

DIAXIS_ANY_A_1

Any accelerator

DIAXIS_ANY_B_1

Any brake

DIAXIS_ANY_B_2

Any brake

DIAXIS_ANY_C_1

Any clutch

DIAXIS_ANY_C_2

Any clutch

DIAXIS_ANY_R_1

Any r-axis

DIAXIS_ANY_R_2

Any r-axis

DIAXIS_ANY_S_1

Any s-axis

DIAXIS_ANY_S_2

Any s-axis

DIAXIS_ANY_U_1

Any u-axis

DIAXIS_ANY_U_2

Any u-axis

DIAXIS_ANY_V_1

Any v-axis

DIAXIS_ANY_V_2

Any v-axis

DIAXIS_ANY_X_1

Any x-axis

DIAXIS_ANY_X_2

Any x-axis

DIAXIS_ANY_Y_1

Any y-axis

DIAXIS_ANY_Y_2

Any y-axis

DIAXIS_ANY_Z_1

Any z-axis

DIAXIS_ANY_Z_2

Any z-axis

DIBUTTON_ANY

Any button. This is a constant macro that takes a button number as its argument. For example, DIBUTTON_ANY(3).

DIPOV_ANY_1

Any point-of-view controller

DIPOV_ANY_2

Any point-of-view controller

DIPOV_ANY_3

Any point-of-view controller

DIPOV_ANY_4

Any point-of-view controller

Remarks

These constants can be used to map an application action to a virtual control that is not defined in a genre. Such actions are mapped after genre-specific actions. If the mapper has already mapped all matching controls to genre-specific actions, the any-control action is left unmapped.

Any-control actions are treated with equal priority. If a device has one x-axis and the action array specifies DIAXIS_ANY_1 and DIAXIS_ANY_X_1, the action mapped to the x-axis is the one that appears first in the action array.

DIBUTTON_ANY(x) can accept any value from 0 through 255. Do not use an index more than once. For instance, the following set of DIACTION structures would be invalid.

{eB_MUTE,    DIBUTTON_ANY(0), 0, "Toggle Sound",},
{eB_VOLUP,   DIBUTTON_ANY(0), 0, "Volume Up",   },
{eB_VOLDOWN, DIBUTTON_ANY(0), 0, "Volume Down", },

The correct method uses different indexes, as shown below.

{eB_MUTE,    DIBUTTON_ANY(0), 0, "Toggle Sound",}
{eB_VOLUP,   DIBUTTON_ANY(1), 0, "Volume Up",   }
{eB_VOLDOWN, DIBUTTON_ANY(2), 0, "Volume Down", }

Enumerated Type Information

Minimum operating systems Windows 98, Windows NT 2000, Windows XP


DirectPlay Voice Mapping Enumerated Type

The following constants are used in the dwSemantic member of the DIACTION structure to map an action to a channel on Microsoft DirectPlay voice device.

Syntax

typedef enum {
    DIVOICE_CHANNEL1,
    DIVOICE_CHANNEL2,
    DIVOICE_CHANNEL3,
    DIVOICE_CHANNEL4,
    DIVOICE_CHANNEL5,
    DIVOICE_CHANNEL6,
    DIVOICE_CHANNEL7,
    DIVOICE_CHANNEL8,
    DIVOICE_ALL,
    DIVOICE_TEAM,
    DIVOICE_PLAYBACKMUTE,
    DIVOICE_RECORDMUTE,
    DIVOICE_TRANSMIT,
    DIVOICE_VOICECOMMAND
} DirectPlay Voice Mapping;

Constants

DIVOICE_CHANNEL1

DIVOICE_CHANNEL2

DIVOICE_CHANNEL3

DIVOICE_CHANNEL4

DIVOICE_CHANNEL5

DIVOICE_CHANNEL6

DIVOICE_CHANNEL7

DIVOICE_CHANNEL8

DIVOICE_ALL

DIVOICE_TEAM

DIVOICE_PLAYBACKMUTE

DIVOICE_RECORDMUTE

DIVOICE_TRANSMIT

DIVOICE_VOICECOMMAND

Enumerated Type Information

Minimum operating systems Windows 98, Windows NT 2000, Windows XP


Keyboard Mapping Enumerated Type

The following constants are used in the dwSemantic member of the DIACTION structure to map an action to a physical key.

Syntax

typedef enum {
    DIKEYBOARD_0,
    DIKEYBOARD_1,
    DIKEYBOARD_2,
    DIKEYBOARD_3,
    DIKEYBOARD_4,
    DIKEYBOARD_5,
    DIKEYBOARD_6,
    DIKEYBOARD_7,
    DIKEYBOARD_8,
    DIKEYBOARD_9,
    DIKEYBOARD_A,
    DIKEYBOARD_ABNT_C1,
    DIKEYBOARD_ABNT_C2,
    DIKEYBOARD_ADD,
    DIKEYBOARD_APOSTROPHE,
    DIKEYBOARD_APPS,
    DIKEYBOARD_AT,
    DIKEYBOARD_AX,
    DIKEYBOARD_B,
    DIKEYBOARD_BACK,
    DIKEYBOARD_BACKSLASH,
    DIKEYBOARD_C,
    DIKEYBOARD_CALCULATOR,
    DIKEYBOARD_CAPITAL,
    DIKEYBOARD_COLON,
    DIKEYBOARD_COMMA,
    DIKEYBOARD_CONVERT,
    DIKEYBOARD_D,
    DIKEYBOARD_DECIMAL,
    DIKEYBOARD_DELETE,
    DIKEYBOARD_DIVIDE,
    DIKEYBOARD_DOWN,
    DIKEYBOARD_E,
    DIKEYBOARD_END,
    DIKEYBOARD_EQUALS,
    DIKEYBOARD_ESCAPE,
    DIKEYBOARD_F,
    DIKEYBOARD_F1,
    DIKEYBOARD_F2,
    DIKEYBOARD_F3,
    DIKEYBOARD_F4,
    DIKEYBOARD_F5,
    DIKEYBOARD_F6,
    DIKEYBOARD_F7,
    DIKEYBOARD_F8,
    DIKEYBOARD_F9,
    DIKEYBOARD_F10,
    DIKEYBOARD_F11,
    DIKEYBOARD_F12,
    DIKEYBOARD_F13,
    DIKEYBOARD_F14,
    DIKEYBOARD_F15,
    DIKEYBOARD_G,
    DIKEYBOARD_GRAVE,
    DIKEYBOARD_H,
    DIKEYBOARD_HOME,
    DIKEYBOARD_I,
    DIKEYBOARD_INSERT,
    DIKEYBOARD_J,
    DIKEYBOARD_K,
    DIKEYBOARD_KANA,
    DIKEYBOARD_KANJI,
    DIKEYBOARD_L,
    DIKEYBOARD_LBRACKET,
    DIKEYBOARD_LCONTROL,
    DIKEYBOARD_LEFT,
    DIKEYBOARD_LMENU,
    DIKEYBOARD_LSHIFT,
    DIKEYBOARD_LWIN,
    DIKEYBOARD_M,
    DIKEYBOARD_MAIL,
    DIKEYBOARD_MEDIASELECT,
    DIKEYBOARD_MEDIASTOP,
    DIKEYBOARD_MINUS,
    DIKEYBOARD_MULTIPLY,
    DIKEYBOARD_MUTE,
    DIKEYBOARD_MYCOMPUTER,
    DIKEYBOARD_N,
    DIKEYBOARD_NEXT,
    DIKEYBOARD_NEXTTRACK,
    DIKEYBOARD_NOCONVERT,
    DIKEYBOARD_NUMLOCK,
    DIKEYBOARD_NUMPAD0,
    DIKEYBOARD_NUMPAD1,
    DIKEYBOARD_NUMPAD2,
    DIKEYBOARD_NUMPAD3,
    DIKEYBOARD_NUMPAD4,
    DIKEYBOARD_NUMPAD5,
    DIKEYBOARD_NUMPAD6,
    DIKEYBOARD_NUMPAD7,
    DIKEYBOARD_NUMPAD8,
    DIKEYBOARD_NUMPAD9,
    DIKEYBOARD_NUMPADCOMMA,
    DIKEYBOARD_NUMPADENTER,
    DIKEYBOARD_NUMPADEQUALS,
    DIKEYBOARD_O,
    DIKEYBOARD_OEM_102,
    DIKEYBOARD_P,
    DIKEYBOARD_PAUSE,
    DIKEYBOARD_PERIOD,
    DIKEYBOARD_PLAYPAUSE,
    DIKEYBOARD_POWER,
    DIKEYBOARD_PREVTRACK,
    DIKEYBOARD_PRIOR,
    DIKEYBOARD_Q,
    DIKEYBOARD_R,
    DIKEYBOARD_RBRACKET,
    DIKEYBOARD_RCONTROL,
    DIKEYBOARD_RETURN,
    DIKEYBOARD_RIGHT,
    DIKEYBOARD_RMENU,
    DIKEYBOARD_RSHIFT,
    DIKEYBOARD_RWIN,
    DIKEYBOARD_S,
    DIKEYBOARD_SCROLL,
    DIKEYBOARD_SEMICOLON,
    DIKEYBOARD_SLASH,
    DIKEYBOARD_SLEEP,
    DIKEYBOARD_SPACE,
    DIKEYBOARD_STOP,
    DIKEYBOARD_SUBTRACT,
    DIKEYBOARD_SYSRQ,
    DIKEYBOARD_T,
    DIKEYBOARD_TAB,
    DIKEYBOARD_U,
    DIKEYBOARD_UNDERLINE,
    DIKEYBOARD_UNLABELED,
    DIKEYBOARD_UP,
    DIKEYBOARD_V,
    DIKEYBOARD_VOLUMEDOWN,
    DIKEYBOARD_VOLUMEUP,
    DIKEYBOARD_W,
    DIKEYBOARD_WAKE,
    DIKEYBOARD_WEBBACK,
    DIKEYBOARD_WEBFAVORITES,
    DIKEYBOARD_WEBFORWARD,
    DIKEYBOARD_WEBHOME,
    DIKEYBOARD_WEBREFRESH,
    DIKEYBOARD_WEBSEARCH,
    DIKEYBOARD_WEBSTOP,
    DIKEYBOARD_X,
    DIKEYBOARD_Y,
    DIKEYBOARD_YEN,
    DIKEYBOARD_Z
} Keyboard Mapping;

Constants

DIKEYBOARD_0

On main keyboard

DIKEYBOARD_1

On main keyboard

DIKEYBOARD_2

On main keyboard

DIKEYBOARD_3

On main keyboard

DIKEYBOARD_4

On main keyboard

DIKEYBOARD_5

On main keyboard

DIKEYBOARD_6

On main keyboard

DIKEYBOARD_7

On main keyboard

DIKEYBOARD_8

On main keyboard

DIKEYBOARD_9

On main keyboard

DIKEYBOARD_A

DIKEYBOARD_ABNT_C1

On numeric pad of Brazilian keyboards

DIKEYBOARD_ABNT_C2

On numeric pad of Brazilian keyboards

DIKEYBOARD_ADD

PLUS SIGN (+) on numeric keypad

DIKEYBOARD_APOSTROPHE

DIKEYBOARD_APPS

Application key

DIKEYBOARD_AT

On Japanese keyboard

DIKEYBOARD_AX

On Japanese keyboard

DIKEYBOARD_B

DIKEYBOARD_BACK

BACKSPACE

DIKEYBOARD_BACKSLASH

DIKEYBOARD_C

DIKEYBOARD_CALCULATOR

DIKEYBOARD_CAPITAL

CAPS LOCK

DIKEYBOARD_COLON

On Japanese keyboard

DIKEYBOARD_COMMA

DIKEYBOARD_CONVERT

On Japanese keyboard

DIKEYBOARD_D

DIKEYBOARD_DECIMAL

PERIOD (decimal point) on numeric keypad

DIKEYBOARD_DELETE

DIKEYBOARD_DIVIDE

FORWARD SLASH (/) on numeric keypad

DIKEYBOARD_DOWN

DOWN ARROW

DIKEYBOARD_E

DIKEYBOARD_END

DIKEYBOARD_EQUALS

On main keyboard

DIKEYBOARD_ESCAPE

DIKEYBOARD_F

DIKEYBOARD_F1

DIKEYBOARD_F2

DIKEYBOARD_F3

DIKEYBOARD_F4

DIKEYBOARD_F5

DIKEYBOARD_F6

DIKEYBOARD_F7

DIKEYBOARD_F8

DIKEYBOARD_F9

DIKEYBOARD_F10

DIKEYBOARD_F11

DIKEYBOARD_F12

DIKEYBOARD_F13

On NEC PC-98 Japanese keyboard

DIKEYBOARD_F14

On NEC PC-98 Japanese keyboard

DIKEYBOARD_F15

On NEC PC-98 Japanese keyboard

DIKEYBOARD_G

DIKEYBOARD_GRAVE

GRAVE ACCENT (`)

DIKEYBOARD_H

DIKEYBOARD_HOME

DIKEYBOARD_I

DIKEYBOARD_INSERT

DIKEYBOARD_J

DIKEYBOARD_K

DIKEYBOARD_KANA

On Japanese keyboard

DIKEYBOARD_KANJI

On Japanese keyboard

DIKEYBOARD_L

DIKEYBOARD_LBRACKET

Left SQUARE BRACKET ([)

DIKEYBOARD_LCONTROL

Left CTRL

DIKEYBOARD_LEFT

LEFT ARROW

DIKEYBOARD_LMENU

Left ALT

DIKEYBOARD_LSHIFT

Left SHIFT

DIKEYBOARD_LWIN

Left Microsoft Windows logo key

DIKEYBOARD_M

DIKEYBOARD_MAIL

DIKEYBOARD_MEDIASELECT

MEDIA SELECT key, which displays a selection of supported media players on the system

DIKEYBOARD_MEDIASTOP

DIKEYBOARD_MINUS

On main keyboard

DIKEYBOARD_MULTIPLY

ASTERISK (*) on numeric keypad

DIKEYBOARD_MUTE

DIKEYBOARD_MYCOMPUTER

DIKEYBOARD_N

DIKEYBOARD_NEXT

PAGE DOWN

DIKEYBOARD_NEXTTRACK

NEXT TRACK

DIKEYBOARD_NOCONVERT

On Japanese keyboard

DIKEYBOARD_NUMLOCK

DIKEYBOARD_NUMPAD0

DIKEYBOARD_NUMPAD1

DIKEYBOARD_NUMPAD2

DIKEYBOARD_NUMPAD3

DIKEYBOARD_NUMPAD4

DIKEYBOARD_NUMPAD5

DIKEYBOARD_NUMPAD6

DIKEYBOARD_NUMPAD7

DIKEYBOARD_NUMPAD8

DIKEYBOARD_NUMPAD9

DIKEYBOARD_NUMPADCOMMA

On numeric keypad of NEC PC-98 Japanese keyboard

DIKEYBOARD_NUMPADENTER

DIKEYBOARD_NUMPADEQUALS

On numeric keypad of NEC PC-98 Japanese keyboard

DIKEYBOARD_O

DIKEYBOARD_OEM_102

On British and German keyboards

DIKEYBOARD_P

DIKEYBOARD_PAUSE

DIKEYBOARD_PERIOD

On main keyboard

DIKEYBOARD_PLAYPAUSE

DIKEYBOARD_POWER

DIKEYBOARD_PREVTRACK

PREVIOUS TRACK; CIRCUMFLEX (^) on Japanese keyboard

DIKEYBOARD_PRIOR

PAGE UP

DIKEYBOARD_Q

DIKEYBOARD_R

DIKEYBOARD_RBRACKET

Right SQUARE BRACKET (])

DIKEYBOARD_RCONTROL

Right CTRL

DIKEYBOARD_RETURN

ENTER on main keyboard

DIKEYBOARD_RIGHT

RIGHT ARROW

DIKEYBOARD_RMENU

Right ALT

DIKEYBOARD_RSHIFT

Right SHIFT

DIKEYBOARD_RWIN

Right Windows logo key

DIKEYBOARD_S

DIKEYBOARD_SCROLL

SCROLL LOCK

DIKEYBOARD_SEMICOLON

DIKEYBOARD_SLASH

FORWARD SLASH (/) on main keyboard

DIKEYBOARD_SLEEP

DIKEYBOARD_SPACE

SPACEBAR

DIKEYBOARD_STOP

On NEC PC-98 Japanese keyboard

DIKEYBOARD_SUBTRACT

MINUS SIGN (-) on numeric keypad

DIKEYBOARD_SYSRQ

DIKEYBOARD_T

DIKEYBOARD_TAB

DIKEYBOARD_U

DIKEYBOARD_UNDERLINE

On NEC PC-98 Japanese keyboard

DIKEYBOARD_UNLABELED

On Japanese keyboard

DIKEYBOARD_UP

UP ARROW

DIKEYBOARD_V

DIKEYBOARD_VOLUMEDOWN

DIKEYBOARD_VOLUMEUP

DIKEYBOARD_W

DIKEYBOARD_WAKE

DIKEYBOARD_WEBBACK

DIKEYBOARD_WEBFAVORITES

Displays the Microsoft Internet Explorer Favorites list, the Windows Favorites folder, or the Netscape Bookmarks list

DIKEYBOARD_WEBFORWARD

DIKEYBOARD_WEBHOME

DIKEYBOARD_WEBREFRESH

DIKEYBOARD_WEBSEARCH

DIKEYBOARD_WEBSTOP

DIKEYBOARD_X

DIKEYBOARD_Y

DIKEYBOARD_YEN

On Japanese keyboard

DIKEYBOARD_Z

Enumerated Type Information

Minimum operating systems Windows 98, Windows NT 2000, Windows XP


Mouse Mapping Enumerated Type

The following constants are used in the dwSemantic member of the DIACTION structure to map an action to a physical axis or button on a mouse.

Syntax

typedef enum {
    DIMOUSE_BUTTON0,
    DIMOUSE_BUTTON1,
    DIMOUSE_BUTTON2,
    DIMOUSE_BUTTON3,
    DIMOUSE_BUTTON4,
    DIMOUSE_BUTTON5,
    DIMOUSE_BUTTON6,
    DIMOUSE_BUTTON7,
    DIMOUSE_WHEEL,
    DIMOUSE_XAXIS,
    DIMOUSE_YAXIS,
    DIMOUSE_XAXISAB,
    DIMOUSE_YAXISAB
} Mouse Mapping;

Constants

DIMOUSE_BUTTON0

DIMOUSE_BUTTON1

DIMOUSE_BUTTON2

DIMOUSE_BUTTON3

DIMOUSE_BUTTON4

DIMOUSE_BUTTON5

DIMOUSE_BUTTON6

DIMOUSE_BUTTON7

DIMOUSE_WHEEL

DIMOUSE_XAXIS

DIMOUSE_YAXIS

DIMOUSE_XAXISAB

DIMOUSE_YAXISAB

Remarks

DIMOUSE_XAXISAB and DIMOUSE_YAXISAB represent the x-axis and y-axis on a mouse that returns absolute rather than relative axis data.

Enumerated Type Information

Minimum operating systems Windows 98, Windows NT 2000, Windows XP


Return Values Enumerated Type

The list below contains the HRESULT values that can be returned by Microsoft DirectInput methods and functions. Errors are represented by negative values and cannot be combined.

For a list of the error values each method or function can return, see the individual descriptions. Lists of error codes in the documentation are necessarily incomplete. For example, any DirectInput method can return DIERR_OUTOFMEMORY even though the error code is not explicitly listed as a possible return value in the documentation for that method.

Syntax

typedef enum {
    DI_BUFFEROVERFLOW,
    DI_DOWNLOADSKIPPED,
    DI_EFFECTRESTARTED,
    DI_NOEFFECT,
    DI_NOTATTACHED,
    DI_OK,
    DI_POLLEDDEVICE,
    DI_PROPNOEFFECT,
    DI_SETTINGSNOTSAVED,
    DI_TRUNCATED,
    DI_TRUNCATEDANDRESTARTED,
    DI_WRITEPROTECT,
    DIERR_ACQUIRED,
    DIERR_ALREADYINITIALIZED,
    DIERR_BADDRIVERVER,
    DIERR_BETADIRECTINPUTVERSION,
    DIERR_DEVICEFULL,
    DIERR_DEVICENOTREG,
    DIERR_EFFECTPLAYING,
    DIERR_GENERIC,
    DIERR_HANDLEEXISTS,
    DIERR_HASEFFECTS,
    DIERR_INCOMPLETEEFFECT,
    DIERR_INPUTLOST,
    DIERR_INVALIDPARAM,
    DIERR_MAPFILEFAIL,
    DIERR_MOREDATA,
    DIERR_NOAGGREGATION,
    DIERR_NOINTERFACE,
    DIERR_NOTACQUIRED,
    DIERR_NOTBUFFERED,
    DIERR_NOTDOWNLOADED,
    DIERR_NOTEXCLUSIVEACQUIRED,
    DIERR_NOTFOUND,
    DIERR_NOTINITIALIZED,
    DIERR_OBJECTNOTFOUND,
    DIERR_OLDDIRECTINPUTVERSION,
    DIERR_OTHERAPPHASPRIO,
    DIERR_OUTOFMEMORY,
    DIERR_READONLY,
    DIERR_REPORTFULL,
    DIERR_UNPLUGGED,
    DIERR_UNSUPPORTED,
    E_HANDLE,
    E_PENDING,
    E_POINTER
} Return Values;

Constants

DI_BUFFEROVERFLOW

The device buffer overflowed and some input was lost. This value is equal to the S_FALSE standard COM return value.

DI_DOWNLOADSKIPPED

The parameters of the effect were successfully updated, but the effect could not be downloaded because the associated device was not acquired in exclusive mode.

DI_EFFECTRESTARTED

The effect was stopped, the parameters were updated, and the effect was restarted.

DI_NOEFFECT

The operation had no effect. This value is equal to the S_FALSE standard Component Object Model (COM) return value.

DI_NOTATTACHED

The device exists but is not currently attached to the user's computer. This value is equal to the S_FALSE standard COM return value.

DI_OK

The operation completed successfully. This value is equal to the S_OK standard COM return value.

DI_POLLEDDEVICE

The device is a polled device. As a result, device buffering does not collect any data and event notifications is not signaled until the IDirectInputDevice8::Poll method is called.

DI_PROPNOEFFECT

The change in device properties had no effect. This value is equal to the S_FALSE standard COM return value.

DI_SETTINGSNOTSAVED

The action map was applied to the device, but the settings could not be saved.

DI_TRUNCATED

The parameters of the effect were successfully updated, but some of them were beyond the capabilities of the device and were truncated to the nearest supported value.

DI_TRUNCATEDANDRESTARTED

Equal to DI_EFFECTRESTARTED | DI_TRUNCATED.

DI_WRITEPROTECT

A SUCCESS code indicating that settings cannot be modified.

DIERR_ACQUIRED

The operation cannot be performed while the device is acquired.

DIERR_ALREADYINITIALIZED

This object is already initialized

DIERR_BADDRIVERVER

The object could not be created due to an incompatible driver version or mismatched or incomplete driver components.

DIERR_BETADIRECTINPUTVERSION

The application was written for an unsupported prerelease version of DirectInput.

DIERR_DEVICEFULL

The device is full.

DIERR_DEVICENOTREG

The device or device instance is not registered with DirectInput. This value is equal to the REGDB_E_CLASSNOTREG standard COM return value.

DIERR_EFFECTPLAYING

The parameters were updated in memory but were not downloaded to the device because the device does not support updating an effect while it is still playing.

DIERR_GENERIC

An undetermined error occurred inside the DirectInput subsystem. This value is equal to the E_FAIL standard COM return value.

DIERR_HANDLEEXISTS

The device already has an event notification associated with it. This value is equal to the E_ACCESSDENIED standard COM return value.

DIERR_HASEFFECTS

The device cannot be reinitialized because effects are attached to it.

DIERR_INCOMPLETEEFFECT

The effect could not be downloaded because essential information is missing. For example, no axes have been associated with the effect, or no type-specific information has been supplied.

DIERR_INPUTLOST

Access to the input device has been lost. It must be reacquired.

DIERR_INVALIDPARAM

An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard COM return value.

DIERR_MAPFILEFAIL

An error has occurred either reading the vendor-supplied action-mapping file for the device or reading or writing the user configuration mapping file for the device.

DIERR_MOREDATA

Not all the requested information fit into the buffer.

DIERR_NOAGGREGATION

This object does not support aggregation.

DIERR_NOINTERFACE

The object does not support the specified interface. This value is equal to the E_NOINTERFACE standard COM return value.

DIERR_NOTACQUIRED

The operation cannot be performed unless the device is acquired.

DIERR_NOTBUFFERED

The device is not buffered. Set the DIPROP_BUFFERSIZE property to enable buffering.

DIERR_NOTDOWNLOADED

The effect is not downloaded.

DIERR_NOTEXCLUSIVEACQUIRED

The operation cannot be performed unless the device is acquired in DISCL_EXCLUSIVE mode.

DIERR_NOTFOUND

The requested object does not exist.

DIERR_NOTINITIALIZED

This object has not been initialized.

DIERR_OBJECTNOTFOUND

The requested object does not exist.

DIERR_OLDDIRECTINPUTVERSION

The application requires a newer version of DirectInput.

DIERR_OTHERAPPHASPRIO

Another application has a higher priority level, preventing this call from succeeding. This value is equal to the E_ACCESSDENIED standard DirectInput return value. This error can be returned when an application has only foreground access to a device but is attempting to acquire the device while in the background.

DIERR_OUTOFMEMORY

The DirectInput subsystem could not allocate sufficient memory to complete the call. This value is equal to the E_OUTOFMEMORY standard COM return value.

DIERR_READONLY

The specified property cannot be changed. This value is equal to the E_ACCESSDENIED standard COM return value.

DIERR_REPORTFULL

More information was requested to be sent than can be sent to the device.

DIERR_UNPLUGGED

The operation could not be completed because the device is not plugged in.

DIERR_UNSUPPORTED

The function called is not supported at this time. This value is equal to the E_NOTIMPL standard COM return value.

E_HANDLE

The HWND parameter is not a valid top-level window that belongs to the process.

E_PENDING

Data is not yet available.

E_POINTER

An invalid pointer, usually NULL, was passed as a parameter.

Enumerated Type Information

Minimum operating systems Windows 98, Windows NT 2000, Windows XP


DirectSound

This section provides information about using Microsoft® DirectSound® to play and capture sounds in applications written in C and C++.

Information is presented in the following sections:

  • What's New in DirectSound. A guide to new features of DirectSound in Microsoft DirectX® 9.0.
  • Introduction to DirectSound. An overview of what DirectSound is and what it can do for your application, a comparison of DirectSound and Microsoft DirectMusic®, and a brief first look at the steps your application must take to play sounds.
  • Getting Started with DirectSound. Information on setting up and debugging DirectSound projects.
  • Using DirectSound. A guide to using the application programming interface (API). You'll probably want to familiarize yourself with the table of contents for this section, and then refer to parts of it as you need specific information. It should be used in conjunction with the reference section.
  • Advanced Topics in DirectSound. Information of interest mostly for developing specialized applications or applications that need highly optimized performance.
  • DirectSound C++ Samples. A guide to the sample applications in the SDK, to point you to the sample code you need. As well as showing how to implement basic functionality, each sample demonstrates one or more particular features of DirectSound.
  • DirectSound C/C++ Reference. Detailed information about all the API elements declared in Dsound.h.


What's New in DirectSound

The DirectSound application programming interface (API) has not been significantly revised for DirectX 9.0. However, many performance enhancements have been implemented.

In addition, the following changes have been made:

  • The maximum frequency of sound buffers has been increased from 100 kHz to 200 kHz, where supported by the operating system. (These higher frequencies are not supported by DirectShow.)
  • Frequency and effects controls (DSBCAPS_CTRLFREQUENCY and DSBCAPS_CRTLFX) can now be combined on buffers. Combining these flags makes it possible to have Doppler shift on buffers with effects.
  • Audio formats described by the WAVEFORMATEXTENSIBLE structure are fully supported throughout DirectSound.
  • The standard effect DMOs can process audio data in WAVE_FORMAT_IEEE_FLOAT format.
  • The standard effects support parameter curves (when hosted outside of DirectSound) without having to call IMediaObjectInPlace::Process on them repeatedly in very small increments.


Introduction to DirectSound

This section provides a quick overview of the capabilities of DirectSound and what you need to do to get started with the API. Information is presented in the following sections:

  • The Power of DirectSound
  • DirectSound and DirectMusic


The Power of DirectSound

DirectSound enables the playing of sounds with very low latency and gives applications a high level of control over hardware resources.

By using the DirectSound interfaces in your application, you can do the following:

  • Play sounds from files or resources in WAV format.
  • Play multiple sounds simultaneously.
  • Assign high-priority sounds to hardware-controlled buffers.
  • Locate sounds in a customizable 3-D environment.
  • Add effects such as echo and chorus, and change effect parameters dynamically.
  • Capture WAV sounds from a microphone or other input.

DirectSound works on Microsoft® Windows® 98, Microsoft® Windows® 2000, and later operating systems. Some functionality, chiefly capture effects, is available only on Microsoft Windows XP and later.

See Also

  • DirectSound and DirectMusic


DirectSound and DirectMusic

DirectSound and DirectMusic are separate components of DirectX with some overlapping functionality. Both play WAV sounds, and DirectMusic ultimately synthesizes all sounds into waveforms that are played through DirectSound buffers.

DirectMusic is a much more full-featured API that offers a complete solution for most audio scenarios in games and other interactive applications. Despite its name, DirectMusic plays all kinds of sounds including nonmusical sound effects. DirectSound is the API of choice for scenarios that require low-level management of hardware resources, such as games with many short sounds that must be played with the lowest possible latency and use of system resources.

You can use the DirectSound API independently to play WAV sounds, even in applications that use DirectMusic to play other content. You can also use DirectSound to manipulate sound buffers that are managed by DirectMusic. For example, you can obtain a DirectSound buffer from a DirectMusic audiopath and move it in 3-D space.

The following table summarizes the functionality offered by the two APIs.

Functionality | DirectMusic | DirectSound
Play WAV sounds | Yes | Yes
Play MIDI | Yes | No
Play DirectMusic Producer segments | Yes | No
Load content files and manage objects | Yes | No, but some support in sample code
Control musical parameters at run time | Yes | No
Manage timeline for cuing sounds | Yes | No
Use downloadable sounds (DLS) | Yes | No
Set volume, pitch, and pan of individual sounds | Yes, through DirectSound API | Yes
Set volume on multiple sounds (audiopaths) | Yes | No
Implement 3-D sounds | Yes, through DirectSound API | Yes
Apply effects (DMOs) | Yes, through DirectMusic Producer content or DirectSound API | Yes
Chain buffers for mix-in (send) effects | Yes, through DirectMusic Producer content | No
Capture WAV sounds | No | Yes
Implement full duplex | No | Yes
Capture MIDI | Yes | No
Control allocation of hardware buffers | No | Yes


Getting Started with DirectSound

This section gives information on setting up and debugging DirectSound projects, as well as a brief overview of the programming steps required to play a sound.

More information on getting started is included in the following topics:

  • Building DirectSound Projects
  • Debugging DirectSound Projects
  • Adjusting DirectSound Acceleration for Testing
  • First Steps in DirectSound Programming


Building DirectSound Projects

Projects need to include the Dsound.h header file. If you are using DirectSound in conjunction with DirectMusic, this header is included when you include Dmusici.h.

If you are using the DirectSound API directly and want to be able to use helper functions such as DirectSoundCreate8, be sure to link to Dsound.lib and include the appropriate folder in the library search path.

You must also ensure that your application has access to the GUIDs used by DirectSound. Define INITGUID before all other preprocessor directives, or link to Dxguid.lib.


Debugging DirectSound Projects

Note Support for debugging DirectSound has been removed from the DirectX 9.0 SDK Update (Summer 2004). The following instructions apply only to earlier versions of the SDK, available at the DirectX Downloads Web site.

The DirectSound dynamic-link library (DLL) installed with the debug version of the DirectX software development kit generates information in the debug output window as the application is running.

You can set the debug level within the range from 0 to 5 by using the Debug Output Level slider on the DirectSound page of the DirectX Properties in Control Panel. A setting of 0 produces no debugging information, and 5 produces the most detail. For most purposes it is unnecessary to set the level higher than 2; output at higher levels does not pertain to errors or warnings but is purely informational.


Adjusting DirectSound Acceleration for Testing

By using the Sounds and Audio Devices page in Control Panel, you can adjust the performance of DirectSound on the system. Click the Advanced button in the Sound Playback group on the Audio tab. In the Advanced Audio Properties dialog box, choose the Performance tab. A slider lets you adjust hardware acceleration to one of the following settings:

Full

Enables complete DirectSound acceleration, including the enabling of IKsPropertySet extensions.

Standard

Enables acceleration of DirectSound secondary buffers, but disables any hardware-specific IKsPropertySet extensions. This is the default setting on Windows 2000.

Basic

Disables hardware acceleration of DirectSound secondary buffers. This option is useful if you want to emulate a nonaccelerated sound card for testing purposes.

Emulation

Forces DirectSound into emulation mode, where it acts as if there is no DirectSound-compatible driver on the system. All mixing is done by DirectSound in user mode, and the resulting data is sent to the Win32 waveform-audio functions. This typically results in a large increase in latency.


First Steps in DirectSound Programming

This topic provides a brief overview of the steps you must take to play a sound by using the DirectSound API. For details, see Using DirectSound.

Playing a short sound requires the following steps:

1. Create a device object

Call DirectSoundCreate8 to create an object that supports the IDirectSound8 interface. This object usually represents the default playback device. Optionally, you can first enumerate available devices to obtain the GUID of the device you want to use, and pass this to DirectSoundCreate8.

Note DirectSound is based on the Component Object Model (COM). However, you do not have to initialize COM explicitly unless you are using effect DMOs.

2. Create a secondary buffer

Use IDirectSound8::CreateSoundBuffer to create a buffer object that will contain sound data. Such buffers are called secondary buffers, to distinguish them from the primary buffer, which is the object that mixes all sounds.

3. Obtain PCM data

Read data from a WAV file or resource into a private buffer. The DirectX SDK contains sample code that you can use to do this.

4. Put data in the buffer

Prepare the secondary buffer for a write operation by calling IDirectSoundBuffer8::Lock. In most cases, this method returns a single memory address. Copy data from your private buffer to that address, and then call IDirectSoundBuffer8::Unlock.

5. Play the buffer

Play the sound by calling IDirectSoundBuffer8::Play. You can instruct the buffer either to stop when it reaches the end, or to continue playing over and over again until you call IDirectSoundBuffer8::Stop. You can start and stop the buffer repeatedly; however, only one instance of the sound can play at one time, unless you create other buffers containing the same data. Any number of buffers can be played at a given time, and mixing is done automatically.

The preceding steps apply to the simplest possible scenario, that of a short sound that fits into a buffer of a reasonable size. Typically, sounds that last more than a few seconds are streamed: that is, data that has already been played is periodically replaced by new data.

Sample code distributed with the SDK shows how to perform many common tasks using DirectSound. For more information, see DirectSound C++ Samples.


Using DirectSound

This section is a guide to using the Microsoft® DirectSound® application programming interface (API) in application development.

Information is presented in the following topics:

  • DirectSound Playback Objects
  • DirectSound Devices
  • DirectSound Buffers
  • Using WAV Data
  • 3-D Sound
  • Using Effects
  • Capturing Waveforms

See Also

  • Introduction to DirectSound
  • Advanced Topics in DirectSound
  • DirectSound C/C++ Reference


DirectSound Playback Objects

The following objects are used in playing sounds:

Object | Number | Purpose | Main interfaces
Device | One in each application | Manages the device and creates sound buffers. | IDirectSound8
Secondary buffer | One for each sound | Manages a static or streaming sound and plays it into the primary buffer. | IDirectSoundBuffer8, IDirectSound3DBuffer8, IDirectSoundNotify8
Primary buffer | One in each application | Mixes and plays sounds from secondary buffers, and controls global 3-D parameters. | IDirectSoundBuffer, IDirectSound3DListener8
Effect | Zero or more for each secondary buffer | Transforms the sound in a secondary buffer. | Interface for the particular effect, such as IDirectSoundFXChorus8

The first step in implementing DirectSound in an application is to create a device object, which represents the rendering device. This object is then used to create buffers.

Note DirectSound is based on the Component Object Model (COM). However, you do not have to initialize COM explicitly, by calling CoInitialize or CoInitializeEx, unless you are using effect DMOs.

Secondary buffers are created and managed by the application. DirectSound automatically creates and manages the primary buffer, and an application can play sounds without obtaining an interface to this object. However, in order to obtain the IDirectSound3DListener8 interface, the application must explicitly create a primary buffer object.

When sounds in secondary buffers are played, DirectSound mixes them in the primary buffer and sends them to the rendering device. Only the available processing time limits the number of buffers that DirectSound can mix.

Note Under the Windows driver model (WDM), mixing is done by the kernel mixer, and the primary buffer does not actually contain any data. For more information, see DirectSound Driver Models.

A short sound can be loaded into a secondary buffer in its entirety and played at any time by a simple method call. Longer sounds have to be streamed. An application can ascertain when it is time to stream more data into the buffer either by polling the position of the play cursor or by requesting notification when the play cursor reaches certain points.

Secondary buffers can contain effects such as chorus and echo. They can also have 3-D control capabilities. Global 3-D parameters are controlled by the IDirectSound3DListener8 interface on the primary buffer.


DirectSound Devices

The DirectSound device object represents a rendering device and is used to manage the device and to create sound buffers.

Multiple applications can create objects for the same sound device. When the input focus changes between applications, the audio output automatically switches from one application's streams to the other's. As a result, applications do not have to repeatedly play and stop their buffers when the input focus changes.

This section describes how your application can enumerate available sound devices, create the device object, and use the IDirectSound8 methods of the object to manage the device. The following topics are covered:

  • Enumerating Sound Devices
  • Creating the Device Object
  • Cooperative Levels
  • Device Capabilities
  • Speaker Configuration


Enumerating Sound Devices

If your application is simply going to play sounds through the user's preferred playback device, there is no need to enumerate the available devices. When you create the device object by calling the DirectSoundCreate8 function, you can specify a default device. For more information, see Creating the Device Object.

Enumeration is necessary in the following situations:

  • Your application needs capabilities that may not be available on all devices.
  • Your application requires two or more devices.
  • You wish to offer the user a choice of devices.

Enumeration serves three purposes:

  • It reports what hardware is available.
  • It supplies a GUID for each device.
  • It enables you to create a temporary device object for each device as it is enumerated, so that you can check the capabilities of the device.

To enumerate devices, you must first set up a callback function that will be called once for each device on the system. You can do anything you want within this function, and you can give it any name, but you must declare it in the same form as the DSEnumCallback prototype. The callback function must return TRUE if enumeration is to continue, or FALSE otherwise—for instance, after finding a device with the capabilities you need.

The following callback function adds the name of each enumerated device to a combo box and stores its GUID as the item data. Values for the first three parameters are supplied by the device driver. The fourth parameter is passed on from the DirectSoundEnumerate function; this parameter can be used to pass any 32-bit value, and in this case is the window handle of the combo box. Macros defined in Windowsx.h are used to add strings and data to the combo box.

BOOL CALLBACK DSEnumProc(LPGUID lpGUID,
         LPCTSTR lpszDesc,
         LPCTSTR lpszDrvName,
         LPVOID lpContext )
{
  HWND hCombo = (HWND)lpContext;
  LPGUID lpTemp = NULL;

  if (lpGUID != NULL)  //  NULL only for "Primary Sound Driver".
  {
    if ((lpTemp = (LPGUID)malloc(sizeof(GUID))) == NULL)
    {
        return(TRUE);
    }
    memcpy(lpTemp, lpGUID, sizeof(GUID));
  }

  ComboBox_AddString(hCombo, lpszDesc);
  ComboBox_SetItemData(hCombo,
      ComboBox_FindString(hCombo, 0, lpszDesc),
      lpTemp );
  free(lpTemp);
  return(TRUE);
}

The enumeration is set in motion when the dialog box containing the combo box is initialized. Assume that hCombo is the handle of the combo box and hDlg is the handle of the dialog box.

if (FAILED(DirectSoundEnumerate((LPDSENUMCALLBACK)DSEnumProc,
    (VOID*)&hCombo)))
{
  EndDialog(hDlg, TRUE);
  return(TRUE);
}

In this case, the address of the combo box handle is passed into DirectSoundEnumerate, which in turn passes it to the callback function. This parameter can be any 32-bit value that you want to have access to within the callback.

Note The first device enumerated is always called the Primary Sound Driver, and the lpGUID parameter of the callback is NULL. This device represents the preferred playback device set by the user in Control Panel. It is enumerated separately to make it easy for the application to add "Primary Sound Driver" to a list when presenting the user with a choice of devices. The primary device is also enumerated with its proper name and GUID.


Creating the Device Object

The simplest way to create the device object is by using the DirectSoundCreate8 function. The first parameter of this function specifies the GUID of the device to be associated with the object. You can obtain this GUID by enumerating devices, or you can pass one of the following GUIDs to specify a default device:

GUID definition | Description
DSDEVID_DefaultPlayback | The default system audio device. You can also specify this device by passing a NULL pointer in the device GUID parameter. The default device is the one enumerated as "Primary DirectSound Driver".
DSDEVID_DefaultVoicePlayback | The default voice communications device. Typically this is a secondary device such as a USB headset with microphone.

If no device driver is present, the call to DirectSoundCreate8 fails.

The function returns an error if there is no sound device or, under VXD drivers, if the sound device is under the control of an application using the standard Win32 waveform-audio functions. You should prepare your applications for this call to fail so that they can either continue without sound or prompt the user to close the application that is already using the sound device.

The following code creates an object for the default device and obtains the IDirectSound8 interface:

LPDIRECTSOUND8 lpds;
HRESULT hr = DirectSoundCreate8(NULL, &lpds, NULL));

Note DirectSoundCreate8 does not cause CoInitialize or CoInitializeEx to be called. If your application uses effect DMOs, it must initialize COM explicitly before creating any objects.

If your application will capture sounds as well as play them, you can conveniently create both rendering and capture devices, as well as playback and capture buffers, by using the DirectSoundFullDuplexCreate8 function.

You can also create the device object by using standard COM functions, as follows.

  1. Initialize COM at the start of your application by calling CoInitializeEx.
    HRESULT hr = CoInitializeEx(NULL, 0);
if (FAILED(hr))
{
  ErrorHandler(hr);  // Add error-handling here.
}
  2. Create the device object by using CoCreateInstance and the IDirectSound8::Initialize method, rather than the DirectSoundCreate8 function.
    LPDIRECTSOUND8 lpds;
hr = CoCreateInstance(&CLSID_DirectSound8,
          NULL,
          CLSCTX_INPROC_SERVER,
          IID_IDirectSound8,
          (LPVOID*) &lpds);
if (FAILED(hr))
{
  ErrorHandler(hr);  // Add error-handling here.
}

    CLSID_DirectSound8 is the class identifier of the DirectSound driver object class and IID_IDirectSound8 is the interface identifier. The lpds parameter receives the interface pointer.

  3. Call the IDirectSound8::Initialize method to associate the object with a device. This method takes the same device GUID parameter that DirectSoundCreate8 uses.
    hr = lpds->Initialize(NULL);
if (FAILED(hr))
{
  ErrorHandler(hr);  // Add error-handling here.
}
  4. Before you close the application, close the COM library by calling the CoUninitialize function, as follows:
    CoUninitialize();


Cooperative Levels

Because Windows is a multitasking environment, more than one application can be working with a device driver at any one time. Through the use of cooperative levels, DirectX makes sure that each application does not gain access to the device in the wrong way or at the wrong time. Each DirectSound application has a cooperative level that determines the extent to which it is allowed to access the device.

After creating a device object, you must set the cooperative level for the device by using the IDirectSound8::SetCooperativeLevel method. Unless you do this, no sounds will be heard.

The following example sets the cooperative level for the DirectSound device represented by the IDirectSound8 interface at lpDirectSound. The hwnd parameter is the handle to the application window.

HRESULT hr = lpDirectSound->SetCooperativeLevel(hwnd, DSSCL_PRIORITY);
if (FAILED(hr))
{
  ErrorHandler(hr);  // Add error-handling here.
}

DirectSound defines three cooperative levels for sound devices, specified by the values DSSCL_NORMAL, DSSCL_PRIORITY, and DSSCL_WRITEPRIMARY. These levels are explained in the following topics:

  • Normal Cooperative Level
  • Priority Cooperative Level
  • Write-primary Cooperative Level

Note The DSSCL_EXCLUSIVE cooperative level is obsolete. It is no longer possible for a DirectX application to mute other applications. Applications that request the exclusive level are granted the priority level instead.


Normal Cooperative Level

At the normal cooperative level (DSSCL_NORMAL), the application cannot set the format of the primary buffer or write to the primary buffer. All applications at this cooperative level use a primary buffer format of 22 kHz, stereo sound, and 8-bit samples, so that the device can switch between applications as smoothly as possible.


Priority Cooperative Level

When using a DirectSound device with the priority cooperative level (DSSCL_PRIORITY), the application has first rights to hardware resources, such as hardware mixing, and can set the format of the primary sound buffer.

Game applications should use the priority cooperative level in almost all circumstances. This level gives the most robust behavior while allowing the application control over sampling rate and bit depth. The priority cooperative level also allows audio from other applications, such as IP telephony, to be heard along with the audio from the game.


Write-primary Cooperative Level

The highest cooperative level is write-primary (DSSCL_WRITEPRIMARY). When using a DirectSound device with this cooperative level, your application has direct access to the primary sound buffer on non-WDM drivers. In this mode, the application must write directly to the primary buffer. Secondary buffers cannot be played while this is happening.

An application must be set to the write-primary level in order to obtain direct write access to the audio samples in the primary buffer. If the application is not set to this level, then all calls to the IDirectSoundBuffer::Lock method on the primary buffer will fail.

Note The primary buffer supports only the IDirectSoundBuffer interface, not IDirectSoundBuffer8.

When your application is set to the write-primary cooperative level and gains the foreground, all secondary buffers for other applications are stopped and marked as lost. When your application in turn moves to the background, its primary buffer is marked as lost and must be restored when the application again moves to the foreground. For more information, see Buffer Management.

You cannot set the write-primary cooperative level if a DirectSound driver is not present on the user's system. To determine whether this is the case, call the IDirectSound8::GetCaps method and check for the DSCAPS_EMULDRIVER flag in the DSCAPS structure.

See Also

  • Writing to the Primary Buffer


Device Capabilities

DirectSound enables your application to examine the hardware capabilities of the sound device. Many applications do not need to do this, because DirectSound automatically takes advantage of any available hardware acceleration. However, high-performance applications can use the information to scale their sound requirements to the available hardware. For example, an application might choose to play more sounds if hardware mixing is available than if it is not.

After calling the DirectSoundCreate8 function to create a device object, your application can retrieve the capabilities of the sound device by calling the IDirectSound8::GetCaps method.

The following example retrieves the capabilities of the device represented by the IDirectSound8 interface pointer lpDirectSound:

DSCAPS dscaps;

dscaps.dwSize = sizeof(DSCAPS);
HRESULT hr = lpDirectSound->GetCaps(&dscaps);
if (FAILED(hr))
{
  ErrorHandler(hr);  // Add error-handling here.
}

The DSCAPS structure receives information about the performance and resources of the sound device, including the maximum resources of each type and the resources that are currently available. Note that the dwSize member of this structure must be initialized before the method is called.

If your application scales to hardware capabilities, you should call the IDirectSound8::GetCaps method between every buffer allocation to determine if there are enough resources to create the next buffer.


Speaker Configuration

DirectSound uses the speaker configuration—that is, the position of the speakers relative to the listener—to optimize 3-D effects for the user's sound system.

In Windows® 98, Windows 2000, and later operating systems, the speaker configuration can be set by the user in Control Panel. An application can retrieve this value by using IDirectSound8::GetSpeakerConfig. Applications should not override the setting by calling IDirectSound8::SetSpeakerConfig, as this is a global setting that affects other users and applications.


DirectSound Buffers

DirectSound buffer objects control the delivery of waveform data from a source to a destination. The source might be a synthesizer, another buffer, a WAV file, or a resource. For most buffers, the destination is a mixing engine called the primary buffer. From the primary buffer, the data goes to the hardware that converts the samples to sound waves.

Information about using DirectSound buffers is contained in the following topics:

  • Buffer Basics
  • Creating Secondary Buffers
  • Duplicating Buffers
  • Buffer Control Options
  • 3-D Algorithms for Buffers
  • Filling and Playing Static Buffers
  • Using Streaming Buffers
  • Playback Controls
  • Play and Write Cursors
  • Play Buffer Notification
  • Mixing Sounds
  • Looping Sounds
  • Buffer Management

For information about capture buffers, see Capturing Waveforms.


Buffer Basics

Your application must create at least one secondary sound buffer for storing and playing individual sounds.

A secondary buffer can exist throughout the life of an application, or it can be destroyed when no longer needed. It can be a static buffer that contains a single short sound, or a streaming buffer that is refreshed with new data as it plays. To limit demands on memory, long sounds should be played through streaming buffers that hold no more than a few seconds of data.

You mix sounds from different secondary buffers simply by playing them at the same time. Any number of secondary buffers can be played at one time, up to the limits of available processing power.

Secondary buffers are not all created alike. Characteristics of buffers include the following:

  • Format. The format of a buffer must match the format of the waveform data it plays.
  • Controls. Different buffers can have different controls, such as volume, frequency, and movement in two or three dimensions. When creating a buffer, you should specify only the controls you need; for example, don't create a 3-D buffer for a sound that isn't in a 3-D environment.
  • Location. A buffer can be in memory managed by hardware, or in memory managed by software. Hardware buffers are more efficient but limited in number. Hardware buffers are not supported in 64-bit operating systems.

See Also

  • DSBUFFERDESC


Creating Secondary Buffers

To create a buffer, call the IDirectSound8::CreateSoundBuffer method. This method returns a pointer to an IDirectSoundBuffer interface, from which the application can obtain an IDirectSoundBuffer8 interface.

The following example function creates a secondary sound buffer and returns the IDirectSoundBuffer8 interface.

HRESULT CreateBasicBuffer(LPDIRECTSOUND8 lpDirectSound, LPDIRECTSOUNDBUFFER8* ppDsb8)
{
  WAVEFORMATEX wfx;
  DSBUFFERDESC dsbdesc;
  LPDIRECTSOUNDBUFFER pDsb = NULL;
  HRESULT hr;

  // Set up WAV format structure.

  memset(&wfx, 0, sizeof(WAVEFORMATEX));
  wfx.wFormatTag = WAVE_FORMAT_PCM;
  wfx.nChannels = 2;
  wfx.nSamplesPerSec = 22050;
  wfx.nBlockAlign = 4;
  wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign;
  wfx.wBitsPerSample = 16;

  // Set up DSBUFFERDESC structure.

  memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
  dsbdesc.dwSize = sizeof(DSBUFFERDESC);
  dsbdesc.dwFlags =
    DSBCAPS_CTRLPAN | DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLFREQUENCY
    | DSBCAPS_GLOBALFOCUS;
  dsbdesc.dwBufferBytes = 3 * wfx.nAvgBytesPerSec;
  dsbdesc.lpwfxFormat = &wfx;

  // Create buffer.

  hr = lpDirectSound->CreateSoundBuffer(&dsbdesc, &pDsb, NULL);
  if (SUCCEEDED(hr))
  {
     hr = pDsb->QueryInterface(IID_IDirectSoundBuffer8, (LPVOID*) ppDsb8);
     pDsb->Release();
  }
  return hr;
}

The example function creates a streaming buffer large enough to hold 3 seconds of streaming data. Nonstreaming buffers should be made just large enough to accommodate the entire sound.

The DSBCAPS_GLOBALFOCUS flag in the example ensures that the buffer will continue playing even when the application window is not in the foreground. Without this flag, the buffer will be muted when another application or even a dialog box has the input focus.

If the location of a buffer is not specified, DirectSound places it in hardware-controlled memory if possible. Because hardware buffers are mixed by the sound card processor, they have much less impact on application performance.

If you wish to specify the location of a buffer rather than letting DirectSound decide where it belongs, set either the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flag in the DSBUFFERDESC structure. If the DSBCAPS_LOCHARDWARE flag is set and there are insufficient hardware resources, the buffer creation request fails.

To take advantage of the voice management features of DirectSound, specify the DSBCAPS_LOCDEFER flag when creating the buffer. This flag defers the allocation of resources for the buffer until it is played. For more information, see Dynamic Voice Management.

You can ascertain the location of an existing buffer by using the IDirectSoundBuffer8::GetCaps method and checking the dwFlags member of the DSBCAPS structure for either the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flags. One or the other is always specified.

Buffer objects are owned by the device object that created them. When the device object is released, all buffers created by that object are also released and should not be referenced.


Duplicating Buffers

You can create two or more secondary buffers containing the same data by using the IDirectSound8::DuplicateSoundBuffer method. You cannot duplicate the primary sound buffer. Because the duplicate buffer shares memory with the original buffer, changes to the data of one buffer will be reflected in duplicate buffers.


Buffer Control Options

When creating a sound buffer, your application must specify the control options needed for that buffer. This is done with the dwFlags member of the DSBUFFERDESC structure, which can contain one or more of the flags in the following table.

Flag | Description
DSBCAPS_CTRL3D | The sound source can be moved in 3—D space.
DSBCAPS_CTRLFX | Effects can be added to the buffer.
DSBCAPS_CTRLFREQUENCY | The frequency of the sound can be changed.
DSBCAPS_CTRLPAN | The sound source can be moved from left to right.
DSBCAPS_CTRLPOSITIONNOTIFY | Notification positions can be set on the buffer.
DSBCAPS_CTRLVOLUME | The volume of the sound can be changed.

Note that certain combinations of controls are not allowed. For more information, see DSBUFFERDESC.

To obtain the best performance on all sound cards, your application should specify only control options it will use.

DirectSound uses the control options in determining whether hardware resources can be allocated to sound buffers. For example, a device might support hardware buffers but provide no pan control on those buffers. In this case, DirectSound would use hardware acceleration only if the DSBCAPS_CTRLPAN flag was not specified.

If your application attempts to use a control that a buffer lacks, the method call fails. For example, if you attempt to change the volume by using the IDirectSoundBuffer8::SetVolume method, the method can succeed only if the DSBCAPS_CTRLVOLUME flag was specified when the buffer was created. Otherwise the method fails and returns the DSERR_CONTROLUNAVAIL error code.

See Also

  • Playback Controls


3-D Algorithms for Buffers

When you create a secondary buffer with the DSBCAPS_CTRL3D control flag, you can also specify an algorithm to be used in spatializing the sound if the buffer is in software. By default, no head-related transfer function (HRTF) processing is performed, and the location of the sound relative to the listener is indicated by panning and volume only. You can request two levels of HRTF for the buffer.

For more information, see DSBUFFERDESC.


Filling and Playing Static Buffers

A secondary buffer that contains an entire self-contained sound is called a static buffer. Although it is possible to reuse the same buffer for different sounds, typically data is written to a static buffer only once.

Static buffers are created and managed just like streaming buffers. The only difference is in the way they are used: static buffers are filled once and then played, but streaming buffers are constantly refreshed with data as they are playing.

Note A static buffer is not necessarily one created by setting the DSBCAPS_STATIC flag in the buffer description. This flag requests allocation of memory on the sound card, which is not available on most modern hardware. A static buffer can exist in system memory and can be created with either the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flag.

Loading data into a static buffer is a three-step process:

  1. Lock the entire buffer by using IDirectSoundBuffer8::Lock. You specify the offset within the buffer where you intend to begin writing (normally 0), and get back the memory address of that point.
  2. Write the audio data to the returned address by using a standard memory-copy routine.
  3. Unlock the buffer using IDirectSoundBuffer8::Unlock.

These steps are shown in the following example, where lpdsbStatic is an IDirectSoundBuffer8 interface pointer and pbData is the address of the data source:

LPVOID lpvWrite;
DWORD  dwLength;

if (DS_OK == lpdsbStatic->Lock(
      0,          // Offset at which to start lock.
      0,          // Size of lock; ignored because of flag.
      &lpvWrite,  // Gets address of first part of lock.
      &dwLength,  // Gets size of first part of lock.
      NULL,       // Address of wraparound not needed.
      NULL,       // Size of wraparound not needed.
      DSBLOCK_ENTIREBUFFER))  // Flag.
{
  memcpy(lpvWrite, pbData, dwLength);
  lpdsbStatic->Unlock(
      lpvWrite,   // Address of lock start.
      dwLength,   // Size of lock.
      NULL,       // No wraparound portion.
      0);         // No wraparound size.
}
else
(
  ErrorHandler();  // Add error-handling here.
}

To play the buffer, call IDirectSoundBuffer8::Play, as in the following example:

lpdsbStatic->SetCurrentPosition(0);
HRESULT hr = lpdsbStatic->Play(
    0,  // Unused.
    0,  // Priority for voice management.
    0); // Flags.
if (FAILED(hr))
(
  ErrorHandler();  // Add error-handling here.
}

Because the DSBPLAY_LOOPING flag is not set in the example, the buffer automatically stops when it reaches the end. You can also stop it prematurely by using IDirectSoundBuffer8::Stop. When you stop a buffer prematurely, the play cursor position remains where it is. Hence the call to IDirectSoundBuffer8::SetCurrentPosition in the example, which ensures that the buffer starts from the beginning.


Using Streaming Buffers

A streaming buffer plays a long sound that cannot all fit into the buffer at once. As the buffer plays, old data is periodically replaced with new data.

To play a streaming buffer, call the IDirectSoundBuffer8::Play method, specifying DSBPLAY_LOOPING in the dwFlags parameter.

To halt playback, call the IDirectSoundBuffer8::Stop method. This method stops the buffer immediately, so you need to be sure that all data has been played. This can be done by polling the play position or by setting a notification position.

Streaming into a buffer requires the following steps:

  1. Ascertain whether the buffer is ready to receive new data. This can be done either by polling the play cursor or by waiting for a notification.
  2. Lock a portion of the buffer by using IDirectSoundBuffer8::Lock. This method returns one or two addresses where data can now be written.
  3. Write the audio data to the returned address or addresses by using a standard memory-copy routine.
  4. Unlock the buffer using IDirectSoundBuffer8::Unlock.

The reason IDirectSoundBuffer8::Lock might return two addresses is that you can lock any number of bytes, up to the size of the buffer, regardless of the start point. If necessary, the locked portion wraps around to the beginning of the buffer. If it does, you have to perform two separate memory copies.

For example, say you lock 30,000 bytes beginning at offset 20,000 in a 40,000-byte buffer. When you call Lock in this case, it returns four values:

  • The memory address of offset 20,000.
  • The number of bytes locked from that point to the end of the buffer; that is, 20,000 bytes. You write this number of bytes to the first address.
  • The memory address of offset 0.
  • The number of bytes locked from that point; that is, 10,000 bytes. You write this number of bytes to the second address.

If no wraparound is necessary, the last two values are NULL and 0 respectively.

Although it's possible to lock the entire buffer, you must not do so while it is playing. Normally you refresh only a fraction of the buffer each time. For example, you might lock and write to the first quarter of the buffer as soon as the play cursor reaches the second quarter, and so on. You must never write to the part of the buffer that lies between the play cursor and the write cursor.

The following function writes data to a sound buffer, starting at the position passed in dwOffset:

BOOL AppWriteDataToBuffer(
    LPDIRECTSOUNDBUFFER8 lpDsb,  // The buffer.
    DWORD dwOffset,              // Our own write cursor.
    LPBYTE lpbSoundData,         // Start of our data.
    DWORD dwSoundBytes)          // Size of block to copy.
{
  LPVOID  lpvPtr1;
  DWORD dwBytes1;
  LPVOID  lpvPtr2;
  DWORD dwBytes2;
  HRESULT hr;

  // Obtain memory address of write block. This will be in two parts
  // if the block wraps around.

  hr = lpDsb->Lock(dwOffset, dwSoundBytes, &lpvPtr1,
      &dwBytes1, &lpvPtr2, &dwBytes2, 0);

  // If the buffer was lost, restore and retry lock.

  if (DSERR_BUFFERLOST == hr)
  {
    lpDsb->Restore();
    hr = lpDsb->Lock(dwOffset, dwSoundBytes,
        &lpvPtr1, &dwBytes1,
        &lpvPtr2, &dwBytes2, 0);
  }
  if (SUCCEEDED(hr))
  {
    // Write to pointers.

    CopyMemory(lpvPtr1, lpbSoundData, dwBytes1);
    if (NULL != lpvPtr2)
    {
      CopyMemory(lpvPtr2, lpbSoundData+dwBytes1, dwBytes2);
    }

    // Release the data back to DirectSound.

    hr = lpDsb->Unlock(lpvPtr1, dwBytes1, lpvPtr2,
    dwBytes2);
    if (SUCCEEDED(hr))
    {
      // Success.
      return TRUE;
    }
  }

  // Lock, Unlock, or Restore failed.

  return FALSE;
}

See Also

  • Play and Write Cursors
  • Play Buffer Notification
  • Reading WAV Data
  • Using Buffers Efficiently


Playback Controls

To retrieve and set the volume at which a buffer is played, your application can use the IDirectSoundBuffer8::GetVolume and IDirectSoundBuffer8::SetVolume methods. Setting the volume on the primary buffer changes the waveform-audio volume of the sound card. Volume is measured as hundredths of decibels (dB) of attenuation; it is not possible to amplify the default volume. Note that the decibel scale is not linear; a reduction in volume of 3 dB is equivalent to a halving of the sound energy, and sounds generally become inaudible long before the maximum attenuation of 100 dB is reached.

By calling the IDirectSoundBuffer8::GetFrequency and IDirectSoundBuffer8::SetFrequency methods, you can retrieve and set the frequency at which audio samples play. You cannot change the frequency of the primary buffer.

To retrieve and set the position of the sound source on the left-right axis, you can call the IDirectSoundBuffer8::GetPan and IDirectSoundBuffer8::SetPan methods. Buffers with 3-D capabilities cannot be panned.

In order to use any of these controls, you must set the appropriate flags when creating the buffer. See Buffer Control Options.


Play and Write Cursors

DirectSound maintains two pointers into the buffer: the play cursor and the write cursor. These positions are byte offsets into the buffer, not absolute memory addresses.

The IDirectSoundBuffer8::Play method always starts playing at the position of the play cursor. When a buffer is created, the play cursor is set to 0. As the buffer is played, the cursor moves and always points to the next byte of data to be played. When the buffer is stopped, the cursor remains where it is.

The write cursor is the point after which it is safe to write data into the buffer. The block between the play cursor and the write cursor is already committed to be played, and cannot be changed safely.

You might visualize the buffer as a clock face, with data written to it in a clockwise direction. The play cursor and the write cursor are like two hands sweeping around the face at the same speed, the write cursor always keeping a little ahead of the play cursor. If the play cursor points to the 1 and the write cursor points to the 2, it is only safe to write data after the 2. Data between the 1 and the 2 may already have been queued for playback by DirectSound and should not be touched.

The write cursor moves with the play cursor, not with data written to the buffer. If you're streaming data, you are responsible for maintaining your own pointer into the buffer to indicate where the next block of data should be written.

An application can retrieve the play and write cursors by calling the IDirectSoundBuffer8::GetCurrentPosition method. The IDirectSoundBuffer8::SetCurrentPosition method lets you move the play cursor. Applications do not control the position of the write cursor.

To ensure that the play cursor is reported as accurately as possible, always specify the DSBCAPS_GETCURRENTPOSITION2 flag when creating a secondary buffer. For more information, see DSBUFFERDESC.


Play Buffer Notification

DirectSound can notify your application when the play cursor reaches certain points in a buffer, or when the buffer stops. This can be useful in two common situations:

  • The application must take some action, such as playing another buffer, when a sound has finished playing.
  • The application is streaming data to the buffer, and needs to know when the play cursor reaches predefined points so that data that has been played can be replaced by new data.

Note If you are taking advantage of voice management, it's possible that a buffer could be terminated before a notification position is reached. See the Remarks for DSBPOSITIONNOTIFY.

Using the IDirectSoundNotify8::SetNotificationPositions method, you can set any number of points within the buffer where events are to be signaled. You cannot do this while the buffer is playing.

First you obtain a pointer to the IDirectSoundNotify8 interface. You can do this by using the buffer object's QueryInterface method. A separate interface must be obtained from each buffer on which you want to set notifications.

For each notification position, create an event object with the Win32 CreateEvent function. Put the handle to this event in the hEventNotify member of a DSBPOSITIONNOTIFY structure. In the dwOffset member of that structure, specify the offset within the buffer where you want the event to be signaled. Then pass the address of the structure—or of an array of structures, if you want to set more than one notification position—to SetNotificationPositions.

The following example function sets a single notification position. The event will be signaled when playback stops, either because the end of a nonlooping buffer has been reached, or because the application called the IDirectSoundBuffer8::Stop method. Assume that hMyEvent is a handle returned by CreateEvent and that lpDsbSecondary is a secondary buffer created with the DSBCAPS_CTRLPOSITIONNOTIFY flag.

HRESULT SetStopNotification(HANDLE hMyEvent,
        LPDIRECTSOUNDBUFFER8 lpDsbSecondary)
{
  LPDIRECTSOUNDNOTIFY8 lpDsNotify;
  DSBPOSITIONNOTIFY PositionNotify;
  HRESULT hr;

  if (SUCCEEDED(
      hr = lpDsbSecondary->QueryInterface(IID_IDirectSoundNotify8,
             (LPVOID*)&lpDsNotify)))
  {
    PositionNotify.dwOffset = DSBPN_OFFSETSTOP;
    PositionNotify.hEventNotify = hMyEvent;
    hr = lpDsNotify->SetNotificationPositions(1, &PositionNotify);
    lpDsNotify->Release();
  }
  return hr;
}

Notifications for hardware-controlled buffers are not provided reliably by all drivers; some may generate false notifications. To work around this problem, you can call IDirectSoundBuffer8::GetCurrentPosition whenever your application receives a notification, to be sure that the notification position has actually been reached. Another solution is to create the buffer in software.


Mixing Sounds

Secondary buffers played simultaneously are automatically mixed in the primary buffer. Under the Windows driver model, the mixing is done in the kernel mixer. Different secondary buffers can have different WAV formats (for example, different sampling rates), and sounds are converted to the format of the primary buffer or kernel mixer as necessary.

On VXD drivers, the DirectSound mixer produces the best sound quality if all your application's sounds use the same WAV format and the hardware output format is matched to the format of the sounds. If this is done, the mixer does not need to perform any format conversion. Your application can change the hardware output format by creating a primary sound buffer object and calling the IDirectSoundBuffer8::SetFormat method. To do this, you need the Priority Cooperative Level. You must set the format of the primary buffer before creating any secondary buffers. DirectSound will restore the hardware format to the format specified in the last call every time the application gains the input focus.

On WDM drivers, setting the primary buffer format has no effect. The format is determined by the kernel mixer. For more information, see DirectSound Driver Models.


Looping Sounds

DirectSound does not directly support looping within a buffer, or repetition of only a portion of a sound. (The DSBPLAY_LOOPING flag causes the entire buffer to play again when the play cursor reaches the end.) Although it is possible to implement looping on a static buffer by resetting the play cursor to the start of the loop each time it reaches the end of the loop, doing so might result in audio glitches, as DirectSound must discard any preprocessed data and begin preprocessing again.

To repeat a portion of a sound, play the sound in a streaming buffer and implement the loop in your source data.

See Also

  • Using Streaming Buffers


Buffer Management

The IDirectSoundBuffer8::GetCaps method retrieves the capabilities of the DirectSoundBuffer object.

Your application can use the IDirectSoundBuffer8::GetStatus method to determine if the buffer is playing or if it has stopped.

Use the IDirectSoundBuffer8::GetFormat method to retrieve information about the format of the sound data in a buffer. You also can use IDirectSoundBuffer8::SetFormat to set the format of the sound data in the primary buffer. For more information, see Mixing Sounds.

Note The SetFormat method cannot be called on secondary buffers. After a secondary buffer is created, its format is fixed. To play a sound that is in another format, you must create a new sound buffer with this format.

Memory for a sound buffer can be lost in certain situations: for example, when buffers are located in sound card memory and another application gains control of the hardware resources. Loss can also occur when an application with the write-primary cooperative level moves to the foreground; in this case, DirectSound makes all other sound buffers lost so that the foreground application can write directly to the primary buffer.

The DSERR_BUFFERLOST error code is returned when the IDirectSoundBuffer8::Lock or IDirectSoundBuffer8::Play method is called for a lost buffer. When the application that caused the loss either lowers its cooperative level from write-primary or moves to the background, other applications can attempt to reallocate the buffer memory by calling the IDirectSoundBuffer8::Restore method. If successful, this method restores the buffer memory and all other settings for the buffer, such as volume and pan settings. However, a restored buffer may not contain valid sound data, so the owning application should rewrite the data to the buffer.


Using WAV Data

Under the Windows driver model (WDM), DirectSound hardware buffers can play any uncompressed or compressed sound format that can be described in a WAVEFORMATEX or WAVEFORMATEXTENSIBLE structure, provided the format is supported by the hardware. Software buffers and non-WDM hardware buffers support only 8-bit and 16-bit uncompressed formats.

Waveform (or WAV) data is usually stored in files or resources in Resource Interchange File Format (RIFF). The data includes a description of the WAV format, including parameters such as the sampling rate and number of output channels.

More information on WAV sounds is included in the following topics:

  • Multichannel and High-Resolution WAV Formats
  • Reading WAV Data
  • Calculating the Duration of a WAV Sound


Multichannel and High-Resolution WAV Formats

On WDM drivers, DirectSound buffers support WAV formats that have more than two output channels, for speaker configurations such as 5.1, which has speakers at the front left, front center, front right, back left, and back right, plus a low-frequency enhancer. They also support formats with sample resolutions of greater than 16 bits.

Such formats can be described by a WAVEFORMATEXTENSIBLE structure. This structure is an extension of WAVEFORMATEX that configures the extra bytes specified by the WAVEFORMATEX.cbSize. A WAVEFORMATEXTENSIBLE structure can be cast as WAVEFORMATEX wherever the latter is expected, as for example in the DSBUFFERDESC structure. DirectSound recognizes multichannel and high-resolution formats by the WAVE_FORMAT_EXTENSIBLE tag in WAVEFORMATEX.wFormatTag.

You do not have to use the WAVEFORMATEXTENSIBLE type definition in your application in order to play multichannel or high-resolution files. You need only parse the file header correctly into a WAVEFORMATEX structure that contains the extra bytes specified by cbSize. For an example of how to allocate the WAVEFORMATEX structure, see the CWaveFile::ReadMMIO function in the DirectSound Sample Framework.

If the system is configured for fewer physical speakers than the number of channels specified in a multichannel WAV file, the audio data is mixed appropriately and output to the existing speakers.

DirectSound does not support effects or 3-D processing on buffers in a multichannel format. An attempt to create a buffer with the DSBCAPS_CTRL3D or DSBCAPS_CTRLFX flag and a multichannel WAV format will fail.

For more information on multichannel WAV formats, see Multiple Channel Audio Data and WAVE Files, available at www.microsoft.com.


Reading WAV Data

WAV files are in the Resource Interchange File Format (RIFF), which consists of a variable number of named chunks containing either header information (for example, the format of sound samples) or data (the samples themselves). The Win32 API supplies functions for opening and closing RIFF files, seeking to chunks, and so on. The names of these functions all start with "mmio".

To store WAV sounds in an executable, import your WAV files as resources and give them string names. Note that the CWaveFile Sample Class expects these resources to be of type "WAVE" or "WAV", and expects to find them in the executable module rather than a DLL.

The DirectSound API does not include methods for loading sound data. However, the Dsutil.cpp file used by many of the SDK sample applications implements several classes that can be used to create sound buffers from files, resources, or a memory location.

The basic steps involved in using the sample classes to initialize DirectSound and to create and load buffers are as follows:

  1. Create an object of the CSoundManager Sample Class.
  2. Call CSoundManager::Initialize to create the device object.
  3. Pass the name of a file or resource to CSoundManager::Create or a memory location to CSoundManager::CreateFromMemory. These methods return an object of the CSound Sample Class representing one or more static buffers just large enough to contain the data. (You can create multiple buffers to play several instances of the sound at the same time.) Alternatively, pass the name of a file or resource to CSoundManager::CreateStreaming. This method returns an object of the CStreamingSound Sample Class representing a single streaming buffer .
  4. Call the FillBufferWithSound method on the object retrieved in the preceding step. This reads the data from the file, resource, or memory location into the buffer. For a streaming buffer, it fills the buffer only with as much data as it can hold; to refresh the data as the buffer plays, use CStreamingSound::HandleWaveStreamNotification.

Note that the actual reading of data is done by a CWaveFile object that is a protected member of the CSound or CStreamingSound object. You do not normally need to use the CWaveFile class directly; however, you can refer to the implementation of this class for information on how to parse WAV data.

See Also

  • DirectSound Sample Framework


Calculating the Duration of a WAV Sound

The length of time a waveform will play is determined by the data size and the format. The data size and format can be retrieved by using the CWaveFile::GetSize and CWaveFile::GetFormat methods in the DirectSound sample framework.

The following example function returns the duration of a WAV file, in milliseconds:

DWORD GetSoundLength(LPSTR strFileName)
{
  CWaveFile* pWav;
  DWORD dwLen = 0;
  DWORD dwSize;
  WAVEFORMATEX* wfx;

  pWav = new CWaveFile();
  if (SUCCEEDED(pWav->Open(strFileName, NULL, WAVEFILE_READ)))
  {
    wfx = pWav->GetFormat();
    dwSize = pWav->GetSize();
    dwLen = (DWORD) (1000 * dwSize / wfx->nAvgBytesPerSec);
    pWav->Close();
  }
  if (pWav) delete pWav;
  return dwLen;
}

See Also

  • CWaveFile Sample Class
  • DirectSound Sample Framework
  • Reading WAV Data


3-D Sound

Using DirectSound, you can create a 3-D world for sounds that can be integrated with 3-D graphics. You can locate sound sources and the listener in space, apply Doppler shift to moving sounds, and control physical parameters such as the rate at which sound attenuates over distance.

DirectSound can create virtual 3-D effects on two speakers or a set of headphones. It will also take advantage of multichannel systems with WDM drivers if the user has selected a surround sound speaker configuration in Control Panel. For more information, see DSBUFFERDESC.

The following topics cover some general aspects of 3-D sound:

  • Coordinates of 3-D Space
  • Perception of Sound Positions

Information on how to use 3-D sound in an application is found in the following sections:

  • DirectSound 3-D Buffers
  • DirectSound 3-D Listeners


Coordinates of 3-D Space

The position, velocity, and orientation of sound sources and listeners in 3-D space are represented by Cartesian coordinates, which are values on three axes: the x-axis, the y-axis, and the z-axis. The axes are relative to a viewpoint established by the application. Values on the x-axis increase from left to right, on the y-axis from down to up, and on the z-axis from near to far.

The D3DVECTOR structure contains values describing position, velocity, or orientation on the three axes.

Conventionally, vectors are expressed as three values enclosed in parentheses and separated by commas, in the order (x, y, z).

For position, the values are in meters by default. If your application does not use the meter as its unit of measure for 3-D graphics, you can set a distance factor, which is a floating-point value representing meters per application-specified distance unit. For example, if your application uses feet, it could specify a distance factor of .3048, which is the number of meters in a foot. For more information, see Distance Factor.

For velocity, the vector describes the rate of movement along each axis in units per second. Again, the default unit is meters, but this can be changed by the application.

For orientation, the values are in arbitrary units and are relative to one another. If the base view of the 3-D world is facing north toward the horizon, and the orientation of the listener is (-1, 0, 1) the listener is facing northwest. Because the values within a vector are not in absolute units, the vector could equally well be expressed as (-5, 0, 5) or (-0.25, 0, 0.25).

You can see how vectors in 2-D space work by drawing them on a sheet of graph paper. Let the values increase from the bottom of the paper to the top and from left to right. A line drawn from (0, 0) to (1, 1) has the same orientation, or direction, as one drawn from (0, 0), to (5, 5). However, the second line indicates a greater distance, or velocity. 3-D vectors work in just the same way, with an additional axis in the up-down direction.


Perception of Sound Positions

In the real world, the perception of a sound's position in space is influenced by several factors. Not all of these factors are acoustical; one of the most important is sight. Clues from the sounds themselves include the following:

  • Overall loudness. As a sound source moves away from the listener, its perceived volume decreases at a fixed rate. This phenomenon is known as rolloff.
  • Interaural intensity difference. A sound coming from the listener's right sounds louder in the right ear than in the left.
  • Interaural time difference. A sound emitted by a source to the listener's right will arrive at the right ear slightly before it arrives at the left ear. The duration of this offset is approximately a millisecond.
  • Muffling. The shape and orientation of the ears ensures that sounds coming from behind the listener are slightly muffled compared with sounds coming from in front. In addition, if a sound is coming from the right, the sound reaching the left ear will be muffled by the mass of the listener's head as well as by the orientation of the left ear.
  • Effect of the earlobes. The pinnae, or folds of the ear, cause subtle changes to the pitch and timing of sounds arriving from different directions. The mathematics behind this effect are known as the head-related transfer function (HRTF).


DirectSound 3-D Buffers

Each sound source in a 3-D environment is represented by an IDirectSound3DBuffer8 interface. This interface is supported only by sound buffers created with the DSBCAPS_CTRL3D flag. Methods of the interface are used to set and retrieve parameters of a single sound source.

Applications must supply monaural sound sources when using the 3-D capabilities of DirectSound. If you attempt to create a buffer with the DSBCAPS_CTRL3D flag set and a WAV format with more than one channel, an error results.

This section describes how your applications can obtain and manage 3-D buffer objects.The following topics are discussed:

  • Obtaining the 3-D Buffer Object
  • Minimum and Maximum Distances
  • Processing Mode
  • Buffer Position and Velocity
  • Sound Cones
  • Batch Parameters for 3-D Buffers


Obtaining the 3-D Buffer Object

The IDirectSound3DBuffer8 interface is obtained from a secondary DirectSound buffer that has been created with the DSBCAPS_CTRL3D flag in the dwFlags member of the DSBUFFERDESC structure.

You can retrieve the IDirectSound3DBuffer8 interface by calling QueryInterface method on the buffer, as in the following sample code, where lpDsbSecondary is an IDirectSoundBuffer8 interface.

LPDIRECTSOUND3DBUFFER8 lpDs3dBuffer;

HRESULT hr = lpDsbSecondary->QueryInterface(IID_IDirectSound3DBuffer8,
                (LPVOID *)&lpDs3dBuffer);


Minimum and Maximum Distances

As a listener approaches a sound source, the sound gets louder; the volume doubles when the distance is halved. Past a certain point, however, it is not reasonable for the volume to continue to increase. This is the minimum distance for the sound source.

The minimum distance that you set for a sound determines how quickly that sound fades away with distance. For example, you might set this value to 100 meters for a jet engine and to 2 centimeters for a bee. With these settings, the jet engine is at half volume when 200 meters away from the listener, but the bee is at half volume when only 4 centimeters away.

The following illustration shows how minimum and maximum distance affect the volume of a jet engine and a bee at increasing distances.

Minimum and maximum distances

The default minimum distance for a sound buffer, DS3D_DEFAULTMINDISTANCE, is defined as 1 unit, or 1 meter at the default distance factor. Unless you change this value, the sound is at full volume when it is 1 meter away from the listener, at half volume at 2 meters, at quarter volume at 4 meters, and so on. For most sounds you will probably want to set a larger minimum distance so that the sound does not fade so rapidly as it moves away.

The maximum distance for a sound source is the distance beyond which the volume of the sound no longer decreases. The default maximum distance for a DirectSound 3-D buffer (DS3D_DEFAULTMAXDISTANCE) is 1 billion, meaning that in most cases the attenuation will continue to be calculated long after the sound has moved out of hearing range. To avoid unnecessary processing on software buffers under VXD drivers, applications should set a reasonable maximum distance and include the DSBCAPS_MUTE3DATMAXDISTANCE flag when creating the buffer. (In DirectMusic, this flag is automatically set on standard 3-D buffers created as part of an audiopath.)

The maximum distance can also be used to prevent a sound from becoming inaudible. For example, if you have set the minimum distance for a sound at 100 meters, that sound might become effectively inaudible at 1,000 meters or less. By setting the maximum distance at 800 meters, you ensure that the sound always has at least one-eighth of its maximum volume regardless of the distance. In this case, of course, you would not set the DSBCAPS_MUTE3DATMAXDISTANCE flag.

By default, distance values are expressed in meters.

To adjust the effect of distance on volume for all sound buffers, you can change the rolloff factor.

See Also

  • IDirectSound3DBuffer8::GetMinDistance
  • IDirectSound3DBuffer8::SetMinDistance
  • IDirectSound3DBuffer8::GetMaxDistance
  • IDirectSound3DBuffer8::SetMaxDistance
  • Distance Factor
  • Rolloff Factor


Processing Mode

Sound buffers have three processing modes: normal, head-relative, and disabled.

In normal mode (DS3DMODE_NORMAL), the sound source is positioned and oriented absolutely in world space. This is the default mode, and is used for sound sources that do not move and turn with the listener.

In head-relative mode (DS3DMODE_HEADRELATIVE), the 3-D properties of the sound source are all relative to the current position, velocity, and orientation of the listener. As the listener moves and turns, the buffer is automatically repositioned in world space. Head-relative mode can be used for sounds such as a fly buzzing around the listener's head. However, most sounds that travel with the listener don't have to be 3-D sounds at all.

In disabled mode (DS3DMODE_DISABLE), 3-D sound processing is disabled and the sound seems to originate from the center of the listener's head.

See Also

  • DS3DBUFFER
  • IDirectSound3DBuffer8::SetMode


Buffer Position and Velocity

As a sound source moves, it is up to the application to specify values for its position and velocity.

Position is measured in distance units along each of the three axes, relative to either world space or the listener, depending on the processing mode.

Velocity is measured in distance units per second along each of the three axes of a vector. By default, distance units are meters. Velocity is used by DirectSound only to calculate the effects of Doppler shift.

See Also

  • IDirectSound3DBuffer8::GetPosition
  • IDirectSound3DBuffer8::SetPosition
  • IDirectSound3DBuffer8::GetVelocity
  • IDirectSound3DBuffer8::SetVelocity
  • Distance Factor
  • Doppler Effect


Sound Cones

A sound with no orientation has the same amplitude at a given distance in all directions. A sound with an orientation is loudest in the direction of orientation. The model that describes the loudness of the oriented sound is called a sound cone. Sound cones are made up of an inside (or inner) cone and an outside (or outer) cone. The outside cone angle must always be equal to or greater than the inside cone angle.

At any angle within the inner cone, the volume of the sound is just what it would be if there were no cone, after taking into account the basic volume of the buffer, the distance from the listener, the listener's orientation, and so on.

At any angle outside the outer cone, the normal volume is attenuated by a factor set by the application. The outside cone volume is expressed in hundredths of decibels and is a negative value, because it represents attenuation from the default volume of 0.

Between the inner and outer cones is a zone of transition from the inside volume to the outside volume. The volume decreases as the angle increases.

The following illustration shows the concept of sound cones.

Every 3-D sound buffer has a sound cone, but by default a buffer behaves like an omnidirectional sound source, because the outside volume is not attenuated, and the inside and outside cone angles are 360 degrees. Unless the application changes these values, the sound does not have any apparent orientation.

Designing sound cones properly can add dramatic effects to your application. For example, you could position a sound source in the center of a room, setting its orientation toward an open door in a hallway. Then set the angle of the inside cone so that it extends to the width of the doorway, make the outside cone a bit wider, and set the outside cone volume to inaudible. A listener moving along the hallway will begin to hear the sound only when near the doorway, and the sound will be loudest as the listener passes in front of the open door.

See Also

  • IDirectSound3DBuffer8::GetConeAngles
  • IDirectSound3DBuffer8::SetConeAngles
  • IDirectSound3DBuffer8::GetConeOrientation
  • IDirectSound3DBuffer8::SetConeOrientation
  • IDirectSound3DBuffer8::GetConeOutsideVolume
  • IDirectSound3DBuffer8::SetConeOutsideVolume


Batch Parameters for 3-D Buffers

Applications can retrieve or set a 3-D sound buffer's parameters individually or in batches. If the sound source is moving, you might want to set multiple parameters such as position, orientation, and velocity all at once. You can do so by calling IDirectSound3DBuffer8::GetAllParameters to retrieve the current parameters, changing the appropriate parameters in the DS3DBUFFER structure, and passing the structure back to IDirectSound3DBuffer8::SetAllParameters.

Parameter changes can also be made more efficiently by flagging them as deferred and then executing them all at once. For more information, see Deferred Settings.


DirectSound 3-D Listeners

In a virtual 3-D environment as in the real world, sounds exist only in relation to a point of reception. The 3-D sound effects in a DirectX application are affected not only by the position, orientation, and velocity values of the sound sources, but also by the position, orientation, and velocity of the virtual listener.

By default, the listener is stationary at the zero point of all vectors, oriented with the nose toward the positive Z-axis and the top of the head toward the positive Y-axis. The application can change all these values to reflect the movement and facing of the user within virtual space. The listener object also controls the general parameters of the acoustic environment, such as the amount of Doppler shift and the rate of volume attenuation over distance.

This section describes how your application can obtain a listener object and manage global 3-D sound parameters. The following topics are discussed:

  • Obtaining the 3-D Listener
  • Spatial Parameters of the Listener
  • Distance Factor
  • Doppler Effect
  • Rolloff Factor
  • Batch Parameters for 3-D Listeners
  • Deferred Settings


Obtaining the 3-D Listener

Global sound parameters are set and retrieved by using the IDirectSound3DListener8 interface from the primary buffer. There is only one primary buffer in an application, and only one listener.

To obtain a listener interface, you must first create a primary buffer object by using the IDirectSound8::CreateSoundBuffer method, specifying the DSBCAPS_CTRL3D and DSBCAPS_PRIMARYBUFFER flags in the dwFlags member of the DSBUFFERDESC structure. Call the QueryInterface method on the resulting buffer to obtain a pointer to an IDirectSound3DListener8 interface for that buffer.

The following example function retrieves an interface to the listener.

GetListener(LPDIRECTSOUND8 lpds, LPDIRECTSOUND3DLISTENER8* ppListener)
{
  DSBUFFERDESC             dsbd;
  LPDIRECTSOUNDBUFFER      lpdsbPrimary;  // Cannot be IDirectSoundBuffer8.
  LPDIRECTSOUND3DLISTENER8 lp3DListener = NULL;
  HRESULT hr;

  ZeroMemory(&dsbd, sizeof(DSBUFFERDESC));
  dsbd.dwSize = sizeof(DSBUFFERDESC);
  dsbd.dwFlags = DSBCAPS_CTRL3D | DSBCAPS_PRIMARYBUFFER;

  if (SUCCEEDED(hr = lpds->CreateSoundBuffer(&dsbd, &lpdsbPrimary, NULL)))
  {
    hr = lpdsbPrimary->QueryInterface(IID_IDirectSound3DListener8,
                                 (LPVOID *)ppListener);
    lpdsbPrimary->Release();
  }
  return hr;
}


Spatial Parameters of the Listener

Like a sound source, the listener has a position, orientation, and velocity in the 3-D world.

The orientation of the listener is defined by the relationship between two vectors that share an origin at the center of the listener's head: the top and front vectors. The top vector points straight up through the top of the head, and the front vector points forward through the listener's face at right angles to the top vector, as in the following illustration.

By default, the front vector is (0.0, 0.0, 1.0), and the top vector is (0.0, 1.0, 0.0). The two vectors must always be at right angles to one another. If necessary, DirectSound will adjust the front vector so that it is at right angles to the top vector.

Position is measured in distance units along a vector.

Velocity is measured in distance units per second along a vector. By default, distance units are meters. Velocity is used by DirectSound only to calculate the effects of Doppler shift.

See Also

  • IDirectSound3DListener8::GetOrientation
  • IDirectSound3DListener8::SetOrientation
  • IDirectSound3DListener8::GetPosition
  • IDirectSound3DListener8::SetPosition
  • IDirectSound3DListener8::GetVelocity
  • IDirectSound3DListener8::SetVelocity


Distance Factor

The distance factor is the number of meters in a vector unit. By default, the distance factor is 1.0. If the velocity of a buffer is (2.0, 0.0, 0.0), the sound source is considered to be moving along the x-axis at 2 meters per second. Applications that are using a different unit of measurement for 3-D graphics vectors might want to change the distance factor accordingly.

Suppose, for example, that the basic unit of measurement in your application is the foot, or 0.3048 meters. You set the distance factor to 0.3048. From then on, you use feet in parameters to method calls, and they are automatically converted to meters.

The distance factor mainly affects Doppler shift, by changing the actual velocity represented by n units per second. It does not directly affect rolloff, because the rate of attenuation over distance is based on the minimum distance in vector units. If you set the minimum distance for a given sound at 2 units, the volume will be halved at a distance of 4 units, regardless of whether those units are in feet, meters, or any other measure. For more information, see Minimum and Maximum Distances.

See Also

  • IDirectSound3DListener8::GetDistanceFactor
  • IDirectSound3DListener8::SetDistanceFactor


Doppler Effect

DirectSound automatically creates Doppler shift effects for any buffer or listener that has a velocity. Effects are cumulative: if the listener and the sound buffer are both moving, the system automatically calculates the relative velocity and adjusts the Doppler effect accordingly.

In order to have realistic Doppler shift effects in your application, you must calculate the speed of any object that is moving and set the appropriate velocity for that sound source or listener. You are free to exaggerate or lessen this value in a particular case in order to create special effects. You can also globally increase or decrease Doppler shift by changing the Doppler factor.

The Doppler factor can range from DS3D_MINDOPPLERFACTOR to DS3D_MAXDOPPLERFACTOR, defined as 0.0 and 10.0 respectively. A value of 0 means no Doppler shift is applied to a sound. Every other value represents a multiple of the real-world Doppler shift.

See Also

  • IDirectSound3DListener8::GetDopplerFactor
  • IDirectSound3DListener8::SetDopplerFactor


Rolloff Factor

Rolloff is the amount of attenuation that is applied to sounds, based on the listener's distance from the sound source. DirectSound can ignore rolloff, exaggerate it, or give it the same effect as in the real world, depending on a global parameter called the rolloff factor.

The rolloff factor can range from DS3D_MINROLLOFFFACTOR to DS3D_MAXROLLOFFFACTOR, defined as 0.0 and 10.0 respectively. A value of DS3D_MINROLLOFFFACTOR means that sounds remain at full volume regardless of their distance from the listener. Every other value represents a multiple of the real-world rolloff.

The rolloff factor is global. To change the effect of distance for an individual sound buffer, you can set the minimum distance for the buffer.

See Also

  • IDirectSound3DListener8::GetRolloffFactor
  • IDirectSound3DListener8::SetRolloffFactor
  • Minimum and Maximum Distances


Batch Parameters for 3-D Listeners

Applications can retrieve or set a 3-D listener object's parameters individually or in batches. If the listener is moving, you might want to set multiple parameters such as position, orientation, and velocity all at once. You can do so by calling IDirectSound3DListener8::GetAllParameters to retrieve the current parameters, changing the appropriate parameters in the DS3DLISTENER structure, and passing the structure back to IDirectSound3DListener8::SetAllParameters.

Parameter changes can also be made more efficiently by flagging them as deferred and then executing them all at once. For more information, see Deferred Settings.


Deferred Settings

Every change to 3-D sound buffer and listener settings causes remixing, at the expense of CPU cycles. To minimize the performance impact of changing 3-D settings, set the DS3D_DEFERRED flag in the dwApply parameter of any of the IDirectSound3DListener8 or IDirectSound3DBuffer8 methods that change 3-D settings. Then call the IDirectSound3DListener8::CommitDeferredSettings method to execute all of the deferred commands at once.

Deferred settings are overwritten by immediate settings. For example, if you set the listener velocity to (1.0, 0.0, 0.0) with the DS3D_DEFERRED flag and then set it to (2.0, 0.0, 0.0) with the DS3D_IMMEDIATE flag, the velocity becomes (2.0, 0.0, 0.0) and does not change when CommitDeferredSettings is called.


Using Effects

DirectX provides support for effects processing of sounds by DirectX Media Objects (DMOs). A standard set of effects is available to every DirectX application. Other DMOs can be registered on the system. All the standard DMOs can process 8-bit or 16-bit PCM data, as well as 32-bit floating-point formats.

To implement effects, a DirectSound application must first call CoInitialize to initialize COM. Doing so does not preclude creating the device object by using DirectSoundCreate8.

Using the DirectSound API, it is not possible to create chains of effects, where the output of multiple buffers is mixed into another buffer containing an effect. Buffer chains are available, however, in content authored for DirectMusic.

To take advantage of hardware-specific effects, use the IKsPropertySet interface.

The following topics contain information on setting up and using effects:

  • Setting Effects on Buffers
  • Effect Parameters
  • Standard Effects
  • Audio Effect DMO Wizard


Setting Effects on Buffers

You can set any number of effects on a secondary buffer that was created with the DSBCAPS_CTRLFX flag in the DSBUFFERDESC structure. The buffer must be stopped and not locked. In DirectX 9.0, effects are never hardware-accelerated. It is possible to set an effect on a hardware buffer, but doing so confers no advantages.

Effects might not work smoothly on very small buffers. DirectSound does not permit the creation of effects-capable buffers that hold less than 150 milliseconds of data. This value is defined as DSBSIZE_FX_MIN.

The following sample function sets an echo effect on a buffer and displays the result in the output window of the development environment.

HRESULT SetEcho(LPDIRECTSOUNDBUFFER8 pDSBuffer)
{
  HRESULT hr;
  DWORD dwResults[1];  // One element for each effect.

  // Describe the effect.
  DSEFFECTDESC dsEffect;
  memset(&dsEffect, 0, sizeof(DSEFFECTDESC));
  dsEffect.dwSize = sizeof(DSEFFECTDESC);
  dsEffect.dwFlags = 0;
  dsEffect.guidDSFXClass = GUID_DSFX_STANDARD_ECHO;

  // Set the effect
  if (SUCCEEDED(hr = pDSBuffer->SetFX(1, &dsEffect, dwResults)))
  {
    switch (dwResults[0])
    {
      case DSFXR_LOCHARDWARE:
        OutputDebugString("Effect was placed in hardware.");
        break;
      case DSFXR_LOCSOFTWARE:
        OutputDebugString("Effect was placed in software.");
        break;
      case DSFXR_UNALLOCATED:
        OutputDebugString("Effect is not yet allocated to hardware or software.");
        break;
    }
  }
  return hr;
}


Effect Parameters

To set or retrieve parameters of sound effects, you must first obtain the appropriate interface to the buffer that contains the effect. The following interfaces give you access to parameters of the standard DMOs available on all systems.

  • IDirectSoundFXChorus8
  • IDirectSoundFXCompressor8
  • IDirectSoundFXDistortion8
  • IDirectSoundFXEcho8
  • IDirectSoundFXFlanger8
  • IDirectSoundFXGargle8
  • IDirectSoundFXI3DL2Reverb8
  • IDirectSoundFXParamEq8
  • IDirectSoundFXWavesReverb8

To obtain one of these interfaces, pass the corresponding IID to the QueryInterface method of the buffer containing the effect. For a list of IIDs, see DirectSound Interface GUIDs.


Standard Effects

This topic is an introduction to the sound effects provided with DirectX. The following effects are covered:

  • Chorus
  • Compression
  • Distortion
  • Echo
  • Environmental Reverberation
  • Flange
  • Gargle
  • Parametric Equalizer
  • Waves Reverberation


Chorus

Chorus is a voice-doubling effect created by echoing the original sound with a slight delay and slightly modulating the delay of the echo.

This effect is represented by the IDirectSoundFXChorus8 interface. Its parameters are contained in the DSFXChorus structure.


Compression

Compression is a reduction in the fluctuation of a signal above a certain amplitude.

This effect is represented by the IDirectSoundFXCompressor8 interface. Its parameters are contained in the DSFXCompressor structure.


Distortion

Distortion is achieved by adding harmonics to the signal in such a way that, as the level increases, the top of the waveform becomes squared off or clipped.

This effect is represented by the IDirectSoundFXDistortion8 interface. Its parameters are contained in the DSFXDistortion structure.


Echo

An echo effect causes an entire sound to be repeated after a fixed delay.

This effect is represented by the IDirectSoundFXEcho8 interface. Its parameters are contained in the DSFXEcho structure.


Environmental Reverberation

DirectX provides partial support for environmental reverberation in accordance with the Interactive 3-D Audio Level 2 (I3DL2) specification, published by the Interactive Audio Special Interest Group. The DirectX environmental reverb effect is an implementation of the listener properties in the I3DL2 specification. Source properties are not supported.

Sounds reaching the listener have three temporal components:

  • The direct path is the audio signal that goes straight from the sound source to the listener, without bouncing off any surface.
  • Early reflections are the audio signals that reach the listener after one or two reflections off surfaces such as the walls, floor, and ceiling. If a signal is the result of the sound hitting only one wall on its way to the listener, it is called a first-order reflection. If it bounces off two walls before reaching the listener, it is called a second-order reflection. Humans can typically perceive individual reflections only of the first or second order.
  • Late reverberation, or simply reverb, consists of the combined lower-order reflections, usually a dense succession of echoes of diminishing intensity.

The combination of early reflections and late reverberation is sometimes called the room effect.

Note In the DirectSound implementation, only the signal sent to the room effect is heard. To hear the direct path, play the sound simultaneously in another buffer that does not have the environmental reverb effect.

Reverberation properties include the following:

  • Attenuation of the early reflections and late reverberation.
  • Rolloff factor, or the rate at which reflected signals become attenuated with distance. The rolloff factor for the direct path is managed by the DirectSound listener.
  • Reflections delay. This is the interval between the arrival of the direct-path signals and the arrival of the first early reflections.
  • Reverb delay. This is the interval between the first of the early reflections and the onset of late reverberation.
  • Decay time. This is the interval between the onset of late reverberation and the time when its intensity has been reduced by 60 dB.
  • Diffusion, which is proportional to the number of echos per second in the late reverberation. Depending on the implementation, the density of echos can change as the reverberation decays. In DirectX, the application can control this property by setting a percentage of the range allowed by the implementation.
  • Density, which is is proportional to the number of resonances per hertz in the late reverberation. Lower densities produce hollower sounds like those found in small rooms. In DirectX, the application can control this property by setting a percentage of the range allowed by the implementation.

Reverb properties are represented by an IDirectSoundFXI3DL2Reverb8 interface, and the parameters of the environment are contained in a DSFXI3DL2Reverb structure.

DirectX supports many sets of default parameters, or presets, that describe the reverb properties of audio environments ranging from mountains to sewer pipes. Most applications can simply choose one of these environments by using IDirectSoundFXI3DL2Reverb8::SetPreset.

To set custom properties, use IDirectSoundFXI3DL2Reverb8::SetAllParameters. You can retrieve the current properties by using IDirectSoundFXI3DL2Reverb8::GetAllParameters.


Flange

Flange is an echo effect in which the delay between the original signal and its echo is very short and varies over time. The result is sometimes referred to as a sweeping sound. The term flange originated with the practice of grabbing the flanges of a tape reel to change the speed.

This effect is represented by the IDirectSoundFXFlanger8 interface. Its parameters are contained in the DSFXFlanger structure.


Gargle

The gargle effect modulates the amplitude of the signal.

This effect is represented by the IDirectSoundFXGargle8 interface. Its parameters are contained in the DSFXGargle structure.


Parametric Equalizer

A parametric equalizer amplifies or attenuates signals of a given frequency.

Parametric equalizer effects for different pitches can be applied in parallel by setting multiple instances of the GUID_DSFX_STANDARD_PARAMEQ effect on the same buffer. In this way, the application can have tone control similar to that provided by a hardware equalizer.

This effect is represented by the IDirectSoundFXParamEq8 interface. Its parameters are contained in the DSFXParamEq structure.


Waves Reverberation

The Waves reverberation effect is intended for use with music. The Waves reverberation DMO is based on the Waves MaxxVerb technology, which is licenced to Microsoft.

This effect is represented by the IDirectSoundFXWavesReverb8 interface. Its parameters are contained in the DSFXWavesReverb structure.


Audio Effect DMO Wizard

The Audio Effect DMO Wizard simplifies the task of creating a DirectX Media Object (DMO) that implements an audio effect that can be used in DirectSound buffers and in other applications.

Microsoft Visual C++® 6.0 is required to run the wizard. Select New from the File menu, and then select Audio Effect DMO Wizard from the Projects tab of the New dialog box.

The wizard creates a Visual Studio® project and several C++ code and header files, which implement the framework for the DMO. After the project is created, you must add code that implements the audio effect.

For more information, see the Help for the wizard.


Capturing Waveforms

DirectSound can be used to capture sounds, as an alternative to the Windows Multimedia functions such as waveInOpen. Other than support for acoustic echo cancellation (AEC), DirectSound offers no performance advantages over the Windows Multimedia functions.

The DirectSound capture device object, represented by the IDirectSoundCapture8 interface, is used to query the capabilities of sound capture devices and to create buffers for capturing audio from an input source. Data can be captured in PCM or compressed formats.

The DirectSound capture buffer object, represented by the IDirectSoundCaptureBuffer8 interface, represents a buffer used for receiving data from the input device. Like playback buffers, this buffer is conceptually circular: when input reaches the end of the buffer, it automatically starts again at the beginning.

The methods of IDirectSoundCaptureBuffer8 enable you to retrieve the properties of the buffer, start and stop audio capture, and lock portions of the memory, so that you can safely retrieve data for saving to a file or for playback in a full-duplex implementation. On operating systems that support capture effects, this interface also provides methods for retrieving DMOs and ascertaining the status of effects.

More information about waveform capture is found in the following topics:

  • Enumerating Capture Devices
  • Creating the Capture Device Object
  • Capture Device Capabilities
  • Creating a Capture Buffer
  • Capture Buffer Information
  • Capture Buffer Notification
  • Capture Buffer Effects
  • Using the Capture Buffer
  • Writing to a WAV File


Enumerating Capture Devices

If your application is simply going to capture sounds through the user's preferred capture device, there is no need to enumerate the available devices. When you create the device object by calling the DirectSoundCaptureCreate8 or DirectSoundFullDuplexCreate8 function, you can specify a default device. For more information, see Creating the Capture Device Object.

Enumeration is necessary in the following situations:

  • Your application needs capabilities that may not be available on all devices.
  • Your application requires two or more devices.
  • You wish to offer the user a choice of devices.

Enumeration serves three purposes:

  • It reports what hardware is available.
  • It supplies a GUID for each device.
  • It enables you to create a temporary device object for each device as it is enumerated, so that you can check the capabilities of the device.

To enumerate devices, you must first set up a callback function that will be called once for each device on the system. You can do anything you want within this function, and you can give it any name, but you must declare it in the same form as the DSEnumCallback prototype. The callback function must return TRUE if enumeration is to continue, or FALSE otherwise—for instance, after finding a device with the capabilities you need.

For a sample callback function, see Enumerating Sound Devices.

The enumeration is set in motion by using the DirectSoundCaptureEnumerate function, as follows:

DWORD pv;  // Can be any 32-bit type.

HRESULT hr = DirectSoundCaptureEnumerate(
    (LPDSENUMCALLBACK)DSEnumProc, (VOID*)&pv);

The second parameter can be any 32-bit value that you want to have access to within the callback.

Note The first device enumerated is always called the Primary Sound Capture Driver, and the lpGUID parameter of the callback is NULL. This device represents the preferred capture device set by the user in Control Panel. It is enumerated separately to make it easy for the application to add "Primary Sound Capture Driver" to a list when presenting the user with a choice of devices. The primary capture device is also enumerated with its proper name and GUID.


Creating the Capture Device Object

You can create the capture device object by calling either the DirectSoundCaptureCreate8 or the DirectSoundFullDuplexCreate8 function. Both these functions retrieve a pointer to the IDirectSoundCapture8 interface.

The lpcGUID parameter to DirectSoundCaptureCreate, or the pcGuidRenderDevice parameter to DirectSoundFullDuplexCreate8, can be a GUID obtained by enumeration, or it can be one of the following predefined GUIDs:

GUID | Description
DSDEVID_DefaultCapture | The default system capture device. You can also specify this device by passing a NULL pointer instead of a device GUID.
DSDEVID_DefaultVoiceCapture | The default voice communications capture device. Typically, this is a secondary device such as a USB headset with microphone.

If no device driver is present, the call fails.

You can also use the CoCreateInstance function to create the object. The procedure is similar to that for the device object; see Creating the Device Object. If you use CoCreateInstance, the object is created for the default capture device selected by the user in Control Panel.

If you want playback and capture device objects to coexist, then you should create and initialize the playback device object before creating and initializing the capture device object, or use DirectSoundFullDuplexCreate8.

Some audio devices aren't configured for full duplex audio by default. If your application has problems with creating and initializing both a playback device object and a capture device object, you should advise the user to check the audio device properties to ensure that full duplex is enabled.


Capture Device Capabilities

To retrieve the capabilities of a capture device, call the IDirectSoundCapture8::GetCaps method. The parameter to this method is a pointer to a DSCCAPS structure. As with other such structures, you have to initialize the dwSize member before passing it. On return, the structure contains the number of channels the device supports, as well as a combination of values for supported formats, equivalent to the values in the WAVEINCAPS structure used in the Win32 waveform audio functions.

On non-WDM drivers, a capture device can be used by only one application at a time. If the driver supports simultaneous use of the device by more than one application, DSCCAPS_MULTIPLECAPTURE is returned in the dwFlags member of DSCCAPS. Each application can set its own format for the capture buffer.


Creating a Capture Buffer

To create a capture buffer, call the IDirectSoundCapture8::CreateCaptureBuffer method.

One of the parameters to the method is a DSCBUFFERDESC structure that describes the characteristics of the desired buffer. The last member of this structure is a WAVEFORMATEX structure, which must be initialized with the details of the desired WAV format.

Note that if your application is playing sounds as well as capturing them, capture buffer creation can fail when the format of the capture buffer is not the same as that of the primary buffer. The reason is that some cards have only a single clock and cannot support capture and playback at two different frequencies.

The following example function creates a capture buffer that will hold 1 second of data. Note that the interface to the capture device object passed in as a parameter must be obtained by using the DirectSoundCaptureCreate8 function rather than the earlier DirectSoundCaptureCreate function; otherwise the buffer will not support the IDirectSoundCaptureBuffer8 interface.

HRESULT CreateCaptureBuffer(LPDIRECTSOUNDCAPTURE8 pDSC,
                            LPDIRECTSOUNDCAPTUREBUFFER8* ppDSCB8)
{
  HRESULT hr;
  DSCBUFFERDESC               dscbd;
  LPDIRECTSOUNDCAPTUREBUFFER  pDSCB;
  WAVEFORMATEX                wfx =
    {WAVE_FORMAT_PCM, 2, 44100, 176400, 4, 16, 0};
    // wFormatTag, nChannels, nSamplesPerSec, mAvgBytesPerSec,
    // nBlockAlign, wBitsPerSample, cbSize

  if ((NULL == pDSC) || (NULL == ppDSCB8)) return E_INVALIDARG;
  dscbd.dwSize = sizeof(DSCBUFFERDESC);
  dscbd.dwFlags = 0;
  dscbd.dwBufferBytes = wfx.nAvgBytesPerSec;
  dscbd.dwReserved = 0;
  dscbd.lpwfxFormat = &wfx;
  dscbd.dwFXCount = 0;
  dscbd.lpDSCFXDesc = NULL;

  if (SUCCEEDED(hr = pDSC->CreateCaptureBuffer(&dscbd, &pDSCB, NULL)))
  {
    hr = pDSCB->QueryInterface(IID_IDirectSoundCaptureBuffer8, (LPVOID*)ppDSCB8);
    pDSCB->Release();
  }
  return hr;
}


Capture Buffer Information

You can use the IDirectSoundCaptureBuffer8::GetCaps method to retrieve the size of a capture buffer. Be sure to initialize the dwSize member of the DSCBCAPS structure before passing it as a parameter.

To retrieve information about the format of the data in the buffer, as set when the buffer was created, call IDirectSoundCaptureBuffer8::GetFormat. This method returns the format information in a WAVEFORMATEX structure.

Note that your application can allow for extra format information in the WAVEFORMATEX structure by first calling the GetFormat method with NULL as the lpwfxFormat parameter. In this case the DWORD pointed to by the lpdwSizeWritten parameter receives the size of the structure needed to receive complete format information.

To find out what a capture buffer is currently doing, call the IDirectSoundCaptureBuffer8::GetStatus method. This method fills a DWORD variable with a combination of flags that indicate whether the buffer is busy capturing, and if so, whether it is looping; that is, whether the DSCBSTART_LOOPING flag was set in the last call to IDirectSoundCaptureBuffer8::Start.

The IDirectSoundCaptureBuffer8::GetCurrentPosition method returns the offsets of the read and capture cursors within the buffer. The read cursor is at the end of the data that has been fully captured into the buffer at this point. The capture cursor is at the end of the block of data that is currently being copied from the hardware. You can safely copy data from the buffer only up to the read cursor.


Capture Buffer Notification

To copy data out of the capture buffer at regular intervals, your application has to know when the read cursor, which is the point up to which it is safe to read data, reaches certain points in the buffer. One way to get this information is to poll the position of the read cursor using IDirectSoundCaptureBuffer8::GetCurrentPosition. A more efficient way is to use notifications. Using the IDirectSoundNotify8::SetNotificationPositions method, you can set any number of points within the buffer where events are to be signaled. You cannot do this while the buffer is running.

First you must obtain the IDirectSoundNotify8 interface. You can do this by using the buffer object's QueryInterface method.

For each notification position, create an event object with the Win32 CreateEvent function. Put the handle to this event in the hEventNotify member of a DSBPOSITIONNOTIFY structure. In the dwOffset member of that structure, specify the offset within the buffer where you want the event to be signaled. Then pass the address of the structure—or of an array of structures, if you want to set more than one notification position—to SetNotificationPositions.

The following example sets up three notification positions in a one-second buffer. One event will be signaled when the read position nears the halfway point in the buffer, another will be signaled when it nears the end of the buffer, and the third will be signaled when capture stops.

HRESULT SetCaptureNotifications(LPDIRECTSOUNDCAPTUREBUFFER8 pDSCB)
{
  #define cEvents  3

  LPDIRECTSOUNDNOTIFY8 pDSNotify;
  WAVEFORMATEX         wfx;
  HANDLE     rghEvent[cEvents] = {0};
  DSBPOSITIONNOTIFY  rgdsbpn[cEvents];
  HRESULT    hr;

  if (NULL == pDSCB) return E_INVALIDARG;
  if (FAILED(hr = pDSCB->QueryInterface(IID_IDirectSoundNotify, (LPVOID*)&pDSNotify)))
  {
    return hr;
  }
  if (FAILED(hr = pDSCB->GetFormat(&wfx, sizeof(WAVEFORMATEX), NULL)))
  {
    return hr;
  }

  // Create events.
  for (int i = 0; i < cEvents; ++i)
  {
    rghEvent[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (NULL == rghEvent[i])
    {
      hr = GetLastError();
      return hr;
    }
  }

  // Describe notifications.

  rgdsbpn[0].dwOffset = (wfx.nAvgBytesPerSec/2) -1;
  rgdsbpn[0].hEventNotify = rghEvent[0];

  rgdsbpn[1].dwOffset = wfx.nAvgBytesPerSec - 1;
  rgdsbpn[1].hEventNotify = rghEvent[1];

  rgdsbpn[2].dwOffset = DSBPN_OFFSETSTOP;
  rgdsbpn[2].hEventNotify = rghEvent[2];

  // Create notifications.

  hr = pDSNotify->SetNotificationPositions(cEvents, rgdsbpn);
  pDSNotify->Release();
  return hr;
}


Capture Buffer Effects

Two capture buffer effects are available as kernel-mode implementations on Microsoft® Windows® XP:

  • Acoustic echo cancellation (AEC)
  • Noise suppression

Other effects in DMOs, such as those used on rendering buffers, are not supported.

Both the DirectSoundFullDuplexCreate8 function and the IDirectSoundCapture8::CreateCaptureBuffer method take as a parameter a DSCBUFFERDESC structure that points to an array of DSCEFFECTDESC structures describing desired effects. However, to use the Microsoft implementations you must create the capture buffer by using DirectSoundFullDuplexCreate8. You must also play the secondary sound buffer created by that function; until you do so, the effects are not applied.

In the dwFlags member for each DSCEFFECTDESC structure, you must specify either DSCFX_LOCHARDWARE or DSCFX_LOCSOFTWARE. In most cases, specify DSCFX_LOCSOFTWARE. Buffer creation fails if the effect is not available in the specified location.

The effect is identified in the guidDSCFXClass member of the DSCEFFECTDESC structure. To obtain the Microsoft software implementation, specify DSCFX_MS_AEC or DSCFX_MS_NS in the guidDSCFXInstance member. To use another implementation available in hardware or software, obtain the class and instance GUID from the manufacturer.

After the buffer has been created, you can retrieve information about the effects by using the IDirectSoundCaptureBuffer8::GetFXStatus method.

Acoustic echo cancellation (AEC) is primarily of interest for applications that use voice communication from one site to another. The signal from a microphone at site A is output from the speakers at site B and picked up by the microphone at site B. Without AEC, the signal is then sent back to site A, resulting in an echo and possibly a feedback squeal. AEC overcomes this problem by monitoring the incoming signal at each site, adjusting it to take the room environment into account, and then removing it from the outgoing signal. It also removes any local sounds being played by the computer, such as music, so that these do not interfere with the voice signal being sent over the network.

AEC is implemented at the kernel level of the operating system and is global in its effect. It has the following limitations:

  • Only one capture buffer at a time can use AEC.
  • AEC cannot be started if another application is capturing or playing audio. If AEC has been started, no other application can capture audio without using AEC.
  • Regardless of the input or output format, the kernel mixer processes the sound in 16-bit mono format. As a result, the quality of the sound may be reduced. To minimize processor usage, capture sounds in a 16-bit mono format.
  • While AEC is in use, all DirectSound hardware acceleration on the device is disabled, affecting the user experience for other applications sharing the device.
  • Changes to AEC parameters affect all applications that are running.
  • AEC does not work with some combinations of sound cards and drivers. Applications should always provide the user with the option of turning off AEC.
  • On versions of the operating system prior to Windows XP SP1, AEC does not work with USB speakers, or on any machine in which audio capture and rendering are provided by different devices with different clocks.
  • If the acoustic environment changes, the adaptive filter can take two seconds or more to adjust.
  • Any late reverberations occurring more than 128 milliseconds after the original signal are not removed from the outgoing signal.

Use the IDirectSoundCaptureFXAec8·interface to set and retrieve AEC parameters on a capture buffer that contains this effect. You can also enable noise fill, which is a means of preventing complete silence when there is no new data in the outgoing signal.

Noise suppression can be applied only if AEC is also enabled. The noise suppression capture effect removes constant background noise, such as fan noise. Use the IDirectSoundCaptureFXNoiseSuppress8 interface to set and retrieve parameters.

The effect interfaces are obtained from the capture buffer object by using IDirectSoundCaptureBuffer8::GetObjectInPath.


Using the Capture Buffer

Capturing a sound consists of the following steps:

  1. Start the buffer by calling the IDirectSoundCaptureBuffer8::Start method. Normally you should pass DSCBSTART_LOOPING in the dwFlags parameter so that the buffer will keep running continuously rather than stopping when it reaches the end. Audio data from the input device begins filling the buffer from the beginning.
  2. Wait until the desired amount of data is available. For one method of determining when the capture cursor reaches a certain point, see Capture Buffer Notification.
  3. When sufficient data is available, lock a portion of the capture buffer by calling the IDirectSoundCaptureBuffer8::Lock method.

    To make sure you are not attempting to lock a portion of memory that is about to be used for capture, you can first obtain the position of the read cursor by calling IDirectSoundCaptureBuffer8::GetCurrentPosition.

    As parameters to the Lock method, you pass the size and offset of the block of memory you want to read. The method returns a pointer to the address where the memory block begins, and the size of the block. If the block wraps around from the end of the buffer to the beginning, two pointers are returned, one for each section of the block. The second pointer is NULL if the locked portion of the buffer does not wrap around.

  4. Copy the data from the buffer, using the addresses and block sizes returned by the Lock method.
  5. Unlock the buffer with the IDirectSoundCaptureBuffer8::Unlock method.
  6. Repeat steps 2 to 5 until you are ready to stop capturing data. Then call the IDirectSoundCaptureBuffer8::Stop method.


Writing to a WAV File

WAV files are in the Resource Interchange File Format (RIFF), which consists of a variable number of named chunks containing either header information (for example, the format of sound samples) or data (the samples themselves). The Win32 API supplies functions for opening and closing RIFF files, seeking to chunks, and so on. The names of these functions all start with "mmio".

The DirectSound API does not include methods for writing to WAV files. However, the Dsutil.cpp file used by many of the SDK sample applications implements a CWaveFile class that has the following methods for managing capture files:

  • Open. Opens a file and writes the header chunks.
  • Write. Writes from a buffer to the data chunk and advances the write cursor.
  • Close. Writes the size of the data chunk in the header and closes the file.

The first step in writing a WAV file is to call the CWaveFile::Open method. This creates the file and writes the WAV format chunk. The parameters are the filename, a pointer to an initialized WAVEFORMATEX structure, and the WAVEFILE_WRITE flag. The method returns an HRESULT.

The following code opens a WAV file for writing:

CWaveFile   g_pWaveFile;
WAVEFORMATEX  wfxInput;

ZeroMemory( &wfxInput, sizeof(wfxInput));
wfxInput.wFormatTag = WAVE_FORMAT_PCM;
wfxInput.nSamplesPerSec = 22050
wfxInput.wBitsPerSample =  8;
wfxInput.nChannels = 1;
wfxInput.nBlockAlign =
    wfxInput.nChannels * (wfxInput.wBitsPerSample / 8);
wfxInput.nAvgBytesPerSec =
    wfxInput.nBlockAlign * wfxInput.nSamplesPerSec;

g_pWaveFile = new CWaveFile;
if (FAILED(g_pWaveFile->Open("mywave.wav", &wfxInput,
    WAVEFILE_WRITE)))
{
  g_pWaveFile->Close();
}

The application can now begin copying data from the capture buffer to the file.

The following example function is called each time the read cursor reaches a notification position. In this function, the following global variables are used:

  • g_pDSBCapture is a pointer to the IDirectSoundCaptureBuffer8 interface of the capture buffer.
  • g_dwNextCaptureOffset tracks the buffer offset of the next block of data that will be copied to the file.
  • g_dwCaptureBufferSize is the size of the capture buffer, used in calculating wraparound.
HRESULT RecordCapturedData()
{
  HRESULT hr;
  VOID* pbCaptureData  = NULL;
  DWORD dwCaptureLength;
  VOID* pbCaptureData2 = NULL;
  DWORD dwCaptureLength2;
  VOID* pbPlayData   = NULL;
  UINT  dwDataWrote;
  DWORD dwReadPos;
  LONG lLockSize;

  if (NULL == g_pDSBCapture)
      return S_FALSE;
  if (NULL == g_pWaveFile)
      return S_FALSE;

  if (FAILED (hr = g_pDSBCapture->GetCurrentPosition(
    NULL, &dwReadPos)))
      return hr;

  // Lock everything between the private cursor
  // and the read cursor, allowing for wraparound.

  lLockSize = dwReadPos - g_dwNextCaptureOffset;
  if( lLockSize < 0 ) lLockSize += g_dwCaptureBufferSize;

  if( lLockSize == 0 ) return S_FALSE;

  if (FAILED(hr = g_pDSBCapture->Lock(
        g_dwNextCaptureOffset, lLockSize,
        &pbCaptureData, &dwCaptureLength,
        &pbCaptureData2, &dwCaptureLength2, 0L)))
    return hr;

  // Write the data. This is done in two steps
  // to account for wraparound.

  if (FAILED( hr = g_pWaveFile->Write( dwCaptureLength,
      (BYTE*)pbCaptureData, &dwDataWrote)))
    return hr;

  if (pbCaptureData2 != NULL)
  {
    if (FAILED(hr = g_pWaveFile->Write(
        dwCaptureLength2, (BYTE*)pbCaptureData2,
        &dwDataWrote)))
      return hr;
  }

  // Unlock the capture buffer.

 g_pDSBCapture->Unlock( pbCaptureData, dwCaptureLength,
    pbCaptureData2, dwCaptureLength2  );

  // Move the capture offset forward.

  g_dwNextCaptureOffset += dwCaptureLength;
  g_dwNextCaptureOffset %= g_dwCaptureBufferSize;
  g_dwNextCaptureOffset += dwCaptureLength2;
  g_dwNextCaptureOffset %= g_dwCaptureBufferSize;

  return S_OK;
}

When capturing is finished, the application closes the WAV file.

g_pWaveFile->Close();

See Also

  • CaptureSound Sample


Advanced Topics in DirectSound

This section contains information about optimizations and advanced features not needed by all Microsoft® DirectSound® applications.

Information is presented in the following topics:

  • DirectSound Driver Models
  • Property Sets for DirectSound Buffers
  • Optimizing DirectSound Performance
  • Writing to the Primary Buffer


DirectSound Driver Models

Under the VXD driver model, all DirectSound mixing is done in Dsound.vxd, a virtual device driver. Dsound.vxd also provides close access to the actual DMA buffer that the sound card uses to receive data from the host CPU. This is the same as the DirectSound primary buffer. A DirectSound application can set specific properties of the primary buffer, such as sampling rate and bit depth, thus changing the properties of the hardware itself.

Under the Windows Driver Model (WDM), DirectSound does not have direct access to the sound hardware, except in the case of hardware-accelerated buffers. Instead, DirectSound sends data to the kernel mixer. The kernel mixer's job is to convert the format of multiple audio streams to a common format, mix them together and send the result to the hardware. In a sense, it does what Dsound.vxd does. One major difference is that Dsound.vxd mixes only DirectSound buffer data, but the kernel mixer mixes all Windows audio data, including data from applications that use the Win32 waveOut functions. The rule that DirectSound and the waveform-audio output device cannot both be open at the same time is not true on systems with WDM drivers.

Of particular importance is the kernel mixer's relationship with the audio hardware. the kernel mixer is the only software on the system that can specify the format of the hardware's DMA buffer. It selects the format on the basis of sounds it is asked to mix. It sets the output format to the highest-quality format of sounds that it is asked to mix, or to the closest format to this that the hardware supports.

This has one very important implication: DirectSound cannot set the format of the hardware's DMA buffer. For your application, this means that the hardware format is based on the data you actually play. If you play a 44 kHz file, Kmixer will mix all data up to 44 kHz and ensure that the hardware is running at 44 kHz.

As an application developer, you don't choose the driver model used. That is completely determined by the type of sound card, the version of Windows, and the installed driver. For this reason, it is very important that you cover all possibilities when you test your application. DirectSound might be using Dsound.vxd or it might be using the kernel mixer, and you should ensure that your application's behavior and performance are acceptable on both.


System Property Sets

Information about system-wide DirectSound device properties can be obtained from an object of class CLSID_DirectSoundPrivate (11AB3EC0-25EC-11d1-A4D8-00C04FC28ACA). This class supports the IKsPropertySet interface. The CLSID and properties are defined in Dsconf.h.

  1. To create an object of this classCall the LoadLibrary function to load Dsound.dll.
  2. Call the GetProcAddress function to obtain the DllGetClassObject function.
  3. Call DllGetClassObject to obtain the IClassFactory interface of the class factory for the CLSID_DirectSoundPrivate class.
  4. Call IClassFactory::CreateInstance to create the CLSID_DirectSoundPrivate object and retrieve the IKsPropertySet interface (IID_IKsPropertySet).

The CLSID_DirectSoundPrivate object supports one property set, DSPROPSETID_DirectSoundDevice (84624F82-25EC-11d1-A4D8-00C04FC28ACA). This property set exposes the following three read-only properties.

  • DSPROPERTY_DIRECTSOUNDDEVICE_WAVEDEVICEMAPPING
  • DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION
  • DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE

DSPROPERTY_DIRECTSOUNDDEVICE_WAVEDEVICEMAPPING

This property retrieves the DirectSound device GUID corresponding to a specified Windows Multimedia device name.

Property data is contained in a DSPROPERTY_DIRECTSOUNDDEVICE_WAVEDEVICEMAPPING_DATA structure, available in ANSI and Unicode versions. This structure has the following members.

Member | Type | Description
DeviceName | String | [in] Name of device
DataFlow | DIRECTSOUNDDEVICE_DATAFLOW | [in] Direction of data flow, either DIRECTSOUNDDEVICE_DATAFLOW_RENDER or DIRECTSOUNDDEVICE_DATAFLOW_CAPTURE
DeviceID | GUID | [out] DirectSound device ID

DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION

This property retrieves a full description of a DirectSound device specified by GUID.

Property data is contained in a DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_DATA structure, available in ANSI and Unicode versions. This structure has the following members.

Member | Type | Description
Type | DIRECTSOUNDDEVICE_TYPE | [out] Device type: DIRECTSOUNDDEVICE_TYPE_EMULATED, DIRECTSOUNDDEVICE_TYPE_VXD or DIRECTSOUNDDEVICE_TYPE_WDM
DataFlow | DIRECTSOUNDDEVICE_DATAFLOW | [in, out] Direction of data flow, either DIRECTSOUNDDEVICE_DATAFLOW_RENDER or DIRECTSOUNDDEVICE_DATAFLOW_CAPTURE
DeviceID | GUID | [in] DirectSound device GUID, or NULL for the default device of the type specified by DataFlow
Description | String | [out] Description of DirectSound device
Module | String | [out] Module name of the DirectSound driver
Interface | String | [out] PnP device interface name
WaveDeviceID | ULONG | [out] Identifier of the corresponding Windows Multimedia device

DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE

This property enumerates all DirectSound render or capture devices.

Property data is contained in a DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_DATA structure, available in Ansi and Unicode versions. This structure has the following members.

Member | Type | Description
Callback | LPFNDIRECTSOUNDDEVICEENUMERATECALLBACK | [in] Application-defined callback function. When IKsPropertySet::Get is called, this function is called once for each device enumerated. It takes as parameters a DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_DATA structure describing the enumerated device, and the value in Context.
Context | LPVOID | [in] User-defined value to be passed to the callback function for each device enumerated.


Property Sets for DirectSound Buffers

To make use of extended properties on sound cards, you must first determine whether the driver supports the IKsPropertySet interface, and obtain a pointer to the interface if it is supported. You can do this by calling the QueryInterface method of an existing interface on a DirectSound 3-D buffer object, as follows:

HRESULT hr = lpDirectSound3DBuffer->QueryInterface(
    IID_IKsPropertySet,
    (void**)&lpKsPropertySet));

In the example, lpDirectSound3DBuffer is a pointer to the buffer's interface and lpKsPropertySet receives the address of the IKsPropertySet interface if one is found. IID_IKsPropertySet is a GUID defined in Dsound.h. The interface is available only if the buffer is hardware-accelerated and the underlying driver supports property sets.

Note The declaration of this interface in Dsound.h is different from that in Ksproxy.h and Strmif.h. If your project includes Ksproxy.h or Strmif.h but you wish to use the DirectSound implementation, be sure to include Dsound.h first. Failing to do so may cause your application to stop responding when a method of IKsPropertySet is called.

You can look for a particular property by using the IKsPropertySet::QuerySupport method. The value of the PropertySetId parameter is a GUID defined by the hardware vendor.

After you've determined that support for a particular property exists, you can change the state of the property by using the IKsPropertySet::Set method and determine its present state by using the IKsPropertySet::Get method. The state of the property is set or returned in the pPropertyData parameter.

Additional property parameters may also be passed to the object in the pPropertyParams parameter to the IKsPropertySet::Set method. The exact way in which this parameter is to be used is defined in the hardware vendor's specifications for the property set, but typically it would be used to define the instance of the property set. In practice, the pPropertyParams parameter is rarely used.


Optimizing DirectSound Performance

This section offers miscellaneous tips for improving the performance of applications that play their audio data directly into DirectSound buffers. The following topics are covered:

  • Using Hardware Mixing
  • Dynamic Voice Management
  • Using Buffers Efficiently


Using Hardware Mixing

Modern sound cards are designed to connect to the peripheral component interconnect (PCI) local bus. This bus provides the card with rapid access to system memory. As a result, it is practical for the audio processor to mix data directly from buffers in system memory, and it is unnecessary to have memory buffers on the card itself.

On PCI cards, static buffers and streaming buffers are effectively the same, and the same buffers may be reported in DSCAPS as both static and streaming buffers. The DSBCAPS_STATIC flag in DSBUFFERDESC does not affect the location of a DirectSound buffer.

The following tips will help you make the most of hardware mixing.

  • At run time, use the IDirectSound8::GetCaps method to determine what formats are supported by the sound-accelerator hardware, and use only those formats if possible.
  • Create sound buffers first for the sounds you use the most. There is a limit to the number of buffers that can be mixed by hardware.
  • To force a buffer to be created in hardware, specify the DSBCAPS_LOCHARDWARE flag in the dwFlags member of the DSBUFFERDESC structure. If you do this and resources for hardware mixing are not available, the IDirectSound8::CreateSoundBuffer method will fail.
  • Use voice management to enable DirectSound to assign buffers to hardware resources when they are available, and to force termination of less important buffers in order to free hardware resources. See Dynamic Voice Management.


Dynamic Voice Management

Many sound cards maintain their own secondary buffers and handle 3-D effects and mixing for them. These hardware buffers, as they are called, usually reside in system memory rather than on the card itself, but because they are mixed by the device, they make far smaller demands on the system processor than do software buffers. It is therefore most efficient to have as many buffers as possible allocated to hardware, especially 3-D buffers.

By default, DirectSound allocates buffers to hardware whenever it can. However, it can create only as many hardware buffers as the device can play at one time. In other words, the number of hardware buffers is limited by the availability of hardware voices. DirectSound allocates a hardware voice when a buffer is created and releases it only when the buffer is destroyed. If an application creates many buffers, some of them will likely end up in software, which means that they will be managed and mixed by the CPU rather than the sound card.

Note The DirectSound voice manager allocates hardware mixing resources, not memory. On a PCI card, the buffer occupies the same memory before and after it is allocated, regardless of whether it is allocated to the hardware mixer or the software mixer.

Dynamic voice management helps you overcome the limited availability of hardware resources by deferring voice allocation until buffers are played, and by enabling DirectSound to stop lower-priority sounds prematurely and release their resources so that these resources can be allocated to new sounds.

To defer the allocation of resources for hardware mixing and 3-D effects to the moment when the buffer is played, specify the DSBCAPS_LOCDEFER flag in the DSBUFFERDESC structure passed to IDirectSound8::CreateSoundBuffer. When you call IDirectSoundBuffer8::Play or IDirectSoundBuffer8::AcquireResources on such a buffer, DirectSound places the buffer in hardware if possible, and in software otherwise.

When calling Play, you can attempt to free a hardware voice for the buffer by passing one of the flags in the following table, or one of the first two flags in combination with the third. DirectSound then searches for a playing buffer that is suitable for termination as specified by the flags.

Flag | Criterion
DSBPLAY_TERMINATEBY_TIME | Select the buffer that has been playing longer than any other candidate buffers.
DSBPLAY_TERMINATEBY_DISTANCE | Select the 3-D candidate buffer farthest from the listener.
DSBPLAY_TERMINATEBY_PRIORITY | Select the buffer that has the lowest priority of candidate buffers, as set in the call to Play. If this is combined with one of the other two flags, the other flag is used only to resolve ties.

If it finds a suitable buffer, DirectSound stops it and allocates the voice it was using to the newly played buffer. If no buffer is suitable for termination, the newly played buffer is played in software, unless the DSBPLAY_LOCHARDWARE flag was specified, in which case the call to Play fails.

For more information on how deferred buffers are dealt with when played, see IDirectSoundBuffer8::Play.

Note Do not use the DSBCAPS_STATIC flag in combination with DSBCAPS_LOCDEFER when creating buffers. DSBCAPS_STATIC buffers are placed in on-card memory when this is available, as is the case on some older cards. If you create such a buffer with the DSBCAPS_LOCDEFER flag, the buffer memory is not copied to the sound card until the buffer is played for the first time, which can result in unacceptable delays.


Using Buffers Efficiently

When using streaming buffers, limit the frequency of notifications and data writes. Do not create buffers with many notification positions, or small buffers with notifications at very short intervals. A streaming buffer can work efficiently and reliably with as few as three notification positions.

Performance is affected when you make control changes on a secondary buffer. To improve performance, reduce the frequency of calls to IDirectSoundBuffer8::SetVolume, IDirectSoundBuffer8::SetPan, and IDirectSoundBuffer8::SetFrequency. For example, if you have a routine that moves a sound from the left to the right speaker in synchronization with animation frames, try calling the SetPan method only every second or third frame.

Keep in mind that 3-D buffers in software make high demands on the central processing unit. To limit these demands you can do the following:

  • Put frequently-used sounds in hardware buffers if possible.
  • Don't create 3-D buffers for sounds that won't benefit from the effect.
  • Use IDirectSound3DBuffer8::SetMode with the DS3DMODE_DISABLE flag to disable 3-D processing on any 3-D sound buffer that is no longer moving in relation to the listener.
  • Make parameter changes in batches, or use deferred settings to make changes to all buffers and the listener at once.

See Also

  • Batch Parameters for 3-D Buffers
  • Batch Parameters for 3-D Listeners
  • Deferred Settings
  • Minimum and Maximum Distances


Writing to the Primary Buffer

For applications that require specialized mixing or other effects not supported by secondary buffers, DirectSound allows direct access to the primary buffer.

When you obtain write access to the primary buffer, other DirectSound features become unavailable. Secondary buffers are not mixed, so hardware-accelerated mixing is unavailable.

Most applications should use secondary buffers instead of directly accessing the primary buffer. Applications can write to a secondary buffer easily because the larger buffer size provides more time to write the next block of data, thereby minimizing the risk of gaps in the audio. Even if an application has simple audio requirements, such as using one stream of audio data that does not require mixing, it will achieve better performance by using a secondary buffer to play its audio data.

Note Writing directly to the primary buffer offers no advantages under the Windows driver model (WDM). Under WDM, the primary buffer is in effect a secondary buffer that is mixed by the kernel mixer. For more information on WDM, see DirectSound Driver Models.

You cannot specify the size of the primary buffer, and you must accept the returned size after the buffer is created. A primary buffer is typically very small, so if your application writes directly to this kind of buffer, it must write blocks of data at short intervals to prevent the previously written data from being replayed.

You cannot obtain write access to a primary buffer unless it exists in hardware. To determine whether this is the case, call the IDirectSoundBuffer8::GetCaps method and check for the DSBCAPS_LOCHARDWARE flag in the dwFlags member of the DSBCAPS structure that is returned. If you attempt to lock a primary buffer that is emulated in software, the call will fail.

You create an accessible primary buffer by specifying the DSBCAPS_PRIMARYBUFFER flag in the DSBUFFERDESC structure passed to the IDirectSound8::CreateSoundBuffer method. If you want to write to the buffer, the cooperative level must be DSSCL_WRITEPRIMARY.

Primary sound buffers must be played with looping. Ensure that the DSBPLAY_LOOPING flag is set.

The following example shows how to obtain write access to the primary buffer. Note that the primary buffer supports only the IDirectSoundBuffer interface, not IDirectSoundBuffer8.

BOOL AppCreateWritePrimaryBuffer(
  LPDIRECTSOUND8 lpDirectSound,
  LPDIRECTSOUNDBUFFER *lplpDsb,
  LPDWORD lpdwBufferSize,
  HWND hwnd)
{
  DSBUFFERDESC dsbdesc;
  DSBCAPS dsbcaps;
  HRESULT hr;
  WAVEFORMATEX wf;

  // Set up wave format structure.
  memset(&wf, 0, sizeof(WAVEFORMATEX));
  wf.wFormatTag = WAVE_FORMAT_PCM;
  wf.nChannels = 2;
  wf.nSamplesPerSec = 22050;
  wf.nBlockAlign = 4;
  wf.nAvgBytesPerSec =
      wf.nSamplesPerSec * wf.nBlockAlign;
  wf.wBitsPerSample = 16;

  // Set up DSBUFFERDESC structure.
  memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
  dsbdesc.dwSize = sizeof(DSBUFFERDESC);
  dsbdesc.dwFlags = DSBCAPS_PRIMARYBUFFER;
  // Buffer size is determined by sound hardware.
  dsbdesc.dwBufferBytes = 0;
  dsbdesc.lpwfxFormat = NULL; // Must be NULL for primary buffers.

  // Obtain write-primary cooperative level.
  hr = lpDirectSound->SetCooperativeLevel(hwnd, DSSCL_WRITEPRIMARY);
  if SUCCEEDED(hr)
  {
    // Try to create buffer.
    hr = lpDirectSound->CreateSoundBuffer(&dsbdesc,
      lplpDsb, NULL);
    if SUCCEEDED(hr)
    {
      // Set primary buffer to desired format.
      hr = (*lplpDsb)->SetFormat(&wf);
      if SUCCEEDED(hr)
      {
        // If you want to know the buffer size, call GetCaps.
        dsbcaps.dwSize = sizeof(DSBCAPS);
        (*lplpDsb)->GetCaps(&dsbcaps);
        *lpdwBufferSize = dsbcaps.dwBufferBytes;
        return TRUE;
      }
    }
  }
  // Failure.
  *lplpDsb = NULL;
  *lpdwBufferSize = 0;
  return FALSE;
}

The following example illustrates how an application might implement a custom mixer. The AppMixIntoPrimaryBuffer sample function would have to be called at regular intervals, frequently enough to prevent the sound device from repeating blocks of data. The CustomMixer function is an application-defined function that mixes several streams together, as specified in an application-defined APPSTREAMINFO structure, and writes the result to the specified pointer.

BOOL AppMixIntoPrimaryBuffer(
    APPSTREAMINFO* lpAppStreamInfo,
    LPDIRECTSOUNDBUFFER lpDsbPrimary,
    DWORD dwDataBytes,
    DWORD dwOldPos,
    LPDWORD lpdwNewPos)
{
  LPVOID lpvPtr1;
  DWORD dwBytes1;
  LPVOID lpvPtr2;
  DWORD dwBytes2;
  HRESULT hr;
  // Obtain write pointer.
  hr = lpDsbPrimary->Lock(dwOldPos, dwDataBytes,
          &lpvPtr1, &dwBytes1,
          &lpvPtr2, &dwBytes2, 0);

  // If DSERR_BUFFERLOST is returned, restore and retry lock.

  if (DSERR_BUFFERLOST == hr)
  {
    lpDsbPrimary->Restore();
    hr = lpDsbPrimary->Lock(dwOldPos, dwDataBytes,
            &lpvPtr1, &dwBytes1,
            &lpvPtr2, &dwBytes2, 0);
  }
  if SUCCEEDED(hr)
  {
    // Mix data into the returned pointers.
    CustomMixer(lpAppStreamInfo, lpvPtr1, dwBytes1);
    *lpdwNewPos = dwOldPos + dwBytes1;
    if (NULL != lpvPtr2)
    {
      CustomMixer(lpAppStreamInfo, lpvPtr2, dwBytes2);
      *lpdwNewPos = dwBytes2; // Because it wrapped around.
    }
    // Release the data back to DirectSound.
    hr = lpDsbPrimary->Unlock(lpvPtr1, dwBytes1,
            lpvPtr2, dwBytes2);
    if SUCCEEDED(hr)
    {
      return TRUE;
    }
  }
  // Lock or Unlock failed.
  return FALSE;
}


DirectSound C++ Samples

The sample applications described in this section demonstrate the use and capabilities of the Microsoft® DirectMusic® application programming interface (API) in Microsoft® DirectX® for C++.

The following samples are found on the Start menu under Programs/Microsoft DirectX 9.0 SDK/C++ Samples/DirectSound Samples.

  • AdjustSound Sample
  • AmplitudeModulation Sample
  • CaptureSound Sample
  • Enumerate DirectSound Devices Sample
  • Full Duplex Filter Sample
  • Play 3D Sound Sample
  • Play Sound Sample
  • SoundFX Sample
  • Stream Data Sample
  • Voice Management Sample

The source code is in the following folder, where SDK root is the installation folder for the DirectX SDK, such as C:\DXSDK:

(SDK root)\samples\C++\DirectSound

The samples use common source files that implement functions and classes for basic DirectSound functionality and for general tasks such as finding media files. For more information, see DirectSound Sample Framework.


DirectSound Sample Framework

The core functionality for the DirectSound samples is in a common set of classes, declared in Dsutil.h and implemented in Dsutil.cpp.

These files are found in the following folders:

(SDK root)\samples\C++\Common\Include
(SDK root)\samples\C++\Common\Src

To use the sample framework, your project must link to Dxerr9.lib and Winmm.lib.

The framework classes provide basic functionality for the samples, and you can use them as a starting-point for your own applications. However, they are not intended to be a full-featured wrapper for the DirectSound API.

The following classes are used in the samples:

Class | Description
CSound Sample Class | Represents a static buffer.
CSoundManager Sample Class | Contains functionality for creating and initializing DirectSound, accessing the primary buffer, and creating secondary buffers.
CStreamingSound Sample Class | Represents a sound in one or more streaming buffers.
CWaveFile Sample Class | Used for reading from and writing to WAV files and reading from WAV resources or waveforms stored in memory.

See Also

  • DirectSound C++ Samples


CSound Sample Class

The CSound sample class represents a sound in one or more static buffers. An object of this class can be used to play multiple instances of a sound effect. The object is usually created through a call to the Create method of the CSoundManager Sample Class.

class CSound
{
protected:
    LPDIRECTSOUNDBUFFER* m_apDSBuffer;
    DWORD                m_dwDSBufferSize;
    CWaveFile*           m_pWaveFile;
    DWORD                m_dwNumBuffers;
    DWORD                m_dwCreationFlags;

    HRESULT RestoreBuffer(LPDIRECTSOUNDBUFFER pDSB, BOOL* pbWasRestored);

public:
    CSound(LPDIRECTSOUNDBUFFER* apDSBuffer, DWORD dwDSBufferSize,
        DWORD dwNumBuffers, CWaveFile* pWaveFile, DWORD dwCreationFlags);
    virtual ~CSound();

    HRESULT Get3DBufferInterface(DWORD dwIndex,
        LPDIRECTSOUND3DBUFFER* ppDS3DBuffer);
    HRESULT FillBufferWithSound(LPDIRECTSOUNDBUFFER pDSB,
        BOOL bRepeatWavIfBufferLarger);
    LPDIRECTSOUNDBUFFER GetFreeBuffer();
    LPDIRECTSOUNDBUFFER GetBuffer(DWORD dwIndex);
    HRESULT Play(DWORD dwPriority = 0, DWORD dwFlags = 0,
        LONG lVolume = 0, LONG lFrequency = 0);
    HRESULT Play3D(LPDS3DBUFFER p3DBuffer, DWORD dwPriority = 0,
        DWORD dwFlags = 0, LONG lFrequency = 0);
    HRESULT Stop();
    HRESULT Reset();
    BOOL    IsSoundPlaying();
};

Constructor

The constructor fills one or more buffers with the data from a specified WAV file and initializes private data members.

Public Methods

The class contains the following public methods, in alphabetical order.

Method | Description
FillBufferWithSound | Fills the specified buffer with the data from the WAV file that was passed to the object constructor. If the buffer is larger than the data, data can optionally be repeated; otherwise the rest of the buffer is filled with silence.
Get3DBufferInterface | Retrieves the IDirectSound3DBuffer8 interface pointer for the specified buffer, if the buffer has 3-D capabilities.
GetBuffer | Retrieves the IDirectSoundBuffer interface of the specified buffer. Use QueryInterface to retrieve IDirectSoundBuffer8.
GetFreeBuffer | Retrieves the IDirectSoundBuffer interface of the first buffer that is not playing. If all buffers are playing, the method returns a randomly selected buffer. Use QueryInterface to retrieve IDirectSoundBuffer8.
IsSoundPlaying | Returns a Boolean variable that indicates whether the specified buffer is playing.
Play | Plays a buffer. The method selects the buffer to play by calling GetFreeBuffer, and restores it if necessary The application can pass in a voice management flag; the DSBPLAY_LOOPING flag to repeat the sound; a volume in hundredths of decibels (where 0 is full volume and -10,000 is silence); and a frequency in hertz that is added to the basic frequency of the sound.
Play3D | Plays a 3-D buffer. This method is similar to Play, but the application also passes in a DS3DBUFFER structure describing the 3-D parameters to be set. (Note that if the CSound object has more than one buffer, there is no way to determine which one is played by this call. If you want to set 3-D parameters dynamically while the buffer is playing, add functionality to return a buffer pointer.)
Reset | Sets the play cursor on all buffers to the beginning.
Stop | Stops all buffers.

The class is implemented in (SDK root)\samples\C++\Common\Src\Dsutil.cpp.

See Also

  • DirectSound Sample Framework
  • DirectSound Buffers


CSoundManager Sample Class

The CSoundManager sample class contains functionality for creating and initializing DirectSound, accessing the primary buffer, and creating secondary buffers.

class CSoundManager
{
protected:
    LPDIRECTSOUND8 m_pDS;

public:
    CSoundManager();
    ~CSoundManager();

    HRESULT Initialize( HWND hWnd, DWORD dwCoopLevel );
    inline  LPDIRECTSOUND8 GetDirectSound() { return m_pDS; }
    HRESULT SetPrimaryBufferFormat( DWORD dwPrimaryChannels,
        DWORD dwPrimaryFreq, DWORD dwPrimaryBitRate );
    HRESULT Get3DListenerInterface(LPDIRECTSOUND3DLISTENER* ppDSListener );
    HRESULT Create( CSound** ppSound, LPTSTR strWaveFileName,
        DWORD dwCreationFlags = 0, GUID guid3DAlgorithm = GUID_NULL,
        DWORD dwNumBuffers = 1 );
    HRESULT CreateFromMemory( CSound** ppSound, BYTE* pbData,
        ULONG ulDataSize, LPWAVEFORMATEX pwfx, DWORD dwCreationFlags = 0,
        GUID guid3DAlgorithm = GUID_NULL, DWORD dwNumBuffers = 1 );
    HRESULT CreateStreaming( CStreamingSound** ppStreamingSound,
        LPTSTR strWaveFileName, DWORD dwCreationFlags,
        GUID guid3DAlgorithm, DWORD dwNotifyCount, DWORD dwNotifySize,
        HANDLE hNotifyEvent );
};

Constructor

The constructor initializes a data member.

Public Methods

The class contains the following public methods, in alphabetical order.

Method | Description
Create | Creates a CSound object associated with a WAV file and containing the specified number of buffers. For information on possible values in the dwCreationFlags and guid3DAlgorithm parameters, see DSBUFFERDESC.
CreateFromMemory | Creates a CSound object associated with a waveform in memory and containing the specified number of buffers. For information on possible values in the dwCreationFlags and guid3DAlgorithm parameters, see DSBUFFERDESC.
CreateStreaming | Creates a CStreamingSound object associated with a WAV file and containing a single streaming buffer. The application specifies notification positions and an event. In response to notifications, the application calls CStreamingSound::HandleWaveStreamNotification to refresh the data in the buffer. For information on possible values in the dwCreationFlags and guid3DAlgorithm parameters, see DSBUFFERDESC.
Get3DListenerInterface | Retrieves the IDirectSound3DListener8 interface.
GetDirectSound | Retrieves the IDirectSound8 interface of the DirectSound object created by Initialize.
Initialize | Creates the DirectSound object and sets the cooperative level.
SetPrimaryBufferFormat | Sets the format of the primary buffer. This method should not be used by most applications. For more information, see Mixing Sounds.

The class is implemented in (SDK root)\samples\C++\Common\Src\Dsutil.cpp.

See Also

  • DirectSound Sample Framework
  • CSound Sample Class
  • CStreamingSound Sample Class
  • DirectSound Buffers


CStreamingSound Sample Class

The CStreamingSound sample class represents a streaming buffer. The class inherits from CSound. An object of this class is usually created through a call to the CreateStreaming method of the CSoundManager Sample Class.

A CStreaming object has only one buffer. When calling methods inherited from CSound that take a buffer index, pass 0.

class CStreamingSound : public CSound
{
protected:
    DWORD m_dwLastPlayPos;
    DWORD m_dwPlayProgress;
    DWORD m_dwNotifySize;
    DWORD m_dwNextWriteOffset;
    BOOL  m_bFillNextNotificationWithSilence;

public:
    CStreamingSound(LPDIRECTSOUNDBUFFER pDSBuffer, DWORD dwDSBufferSize,
        CWaveFile* pWaveFile, DWORD dwNotifySize);
    ~CStreamingSound();

    HRESULT HandleWaveStreamNotification(BOOL bLoopedPlay);
    HRESULT Reset();
};

Constructor

The constructor calls the CSound constructor to fill the buffer with data from the beginning of the WAV file, and initializes private data members.

Public Methods

In addition to the methods inherited from CSound, the class contains the following public methods, in alphabetical order.

Method | Description
HandleWaveStreamNotification | Restores the buffer if necessary, then reads data from the file and writes it to the part of the buffer that has just been played. If the end of data is reached, the rest of the buffer is filled with silence, and the buffer is stopped after all data has been played. Call this method in response to notifications received in the message loop. Pass in TRUE as the parameter to repeat the sound when it reaches the end.
Reset | Restores the buffer if necessary, then resets the play position and the file so that the sound can begin playing again from the beginning.

The class is implemented in (SDK root)\samples\C++\Common\Src\Dsutil.cpp.

See Also

  • DirectSound Sample Framework
  • CSound Sample Class
  • DirectSound Buffers


CWaveFile Sample Class

The CWaveFile sample class is used for reading from and writing to WAV files and reading from WAV resources or waveforms stored in memory. An object of this class is created by CSoundManager when creating a CSound or CStreamingSound object. Applications do not usually need to call methods of CWaveFile directly.

class CWaveFile
{
public:
    WAVEFORMATEX* m_pwfx;
    HMMIO         m_hmmio;
    MMCKINFO      m_ck;
    MMCKINFO      m_ckRiff;
    DWORD         m_dwSize;
    MMIOINFO      m_mmioinfoOut;
    DWORD         m_dwFlags;
    BOOL          m_bIsReadingFromMemory;
    BYTE*         m_pbData;
    BYTE*         m_pbDataCur;
    ULONG         m_ulDataSize;
    CHAR*         m_pResourceBuffer;

protected:
    HRESULT ReadMMIO();
    HRESULT WriteMMIO(WAVEFORMATEX *pwfxDest);

public:
    CWaveFile();
    ~CWaveFile();

    HRESULT Open(LPTSTR strFileName, WAVEFORMATEX* pwfx, DWORD dwFlags);
    HRESULT OpenFromMemory(BYTE* pbData, ULONG ulDataSize,
        WAVEFORMATEX* pwfx, DWORD dwFlags);
    HRESULT Close();
    HRESULT Read(BYTE* pBuffer, DWORD dwSizeToRead, DWORD* pdwSizeRead);
    HRESULT Write(UINT nSizeToWrite, BYTE* pbData, UINT* pnSizeWrote);
    DWORD   GetSize();
    HRESULT ResetFile();
    WAVEFORMATEX* GetFormat() { return m_pwfx; };
};

Constructor

The constructor initializes data members.

Public Methods

The class contains the following public methods, in alphabetical order.

Method | Description
Close | Closes the file. If the file is being written to, first writes RIFF chunk sizes.
GetFormat | Returns a WAVEFORMATEX structure describing the format of the waveform.
GetSize | Retrieves the size of the data chunk, after Open has been called.
Open | Opens the file or loads the resource and retrieves the WAV format and data chunk size, or opens the file for writing and writes the header chunks. The strFileName parameter can be a file path or the name of a resource of type "WAVE" or "WAV". Pass WAVEFILE_READ in dwFlags to read from the file, or WAVEFILE_WRITE if capturing to the file. Use the pwfx parameter to specify the format of captured data; this parameter is ignored if the file is being read.
OpenFromMemory | Initializes data members so that subsequent calls to Read will get data from the supplied memory location rather than from a file or resource. It is assumed that the data does not contain any RIFF headers, and that pbData points to the start of the waveform samples.
Read | Reads data from the file, resource, or memory and copies it to the supplied address, which the application is responsible for obtaining by using IDirectSoundBuffer8::Lock. Read advances the pointer into the data by the number of bytes specified in dwSizeToRead.
ResetFile | Resets the pointer into the file or data to the beginning of the data chunk.
Write | Writes data to the file from the specified address, which the application is responsible for obtaining by using IDirectSoundCaptureBuffer8::Lock.

The class is implemented in (SDK root)\samples\C++\Common\Src\Dsutil.cpp.

See Also

  • DirectSound Sample Framework
  • Reading WAV Data
  • Writing to a WAV File


AdjustSound Sample

Description

The AdjustSound sample shows how to create a DirectSound secondary buffer to play a WAV file, and how to change the parameters of the buffer.

Path

Source: (SDK root)\Samples\C++\DirectSound\AdjustSound

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Load a WAV file by clicking Sound File. Select Focus and Buffer Mixing options; note that the various settings are explained under Expected Behavior as you select them. Click Play. If you don't hear any sound, check the Status pane. The application might fail to create the buffer in hardware if this option has been selected.

By using the sliders you can adjust the frequency, pan, and volume dynamically as the buffer is playing.

Programming Notes

To set the focus behavior of the buffer, the application calls IDirectSound8::CreateSoundBuffer with DSBCAPS_GLOBALFOCUS or DSBCAPS_STICKYFOCUS, or neither of these flags. To set the memory location of the buffer, it sets either DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE, or neither of these flags to allow DirectSound to create the buffer in a either hardware or software.

Parameters are set by using IDirectSoundBuffer8::SetFrequency, IDirectSoundBuffer8::SetPan, and IDirectSoundBuffer8::SetVolume.

For a simpler example of how to set up a DirectSound buffer without as many controls, see the Play Sound Sample.

See Also

  • DirectSound C++ Samples
  • DirectSound Buffers


AmplitudeModulation Sample

Description

The AmplitudeModulation sample shows how to apply an effect to a DirectSound secondary buffer and modify the parameters of the effect.

Path

Source: (SDK root)\Samples\C++\DirectSound\AmplitudeModulation

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Play the default sound or load another WAV file by clicking Sound File. Change the parameters of the effect by selecting one of the Wave Form options and moving the slider to change the modulation rate.

Programming Notes

The application takes the following steps to set an effect on a buffer and change its parameters:

  1. Creates the buffer with the DSBCAPS_CTRLFX flag.
  2. Describe the effect in a DSEFFECTDESC structure, setting the guidDSFXClass member to the GUID of the effect desired.
  3. Passes the buffer description to IDirectSoundBuffer8::SetFX.
  4. Calls IDirectSoundBuffer8::GetObjectInPath to get an interface pointer to the effect, in this case IDirectSoundFXGargle8.
  5. In the OnEffectChanged function, uses IDirectSoundFXGargle8::SetAllParameters to change the parameters of the gargle effect.

See Also

  • DirectSound C++ Samples
  • Using Effects


CaptureSound Sample

Description

The CaptureSound application shows how to capture waveforms to a file.

Path

Source: (SDK root)\Samples\C++\DirectSound\CaptureSound

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Select a device and a format. Create a file, or replace an existing one, by clicking Sound File. Click Record to start and stop recording.

Programming Notes

The sample relies on notifications to ascertain when data should be read from the buffer. The notification positions are set up in the InitNotifications function, and the events are received in the WinMain function.

See Also

  • DirectSound C++ Samples
  • Capturing Waveforms


Enumerate DirectSound Devices Sample

Description

The Enumerate DirectSound Devices sample shows how to enumerate and create playback and capture devices.

Path

Source: (SDK root)\Samples\C++\DirectSound\EnumDevices

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Select a playback and capture device from the dropdown lists. Click Create.

Programming Notes

The sample demonstrates the use of the DSEnumCallback function. The handle of the listbox is passed to this function as the pContext parameter so that the name of the device can be displayed and the GUID can be stored as list item data.

See Also

  • DirectSound C++ Samples
  • Enumerating Capture Devices
  • Enumerating Sound Devices


Full Duplex Filter Sample

Description

The Full Duplex Filter sample application shows how to capture and play back sounds at the same time.

Path

Source: (SDK root)\Samples\C++\DirectSound\FullDuplexFilter

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Be sure your sound card is configured for full-duplex operation and that you have a microphone attached. Choose a format from the Output Format list. A list of formats appears in the Input Format list. Select one. Click OK. If full duplex is successfully created, another dialog box is displayed with a Record button. Click this button. Speak into the microphone and your voice is heard over the speakers.

Programming Notes

The sample does not use the DirectSoundFullDuplexCreate8 function, which is not supported on earlier operating systems. Note that the DirectSound device is created before the DirectSoundCapture device.

See Also

  • DirectSound C++ Samples
  • Creating the Capture Device Object
  • Creating the Device Object


Play 3D Sound Sample

Description

The Play 3D Sound sample shows how to create a 3-D sound buffer and manipulate its properties.

Path

Source: (SDK root)\Samples\C++\DirectSound\Play3DSound

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Click Sound File and load a WAV file. Play the sound. The position of the sound source is shown as a red dot on the graph, where the x-axis is from left to right and the z-axis is from bottom to top. Change the range of movement on the two axes by using the sliders.

The listener is located at the center of the graph, and has its default orientation, looking along the positive z-axis; that is, toward the top of the screen. The sound source moves to the listener's left and right and to the listener's front and rear, but does not move above and below the listener.

The sliders in the center of the window control the properties of the listener; that is, the global sound properties. If you click Defer Settings, changes are not applied until you click Apply Settings.

Programming Notes

For a simpler example of how to set up a DirectSound buffer without 3-D positioning, see the Play Sound Sample.

The sample obtains an IDirectSound3DListener8 interface as follows:

  1. Describes a buffer in a DSBUFFERDESC structure containing the DSBCAPS_CTRL3D and DSBCAPS_PRIMARYBUFFER flags.
  2. Passes the buffer description to IDirectSound8::CreateSoundBuffer. This creates a primary buffer object with 3-D capabilities.
  3. Calls QueryInterface to obtain the IDirectSound3DListener8 interface. This interface controls global 3-D properties.

The sample obtains an IDirectSound3DBuffer8 interface as follows:

  1. Describes a buffer in a DSBUFFERDESC structure, setting the DSBCAPS_CTRL3D capabilties flag and and a 3-D virtualization algorithm.
  2. Passes the buffer description to IDirectSound8::CreateSoundBuffer, creating a secondary buffer object with 3-D capabilities.
  3. Calls QueryInterface to obtain the IDirectSound3DBuffer8 interface. This interface controls the 3-D properties of sounds played through the buffer.

The application sets the parameters of the listener by calling IDirectSound3DListener8::SetAllParameters. The listener properties are described in a DS3DLISTENER structure. To set the position of the sound source, the application calls IDirectSound3DBuffer8::SetAllParameters, passing in a DS3DBUFFER structure.

If the DS3D_DEFERRED flag is set when parameters are set, nothing is actually changed until IDirectSound3DListener8::CommitDeferredSettings is called. This method commits all deferred settings for buffers as well as the listener, and makes it possible for DirectSound to perform calculations once instead of many times.

See Also

  • DirectSound C++ Samples
  • 3-D Sound


Play Sound Sample

Description

The Play Sound sample shows how to play a WAV file in a DirectSound secondary buffer.

Path

Source: (SDK root)\Samples\C++\DirectSound\PlaySound

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Load a WAV file by clicking Sound File. Select Loop Sound if you want it to play repeatedly. Click Play.

Programming Notes

The sample shows the basic tasks required to play a sound in a DirectSound Buffer, as follows:

Set up DirectSound:

  1. Call the DirectSoundCreate function to create the DirectSound object.
  2. Call IDirectSound8::SetCooperativeLevel.
  3. Set the primary buffer format. This sample calls the DSUtil_SetPrimaryBufferFormat function in Dsutil.cpp to do this.

Load a WAV file into a DirectSound buffer:

  1. Read the WAV file header to get the data size and format.
  2. If the WAV file is a reasonable size, create a secondary buffer in the same format as the data, large enough to hold the entire file. If the WAV file is too large, data will have to be streamed to the buffer. See Stream Data Sample.
  3. Fill the buffer with data. Obtain a pointer into the buffer by calling IDirectSoundBuffer8::Lock. Because data is not being streamed as the buffer is playing, the entire buffer can be locked. After the memory has been copied, call IDirectSoundBuffer8::Unlock.

Play the DirectSound buffer:

  1. Check to see if the buffer has been lost. If so, restore it.
  2. To play the buffer call IDirectSoundBuffer8::Play.

Free DirectSound:

Call Release on all the DirectSound interfaces that were obtained. Release buffers before releasing the DirectSound object.

See Also

  • DirectSound C++ Samples
  • Filling and Playing Static Buffers


SoundFX Sample

Description

The SoundFX sample shows how to use DMOs with DirectSound and how to manipulate effect parameters.

Path

Source: (SDK root)\Samples\C++\DirectSound\SoundFX

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

A default sound file is loaded when the application is run. If you wish, load a different one by clicking Open File.

At first, no effects are enabled. Click Play to hear the sound without effects.

Click Stop to stop the buffer. Apply one or more effects by selecting checkboxes in the Enable column. Play the sound again.

To adjust parameters for an effect, select an option button in the Adjust column and change the values in the frame on the right side of the window. This can be done regardless of whether the sound is playing and regardless of whether the effect has been applied yet.

Programming Notes

The application implements a CSoundFXManager class to manage effects. An IDirectSoundBuffer8 interface is used to set effects on the buffer in the CSoundFXManager::ActivateFX method. Effect parameters are set in the OnEffectChanged function in response to messages from the interface.

See Also

  • DirectSound C++ Samples
  • Using Effects
  • Using Effects


Stream Data Sample

Description

The Stream Data sample shows how to stream a WAV file to a DirectSound secondary buffer. It is similar to the Play Sound Sample, but adds support for streaming.

Path

Source: (SDK root)\Samples\C++\DirectSound\StreamData

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Load a WAV file by clicking Sound File. Select Loop Sound if you want it to play repeatedly. Click Play.

Programming Notes

The sample shows the basic tasks required to play a streaming sound in a DirectSound secondary buffer.

Set up DirectSound:

  1. Call the DirectSoundCreate8 function to create the DirectSound object.
  2. Call IDirectSound8::SetCooperativeLevel.
  3. Set the primary buffer format. The sample calls the DSUtil_SetPrimaryBufferFormat function in Dsutil.cpp to do this.

Create a DirectSound buffer and set up the notifications:

  1. Read the WAV file header to get the data size and format.
  2. Choose a DirectSound buffer size. For this sample, the buffer holds about 3 seconds of data.
  3. Create a DirectSound buffer of that size and with the same format as the WAV file. Also set the DSBCAPS_CTRLPOSITIONNOTIFY flag so that the buffer can send notification events whenever playback has reached certain points in the buffer. On some drivers, using this flag limits the buffer to software, because the hardware buffers do not support position notifications.
  4. Set up the notifications on the buffer by obtaining an IDirectSoundNotify8 interface from the buffer and calling IDirectSoundNotify8::SetNotificationPositions. See the InitDSoundNotification function. When the play cursor passes a notification position, it signals a Win32 event.

Play the DirectSound buffer:

  1. Ascertain if the buffer has been lost, and call IDirectSoundBuffer8::Restore if so.
  2. Fill the entire buffer with data from the file.
  3. Call IDirectSoundBuffer8::Play with the DSBPLAY_LOOPING flag. The looping flag needs to be set so that the buffer will continue playing after the first batch of data has been played.

Check to ascertain if a notification is signaled:

  1. Look for a signaled event in the message loop or in a separate thread by calling MsgWaitForMultipleObjects.
  2. If a buffer notification event has been signaled, lock the section of the buffer that has just been played and fill it with new data. See the HandleNotification function.

Stop the buffer:

When handling the event notification, keep track of how much data has been put in the buffer. When the entire WAV file has been put into the buffer, and after DirectSound has played it all, it is necessary to manually stop the buffer since the buffer will continuously loop otherwise.

See Also

  • DirectSound C++ Samples
  • Using Streaming Buffers


Voice Management Sample

Description

The Voice Management sample shows how to implement dynamic voice management when creating DirectSound secondary buffers.

Path

Source: (SDK root)\Samples\C++\DirectSound\VoiceManagement

Executable: (SDK root)\Samples\C++\DirectSound\Bin

User's Guide

Load a WAV file by clicking Sound File. Select the Voice Allocation Flags, Buffer Priority, and Voice Management Flags options. Note that the effect of the selected options is described under Expected Behavior. Create the buffer and play the sound by clicking Play.

Programming Notes

To use voice management flags, the buffer must be created using DSBCAPS_LOCDEFER. Otherwise DirectSound will not be able to dynamically place the buffer in either hardware or software at run time.

When playing the buffer, call IDirectSoundBuffer8::Play with a valid combination of voice management flags. Run the sample to observe the result of any combination of flags.

See Also

  • DirectSound C++ Samples
  • Dynamic Voice Management


DirectSound C/C++ Reference

This section contains reference information for the Microsoft® DirectSound® application programming interface (API). Reference material is divided into the following categories.

  • DirectSound Interfaces
  • DirectSound Callback Function
  • DirectSound Functions
  • DirectSound Structures
  • DirectSound Return Values


DirectSound Interfaces

This section contains references for methods of the DirectSound interfaces shown in the following table.

Interface | Description
IDirectSound8 | Used to create buffer objects and set up the environment.
IDirectSound3DBuffer8 | Used to retrieve and set parameters that describe the position, orientation, and environment of a sound buffer in 3-D space.
IDirectSound3DListener8 | Used to retrieve and set parameters that describe a listener's position, orientation, and listening environment in 3-D space.
IDirectSoundBuffer8 | Used to manage sound buffers.
IDirectSoundCapture8 | Used to create sound capture buffers.
IDirectSoundCaptureBuffer8 | Used to manipulate sound capture buffers.
IDirectSoundCaptureFXAec8 | Used to set and retrieve parameters on a capture buffer that supports acoustic echo cancellation.
IDirectSoundCaptureFXNoiseSuppress8 | Used to set and retrieve parameters on a capture buffer that supports noise suppression.
IDirectSoundFullDuplex8 | Represents a full-duplex stream.
IDirectSoundFXChorus8 | Used to set and retrieve effect parameters on a buffer that supports chorus.
IDirectSoundFXCompressor8 | Used to set and retrieve effect parameters on a buffer that supports compression.
IDirectSoundFXDistortion8 | Used to set and retrieve effect parameters on a buffer that supports distortion.
IDirectSoundFXEcho8 | Used to set and retrieve effect parameters on a buffer that supports echo.
IDirectSoundFXFlanger8 | Used to set and retrieve effect parameters on a buffer that supports flange.
IDirectSoundFXGargle8 | Used to set and retrieve effect parameters on a buffer that supports amplitude modulation.
IDirectSoundFXI3DL2Reverb8 | Used to set and retrieve effect parameters on a buffer that supports I3DL2 (Interactive 3D Audio Level 2) reverberation effects.
IDirectSoundFXParamEq8 | Used to set and retrieve effect parameters on a buffer that supports parametric equalizer effects.
IDirectSoundFXWavesReverb8 | Used to set and retrieve effect parameters on a buffer that supports Waves reverberation effects.
IDirectSoundNotify8 | Sets up notification events for a playback or capture buffer.
IKsPropertySet | Enables drivers to provide extended capabilities that can be used without API extensions.

For DirectX 8.0 and later, only IDirectSound8, IDirectSoundBuffer8, and IDirectSoundCaptureBuffer8 are new interfaces that supersede interfaces with similar, unnumbered names. Other interface names ending in 8 are simple defines for unchanged or new unnumbered interfaces. For example, IDirectSoundCapture8 is exactly equivalent to IDirectSoundCapture.

All interfaces that have a defined name ending in 8 are documented under that defined name, and it is recommended that you always use this name in your code.

For information on which methods are supported by an earlier version of an interface, see the declaration of the interface in Dsound.h.

When a method takes an interface pointer as an in parameter, you can pass in the newer version even where the parameter type is declared as the earlier version. For example, a pointer to either IDirectSoundBuffer or IDirectSoundBuffer8 can be passed to IDirectSound8::DuplicateSoundBuffer as the pDSBufferOriginal parameter.

When a method returns an interface, however, it is usually the earlier interface, and to obtain the newer interface you must use QueryInterface. This is the case, for example, with the ppDSBuffer parameter of IDirectSound8::CreateSoundBuffer.


IDirectSound8 Interface

The IDirectSound8 interface is used to create buffer objects, manage devices, and set up the environment. This interface supersedes IDirectSound and adds new methods.

Obtain this interface by using the DirectSoundCreate8 or DirectSoundFullDuplexCreate8 function, or by using CoCreateInstance or CoCreateInstanceEx to create an object of class CLSID_DirectSound8.

In addition to the methods inherited from IUnknown, the IDirectSound8 interface exposes the following methods.

Method | Description
Compact | No effect.
CreateSoundBuffer | Creates a sound buffer object to manage audio samples.
DuplicateSoundBuffer | Creates a new secondary buffer that shares the original buffer's memory.
GetCaps | Retrieves the capabilities of the hardware device.
GetSpeakerConfig | Retrieves the speaker configuration.
Initialize | Initializes a device object that was created by using the CoCreateInstance function.
SetCooperativeLevel | Sets the cooperative level of the application for this sound device.
SetSpeakerConfig | Specifies the speaker configuration of the device.
VerifyCertification | Ascertains whether the device driver is certified for DirectX.

The LPDIRECTSOUND8 type is defined as a pointer to the IDirectSound8 interface:

typedef struct IDirectSound8  *LPDIRECTSOUND8;

Remarks

Only objects of class CLSID_DirectSound8 support this interface. All device objects created by DirectSoundCreate8 and DirectSoundFullDuplexCreate8 fall into this category. Objects of class CLSID_DirectSound, which include all those created by using the earlier DirectSoundCreate function, support only the earlier IDirectSound interface.

The behavior of CLSID_DirectSound8 objects is somewhat different from that of CLSID_DirectSound objects. These differences are found in the IDirectSound interface as well as the IDirectSound8 interface. Specific differences in the behavior of the newer object include the following:

  • In calls to IDirectSound::CreateSoundBuffer and IDirectSound8::CreateSoundBuffer, DSBCAPS_CTRL3D cannot be set on a buffer with a non-mono format, and DSBCAPS_CTRL3D cannot be combined with DSBCAPS_CTRLPAN.
  • New buffer creation flags are supported.
  • Buffers are not filled with silence on creation.
  • The IDirectSoundBuffer interface returned by CreateSoundBuffer can be queried for the IDirectSoundBuffer8 interface.
  • WAV formats in the DSBUFFERDESC structure that have the WAVE_FORMAT_EXTENSIBLE format tag are checked more strictly for validity.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • DirectSound Interfaces


IDirectSound8::Compact

The Compact method has no effect.

Syntax

HRESULT Compact();

Parameters

None.

Return Values

The return value is DS_OK.

Remarks

This method was formerly used for compacting the on-board memory of ISA sound cards.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSound8 Interface


IDirectSound8::CreateSoundBuffer

The CreateSoundBuffer method creates a sound buffer object to manage audio samples.

Syntax

HRESULT CreateSoundBuffer(
  LPCDSBUFFERDESC pcDSBufferDesc,
  LPDIRECTSOUNDBUFFER * ppDSBuffer,
  LPUNKNOWN pUnkOuter
);

Parameters

pcDSBufferDesc

Address of a DSBUFFERDESC structure that describes the sound buffer to create.

ppDSBuffer

Address of a variable that receives the IDirectSoundBuffer interface of the new buffer object. Use QueryInterface to obtain IDirectSoundBuffer8. IDirectSoundBuffer8 is not available for the primary buffer.

pUnkOuter

Address of the controlling object's IUnknown interface for COM aggregation. Must be NULL.

Return Values

If the method succeeds, the return value is DS_OK, or DS_NO_VIRTUALIZATION if a requested 3-D algorithm was not available and stereo panning was substituted. See the description of the guid3DAlgorithm member of DSBUFFERDESC.

If the method fails, the return value may be one of the error values shown in the following table.

Return code
DSERR_ALLOCATED
DSERR_BADFORMAT
DSERR_BUFFERTOOSMALL
DSERR_CONTROLUNAVAIL
DSERR_DS8_REQUIRED
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_NOAGGREGATION
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED
DSERR_UNSUPPORTED

Remarks

DirectSound does not initialize the contents of the buffer, and the application cannot assume that it contains silence.

If an attempt is made to create a buffer with the DSBCAPS_LOCHARDWARE flag on a system where hardware acceleration is not available, the method fails with either DSERR_CONTROLUNAVAIL or DSERR_INVALIDCALL, depending on the operating system.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSound8 Interface
  • IDirectSound8::DuplicateSoundBuffer
  • Creating Secondary Buffers


IDirectSound8::DuplicateSoundBuffer

The DuplicateSoundBuffer method creates a new secondary buffer that shares the original buffer's memory.

Syntax

HRESULT DuplicateSoundBuffer(
  LPDIRECTSOUNDBUFFER pDSBufferOriginal,
  LPDIRECTSOUNDBUFFER * ppDSBufferDuplicate
);

Parameters

pDSBufferOriginal

Address of the IDirectSoundBuffer or IDirectSoundBuffer8 interface of the buffer to duplicate.

ppDSBufferDuplicate

Address of a variable that receives the IDirectSoundBuffer interface pointer for the new buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_ALLOCATED
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED

Remarks

This method is not valid for buffers created with the DSBCAPS_CTRLFX flag.

Initially, the duplicate buffer will have the same parameters as the original buffer. However, the application can change the parameters of each buffer independently, and each can be played or stopped without affecting the other.

The buffer memory is released when the last object referencing it is released.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSound8 Interface
  • IDirectSound8::CreateSoundBuffer


IDirectSound8::GetCaps

The GetCaps method retrieves the capabilities of the hardware device that is represented by the device object.

Syntax

HRESULT GetCaps(
  LPDSCAPS pDSCaps
);

Parameters

pDSCaps

Address of a DSCAPS structure that receives the capabilities of this sound device.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the error values shown in the following table.

Return code
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_UNINITIALIZED

Remarks

Information retrieved in the DSCAPS structure describes the maximum capabilities of the sound device and those currently available, such as the number of hardware mixing channels and the amount of on-board sound memory. You can use this information to fine-tune performance and optimize resource allocation.

Because of resource-sharing requirements, the maximum capabilities in one area might be available only at the cost of another area.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSound8 Interface
  • Device Capabilities


IDirectSound8::GetSpeakerConfig

The GetSpeakerConfig method retrieves the speaker configuration.

Syntax

HRESULT GetSpeakerConfig(
  LPDWORD pdwSpeakerConfig
);

Parameters

pdwSpeakerConfig

Address of the speaker configuration for this device. The speaker configuration is specified with one of the values shown in the following table.

Value | Description
DSSPEAKER_5POINT1 | The audio is played through a speaker arrangement of five surround speakers with a subwoofer.
DSSPEAKER_DIRECTOUT | The audio is passed through directly, without being configured for speakers.
DSSPEAKER_HEADPHONE | The audio is played through headphones.
DSSPEAKER_MONO | The audio is played through a single speaker.
DSSPEAKER_QUAD | The audio is played through quadraphonic speakers.
DSSPEAKER_STEREO | The audio is played through stereo speakers (default value).
DSSPEAKER_SURROUND | The audio is played through surround speakers.
DSSPEAKER_7POINT1 | The audio is played through a speaker arrangement of seven surround speakers with a subwoofer.

DSSPEAKER_STEREO can be combined with one of the values shown in the following table.

Value | Description
DSSPEAKER_GEOMETRY_WIDE | The speakers are directed over an arc of 20 degrees.
DSSPEAKER_GEOMETRY_NARROW | The speakers are directed over an arc of 10 degrees.
DSSPEAKER_GEOMETRY_MIN | The speakers are directed over an arc of 5 degrees.
DSSPEAKER_GEOMETRY_MAX | The speakers are directed over an arc of 180 degrees.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the error values shown in the following table.

Return code
DSERR_INVALIDPARAM
DSERR_UNINITIALIZED

Remarks

The value returned at pdwSpeakerConfig can be a packed DWORD containing both configuration and geometry information. Use the DSSPEAKER_CONFIG and DSSPEAKER_GEOMETRY macros to unpack the DWORD, as in the following example:

if (DSSPEAKER_CONFIG(dwSpeakerConfig) == DSSPEAKER_STEREO)
  {
  if (DSSPEAKER_GEOMETRY(dwSpeakerConfig) ==
        DSSPEAKER_GEOMETRY_WIDE)
    {
      // Configuration is wide stereo.
 ...}
  }

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSound8 Interface
  • IDirectSound8::SetSpeakerConfig
  • Speaker Configuration


IDirectSound8::Initialize

The Initialize method initializes a device object that was created by using the CoCreateInstance function.

Syntax

HRESULT Initialize(
  LPCGUID pcGuidDevice
);

Parameters

pcGuidDevice

Address of the globally unique identifier (GUID) specifying the sound driver to which this device object binds. Pass NULL to select the primary sound driver.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the error values shown in the following table.

Return code
DSERR_ALREADYINITIALIZED
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_NODRIVER

Remarks

This method is provided for compliance with the Component Object Model (COM) protocol. If the DirectSoundCreate8 function was used to create the device object, this method returns DSERR_ALREADYINITIALIZED. If IDirectSound8::Initialize is not called when using CoCreateInstance to create the device object, any method called afterward returns DSERR_UNINITIALIZED.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSound8 Interface


IDirectSound8::SetCooperativeLevel

The SetCooperativeLevel method sets the cooperative level of the application for this sound device.

Syntax

HRESULT SetCooperativeLevel(
  HWND hwnd,
  DWORD dwLevel
);

Parameters

hwnd

Handle to the application window.

dwLevel

Requested level. Specify one of the values shown in the following table.

Value | Description
DSSCL_EXCLUSIVE | For DirectX 8.0 and later, has the same effect as DSSCL_PRIORITY. For previous versions, sets the application to the exclusive level. This means that when it has the input focus, the application will be the only one audible; sounds from applications with the DSBCAPS_GLOBALFOCUS flag set will be muted. With this level, it also has all the privileges of the DSSCL_PRIORITY level. DirectSound will restore the hardware format, as specified by the most recent call to the IDirectSoundBuffer8::SetFormat method, after the application gains the input focus.
DSSCL_NORMAL | Sets the normal level. This level has the smoothest multitasking and resource-sharing behavior, but because it does not allow the primary buffer format to change, output is restricted to the default 8-bit format.
DSSCL_PRIORITY | Sets the priority level. Applications with this cooperative level can call the IDirectSoundBuffer8::SetFormat and IDirectSound8::Compact methods.
DSSCL_WRITEPRIMARY | Sets the write-primary level. The application has write access to the primary buffer. No secondary buffers can be played. This level cannot be set if the DirectSound driver is being emulated for the device; that is, if the IDirectSound8::GetCaps method returns the DSCAPS_EMULDRIVER flag in the DSCAPS structure.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the error values shown in the following table.

Return code
DSERR_ALLOCATED
DSERR_INVALIDPARAM
DSERR_UNINITIALIZED
DSERR_UNSUPPORTED

Remarks

The application must set the cooperative level by calling this method before its buffers can be played. The recommended cooperative level is DSSCL_PRIORITY.

Do not call this method if any buffers are locked.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSound8 Interface
  • Cooperative Levels


IDirectSound8::SetSpeakerConfig

The SetSpeakerConfig method specifies the speaker configuration of the device.

Note This function controls a global Windows setting that affect all users and applications on the system. It is provided only for use by configuration utilities provided by audio device vendors. No other applications should call it.

Syntax

HRESULT SetSpeakerConfig(
  DWORD dwSpeakerConfig
);

Parameters

dwSpeakerConfig

Speaker configuration of the specified device object. This parameter can be one of the values shown in the following tables.

Value | Description
DSSPEAKER_5POINT1 | The audio is played through a speaker arrangement of surround speakers with a subwoofer.
DSSPEAKER_DIRECTOUT | The audio is passed through directly, without being configured for speakers.
DSSPEAKER_HEADPHONE | The speakers are headphones.
DSSPEAKER_MONO | The speakers are monaural.
DSSPEAKER_QUAD | The speakers are quadraphonic.
DSSPEAKER_STEREO | The speakers are stereo (default value).
DSSPEAKER_SURROUND | The speakers are surround sound.
DSSPEAKER_7POINT1 | The audio is played through a speaker arrangement of seven surround speakers with a subwoofer.

DSSPEAKER_STEREO can be combined with one of the values in the following table.

Value | Description
DSSPEAKER_GEOMETRY_WIDE | The speakers are directed over an arc of 20 degrees.
DSSPEAKER_GEOMETRY_NARROW | The speakers are directed over an arc of 10 degrees.
DSSPEAKER_GEOMETRY_MIN | The speakers are directed over an arc of 5 degrees.
DSSPEAKER_GEOMETRY_MAX | The speakers are directed over an arc of 180 degrees.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the error values shown in the following table.

Return code
DSERR_INVALIDPARAM
DSERR_UNINITIALIZED

Remarks

If a geometry value is to be used, it must be packed in a DWORD along with the DSSPEAKER_STEREO flag. This can be done by using the DSSPEAKER_COMBINED macro, as in the following C++ example:

lpds->SetSpeakerConfig(DSSPEAKER_COMBINED(
    DSSPEAKER_STEREO, DSSPEAKER_GEOMETRY_WIDE));

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSound8 Interface
  • IDirectSound8::GetSpeakerConfig
  • Speaker Configuration


IDirectSound8::VerifyCertification

The VerifyCertification method ascertains whether the device driver is certified for DirectX.

Syntax

VerifyCertification(
  LPDWORD pdwCertified
);

Parameters

pdwCertified

Address of a DWORD variable that receives one of the values shown in the following table.

Value | Description
DS_CERTIFIED | Driver is certified for DirectSound.
DS_UNCERTIFIED | Driver is not certified for DirectSound.

Return Values

If the function succeeds, the return value is DS_OK.

If the function fails, the return value may be one of the error values shown in the following table.

Return code
DSERR_INVALIDPARAM
DSERR_UNSUPPORTED

Remarks

This method may attempt to retrieve certification information from the Internet.

On emulated devices, the method returns DSERR_UNSUPPORTED. Emulated devices are identified by the DSCAPS_EMULDRIVER flag in the dwFlags member of DSCAPS.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSound8 Interface


IDirectSound3DBuffer8 Interface

The IDirectSound3DBuffer8 interface is used to retrieve and set parameters that describe the position, orientation, and environment of a sound buffer in 3-D space.

IDirectSound3DBuffer8 is a define for IDirectSound3DBuffer. The two interface names are interchangeable.

The IDirectSound3DBuffer8 interface is obtained from a buffer that was created with the DSBCAPS_CTRL3D flag. You can get it from the IDirectSoundBuffer8 interface by using the QueryInterface method, or retrieve it from a DirectMusic audiopath by using IDirectMusicSegmentState8::GetObjectInPath or IDirectMusicAudioPath8::GetObjectInPath.

In addition to the methods inherited from IUnknown, the IDirectSound3DBuffer8 interface exposes the following methods, arranged by category.

3-D mode

Method | Description
GetMode | Retrieves the operation mode for 3-D sound processing.
SetMode | Sets the operation mode for 3-D sound processing.

Batch parameters

Method | Description
GetAllParameters | Retrieves all 3-D properties of the sound buffer.
SetAllParameters | Sets all 3-D properties of the sound buffer.

Minimum and maximum distance

Method | Description
GetMaxDistance | Retrieves the maximum distance, which is the distance from the listener beyond which sounds in this buffer are no longer attenuated.
GetMinDistance | Retrieves retrieves the minimum distance, which is the distance from the listener at which sounds in this buffer begin to be attenuated.
SetMaxDistance | Sets the maximum distance.
SetMinDistance | Sets the minimum distance.

Position

Method | Description
GetPosition | Retrieves the position of the sound source.
SetPosition | Sets the position of the sound source.

Sound projection cone

Method | Description
GetConeAngles | Retrieves the inside and outside angles of the sound projection cone.
GetConeOrientation | Retrieves the orientation of the sound projection cone.
GetConeOutsideVolume | Retrieves the volume of the sound outside the outside angle of the sound projection cone.
SetConeAngles | Sets the inside and outside angles of the sound projection cone.
SetConeOrientation | Sets the orientation of the sound projection cone.
SetConeOutsideVolume | Sets the volume of the sound outside the outside angle of the sound projection cone.

Velocity

Method | Description
GetVelocity | Retrieves the velocity of the sound source.
SetVelocity | Sets the velocity of the sound source.

The LPDIRECTSOUND3DBUFFER type is defined as a pointer to the IDirectSound3DBuffer8 interface:

typedef struct IDirectSound3DBuffer  *LPDIRECTSOUND3DBUFFER;

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • DirectSound Interfaces
  • DirectSound 3-D Buffers


IDirectSound3DBuffer8::GetAllParameters

The GetAllParameters method retrieves the 3-D properties of the sound buffer.

Syntax

HRESULT GetAllParameters(
  LPDS3DBUFFER pDs3dBuffer
);

Parameters

pDs3dBuffer

Address of a DS3DBUFFER structure that receives the information describing the 3-D characteristics of the sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DBuffer8 Interface
  • Batch Parameters for 3-D Buffers


IDirectSound3DBuffer8::GetConeAngles

The GetConeAngles method retrieves the inside and outside angles of the sound projection cone.

Syntax

HRESULT GetConeAngles(
  LPDWORD pdwInsideConeAngle,
  LPDWORD pdwOutsideConeAngle
);

Parameters

pdwInsideConeAngle

Addresses of a variable that receives the inside angle of the sound projection cone, in degrees. This is the angle within which the sound is at its normal volume.

pdwOutsideConeAngle

Addresses of a variable that receives the outside angle of the sound projection cone, in degrees. This is the angle outside of which the sound is at its outside volume.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The minimum, maximum, and default cone angles are defined in Dsound.h as DS3D_MINCONEANGLE, DS3D_MAXCONEANGLE, and DS3D_DEFAULTCONEANGLE.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DBuffer8 Interface
  • IDirectSound3DBuffer8::GetConeOrientation
  • IDirectSound3DBuffer8::GetConeOutsideVolume
  • IDirectSound3DBuffer8::SetConeOrientation
  • IDirectSound3DBuffer8::SetConeOutsideVolume
  • Sound Cones


IDirectSound3DBuffer8::GetConeOrientation

The GetConeOrientation method retrieves the orientation of the sound projection cone.

Syntax

HRESULT GetConeOrientation(
  D3DVECTOR * pvOrientation
);

Parameters

pvOrientation

Address of a D3DVECTOR structure that receives the orientation of the sound projection cone. The vector information represents the center of the sound cone.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The values returned are not necessarily the same as those set by using the SetConeOrientation method. DirectSound normalizes orientation vectors so that all axes have a magnitude of less than or equal to 1.0.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DBuffer8 Interface
  • IDirectSound3DBuffer8::SetConeAngles
  • IDirectSound3DBuffer8::SetConeOrientation
  • IDirectSound3DBuffer8::SetConeOutsideVolume
  • Sound Cones


IDirectSound3DBuffer8::GetConeOutsideVolume

The GetConeOutsideVolume method retrieves the volume of the sound outside the outside angle of the sound projection cone.

Syntax

HRESULT GetConeOutsideVolume(
  LPLONG plConeOutsideVolume
);

Parameters

plConeOutsideVolume

Address of a variable that receives the cone outside volume for this buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Volume levels are expressed as attenuation, in hundredths of a decibel. Allowable values are between DSBVOLUME_MAX (no attenuation) and DSBVOLUME_MIN (silence). The default value is DS3D_DEFAULTCONEOUTSIDEVOLUME (no attenuation). These values are defined in Dsound.h. DirectSound does not support amplification.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DBuffer8 Interface
  • IDirectSound3DBuffer8::GetConeOrientation
  • IDirectSound3DBuffer8::SetConeOrientation
  • IDirectSound3DBuffer8::SetConeOutsideVolume
  • Sound Cones


IDirectSound3DBuffer8::GetMaxDistance

The GetMaxDistance method retrieves the maximum distance, which is the distance from the listener beyond which sounds in this buffer are no longer attenuated.

Syntax

HRESULT GetMaxDistance(
  D3DVALUE * pflMaxDistance
);

Parameters

pflMaxDistance

Address of a variable that receives the maximum distance, in meters by default. D3DVALUE is defined as float.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The default maximum distance, defined as DS3D_DEFAULTMAXDISTANCE, is effectively infinite.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DBuffer8 Interface
  • IDirectSound3DBuffer8::GetMinDistance
  • IDirectSound3DBuffer8::SetMaxDistance
  • Minimum and Maximum Distances


IDirectSound3DBuffer8::GetMinDistance

The GetMinDistance method retrieves the minimum distance, which is the distance from the listener at which sounds in this buffer begin to be attenuated.

Syntax

HRESULT GetMinDistance(
  D3DVALUE * pflMinDistance
);

Parameters

pflMinDistance

Address of a variable that receives the minimum distance, in meters by default. D3DVALUE is defined as float.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

By default, the minimum distance value is DS3D_DEFAULTMINDISTANCE, defined as 1.0 (corresponding to 1.0 meter at the default distance factor of 1.0 meters per unit).

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DBuffer8 Interface
  • IDirectSound3DBuffer8::GetMaxDistance
  • IDirectSound3DBuffer8::SetMinDistance
  • Minimum and Maximum Distances


IDirectSound3DBuffer8::GetMode

The GetMode method retrieves the operation mode for 3-D sound processing.

Syntax

HRESULT GetMode(
  LPDWORD pdwMode
);

Parameters

pdwMode

Address of a variable that receives the mode setting. This value will be one of those in the following table.

Value | Description
DS3DMODE_DISABLE | Processing of 3-D sound is disabled. The sound seems to originate from the center of the listener's head.
DS3DMODE_HEADRELATIVE | Sound parameters (position, velocity, and orientation) are relative to the listener's parameters. In this mode, the absolute parameters of the sound are updated automatically as the listener's parameters change, so that the relative parameters remain constant.
DS3DMODE_NORMAL | Normal processing. This is the default mode.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DBuffer8 Interface
  • Processing Mode


IDirectSound3DBuffer8::GetPosition

The GetPosition method retrieves the position of the sound source.

Syntax

HRESULT GetPosition(
  D3DVECTOR * pvPosition
);

Parameters

pvPosition

Address of a D3DVECTOR structure that receives the position of the sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

By default, distance units are meters, but the units can be changed by using the IDirectSound3DListener8::SetDistanceFactor method.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DBuffer8 Interface
  • Buffer Position and Velocity


IDirectSound3DBuffer8::GetVelocity

The GetVelocity method retrieves the velocity of the sound source.

Syntax

HRESULT GetVelocity(
  D3DVECTOR * pvVelocity
);

Parameters

pvVelocity

Address of a D3DVECTOR structure that receives the sound buffer's velocity, in meters per second by default.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Velocity is used for Doppler effects only. It does not actually move the buffer. For more information, see Doppler Effect.

The default unit of measurement is meters per second, but this can be changed by using the IDirectSound3DListener8::SetDistanceFactor method.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DBuffer8 Interface
  • IDirectSound3DBuffer8::SetPosition
  • IDirectSound3DBuffer8::SetVelocity
  • Buffer Position and Velocity


IDirectSound3DBuffer8::SetAllParameters

The SetAllParameters method sets all 3-D sound buffer properties.

Syntax

HRESULT SetAllParameters(
  LPCDS3DBUFFER pcDs3dBuffer,
  DWORD dwApply
);

Parameters

pcDs3dBuffer

Address of a DS3DBUFFER structure that describes the 3-D characteristics of the sound buffer.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DBuffer8 Interface
  • Batch Parameters for 3-D Buffers
  • Deferred Settings


IDirectSound3DBuffer8::SetConeAngles

The SetConeAngles method sets the inside and outside angles of the sound projection cone.

Syntax

HRESULT SetConeAngles(
  DWORD dwInsideConeAngle,
  DWORD dwOutsideConeAngle,
  DWORD dwApply
);

Parameters

dwInsideConeAngle

Inside cone angle, in degrees. This is the angle within which the sound is at its normal volume.

dwOutsideConeAngle

Outside cone angle, in degrees. This is the angle outside of which the sound is at its outside volume.

dwApply

Value that indicates when the setting should be applied. Must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The minimum, maximum, and default cone angles are defined in Dsound.h as DS3D_MINCONEANGLE, DS3D_MAXCONEANGLE, and DS3D_DEFAULTCONEANGLE. Each angle must be in the range of 0 degrees (no cone) to 360 degrees (the full sphere). The default value is 360.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DBuffer8 Interface
  • IDirectSound3DBuffer8::SetConeOrientation
  • IDirectSound3DBuffer8::SetConeOutsideVolume
  • Deferred Settings
  • Sound Cones


IDirectSound3DBuffer8::SetConeOrientation

The SetConeOrientation method sets the orientation of the sound projection cone.

Syntax

HRESULT SetConeOrientation(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z,
  DWORD dwApply
);

Parameters

x, y, and z

Values that specify the coordinates of the sound cone orientation vector. D3DVALUE is defined as float.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

This method has no effect unless the cone angle and cone outside volume have also been set to values other than the default.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DBuffer8 Interface
  • IDirectSound3DBuffer8::SetConeAngles
  • IDirectSound3DBuffer8::SetConeOutsideVolume
  • Deferred Settings
  • Sound Cones


IDirectSound3DBuffer8::SetConeOutsideVolume

The SetConeOutsideVolume method sets the volume of the sound outside the outside angle of the sound projection cone.

Syntax

HRESULT SetConeOutsideVolume(
  LONG lConeOutsideVolume,
  DWORD dwApply
);

Parameters

lConeOutsideVolume

Cone outside volume, in hundredths of a decibel.

dwApply

Value that specifies when the setting should be applied. This value must be one of the those shown in the following table.

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Volume levels are represented by attenuation. Allowable values are between DSBVOLUME_MAX (no attenuation) and DSBVOLUME_MIN (silence). The default value is DS3D_DEFAULTCONEOUTSIDEVOLUME (no attenuation). These values are defined in Dsound.h. DirectSound does not support amplification.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DBuffer8 Interface
  • IDirectSound3DBuffer8::SetConeAngles
  • IDirectSound3DBuffer8::SetConeOrientation
  • IDirectSoundBuffer8::SetVolume
  • Deferred Settings
  • Sound Cones


IDirectSound3DBuffer8::SetMaxDistance

The SetMaxDistance method sets the maximum distance, which is the distance from the listener beyond which sounds in this buffer are no longer attenuated.

Syntax

HRESULT SetMaxDistance(
  D3DVALUE flMaxDistance,
  DWORD dwApply
);

Parameters

flMaxDistance

Maximum distance, in meters by default. D3DVALUE is defined as float.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The default maximum distance, defined as DS3D_DEFAULTMAXDISTANCE, is effectively infinite.

The default unit of measurement is meters, but this can be changed by using the IDirectSound3DListener8::SetDistanceFactor method.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DBuffer8 Interface
  • IDirectSound3DBuffer8::GetMaxDistance
  • IDirectSound3DBuffer8::SetMinDistance
  • Deferred Settings
  • Minimum and Maximum Distances


IDirectSound3DBuffer8::SetMinDistance

The SetMinDistance method sets the minimum distance, which is the distance from the listener at which sounds in this buffer begin to be attenuated.

Syntax

HRESULT SetMinDistance(
  D3DVALUE flMinDistance,
  DWORD dwApply
);

Parameters

flMinDistance

Minimum distance, in meters by default. D3DVALUE is defined as float.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

By default, the minimum distance value is DS3D_DEFAULTMINDISTANCE, defined as 1.0 (corresponding to 1.0 meter at the default distance factor of 1.0 meters per unit).

The default unit of measurement is meters, but this can be changed by using the IDirectSound3DListener8::SetDistanceFactor method.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DBuffer8 Interface
  • IDirectSound3DBuffer8::SetMaxDistance
  • Deferred Settings
  • Minimum and Maximum Distances


IDirectSound3DBuffer8::SetMode

The SetMode method sets the operation mode for 3-D sound processing.

Syntax

HRESULT SetMode(
  DWORD dwMode,
  DWORD dwApply
);

Parameters

dwMode

Flag specifying the 3-D sound processing mode to be set. The following flags are defined:

Value | Description
DS3DMODE_DISABLE | Processing of 3-D sound is disabled. The sound seems to originate from the center of the listener's head.
DS3DMODE_HEADRELATIVE | Sound parameters (position, velocity, and orientation) are relative to the listener's parameters. In this mode, the absolute parameters of the sound are updated automatically as the listener's parameters change, so that the relative parameters remain constant.
DS3DMODE_NORMAL | Normal processing. This is the default mode.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DBuffer8 Interface
  • Deferred Settings
  • Processing Mode


IDirectSound3DBuffer8::SetPosition

The SetPosition method sets the position of the sound source.

Syntax

HRESULT SetPosition(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z,
  DWORD dwApply
);

Parameters

x, y, and z

Values that specify the coordinates of the position vector. DirectSound may adjust these values to prevent floating-point overflow. D3DVALUE is defined as float.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The default unit of measurement is meters, but this can be changed by using the IDirectSound3DListener8::SetDistanceFactor method.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DBuffer8 Interface
  • Deferred Settings
  • Buffer Position and Velocity


IDirectSound3DBuffer8::SetVelocity

The SetVelocity method sets the velocity of the sound source.

Syntax

HRESULT SetVelocity(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z,
  DWORD dwApply
);

Parameters

x, y, and z

Values that specify the coordinates of the velocity vector, in meters per second by default. DirectSound may adjust these values to prevent floating-point overflow. D3DVALUE is defined as float.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Velocity is used only for calculating Doppler effect. It does not change the position of the buffer. For more information, see Doppler Effect.

The default unit of measurement is meters per second, but this can be changed by using the IDirectSound3DListener8::SetDistanceFactor method.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DBuffer8 Interface
  • IDirectSound3DBuffer8::GetVelocity
  • IDirectSound3DBuffer8::SetPosition
  • Buffer Position and Velocity
  • Deferred Settings


IDirectSound3DListener8 Interface

The IDirectSound3DListener8 interface is used to retrieve and set parameters that describe a listener's position, orientation, and listening environment in 3-D space.

The interface can be obtained by calling the IDirectSoundBuffer8::QueryInterface method on a primary buffer created with the DSBCAPS_CTRL3D flag.

In addition to the methods inherited from IUnknown, the IDirectSound3DListener8 interface exposes the following methods, arranged by category.

Batch parameters

Method | Description
CommitDeferredSettings | Commits any deferred settings made since the last call to this method.
GetAllParameters | Retrieves all 3-D parameters of the sound environment and the listener.
SetAllParameters | Sets all 3-D parameters of the sound environment and the listener.

Global sound properties

Method | Description
GetDistanceFactor | Retrieves the distance factor, which is the number of meters in a vector unit.
GetDopplerFactor | Retrieves the multiplier for the Doppler effect.
GetRolloffFactor | Retrieves the rolloff factor, which determines the rate of attenuation over distance.
SetDistanceFactor | Sets the distance factor.
SetDopplerFactor | Sets the multiplier for the Doppler effect.
SetRolloffFactor | Sets the rolloff factor.

Listener properties

Method | Description
GetOrientation | Retrieves the orientation of the listener's head.
GetPosition | Retrieves the listener's position.
GetVelocity | Retrieves the listener's velocity.
SetOrientation | Sets the orientation of the listener's head.
SetPosition | Sets the listener's position.
SetVelocity | Sets the listener's velocity.

The LPDIRECTSOUND3DLISTENER type is defined as a pointer to the IDirectSound3DListener interface:

typedef struct IDirectSound3DListener  *LPDIRECTSOUND3DLISTENER;

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • DirectSound Interfaces


IDirectSound3DListener8::CommitDeferredSettings

The CommitDeferredSettings method commits any deferred settings made since the last call to this method.

Syntax

HRESULT CommitDeferredSettings();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DListener8 Interface
  • Deferred Settings


IDirectSound3DListener8::GetAllParameters

The GetAllParameters method retrieves all 3-D parameters of the sound environment and the listener.

Syntax

HRESULT GetAllParameters(
  LPDS3DLISTENER pListener
);

Parameters

pListener

Address of a DS3DLISTENER structure that receives the state of the 3-D world and listener.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::SetAllParameters


IDirectSound3DListener8::GetDistanceFactor

The GetDistanceFactor method retrieves the distance factor, which is the number of meters in a vector unit.

Syntax

HRESULT GetDistanceFactor(
  D3DVALUE * pflDistanceFactor
);

Parameters

pflDistanceFactor

Address of a variable that receives the distance factor value. D3DVALUE is defined as float.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::SetDistanceFactor
  • Distance Factor


IDirectSound3DListener8::GetDopplerFactor

The GetDopplerFactor method retrieves the multiplier for the Doppler effect.

Syntax

HRESULT GetDopplerFactor(
  D3DVALUE * pflDopplerFactor
);

Parameters

pflDopplerFactor

Address of a variable that receives the Doppler factor value. D3DVALUE is defined as float.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The Doppler factor has a range of DS3D_MINDOPPLERFACTOR (no Doppler effects) to DS3D_MAXDOPPLERFACTOR (defined as 10 times the Doppler effects found in the real world). The default value is DS3D_DEFAULTDOPPLERFACTOR (1.0).

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::SetDopplerFactor
  • Doppler Effect


IDirectSound3DListener8::GetOrientation

The GetOrientation method retrieves the orientation of the listener's head.

Syntax

HRESULT GetOrientation(
  D3DVECTOR * pvOrientFront,
  D3DVECTOR * pvOrientTop
);

Parameters

pvOrientFront

Address of a D3DVECTOR structure that receives the listener's front orientation vector.

pvOrientTop

Address of a D3DVECTOR structure that receives the listener's top orientation vector.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The front vector points in the direction of the listener's nose, and the top vector points up from the top of the listener's head. By default, the front vector is (0,0,1.0) and the top vector is (0,1.0,0).

The values returned are not necessarily the same as those set by using SetOrientation. DirectSound normalizes orientation vectors so that they are at right angles and have a magnitude of less than or equal to 1.0.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::SetOrientation
  • Spatial Parameters of the Listener


IDirectSound3DListener8::GetPosition

The GetPosition method retrieves the listener's position.

Syntax

HRESULT GetPosition(
  D3DVECTOR * pvPosition
);

Parameters

pvPosition

Address of a D3DVECTOR structure that receives the listener's position vector.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

By default, measurement units are meters, but this can be changed by calling the IDirectSound3DListener8::SetDistanceFactor method.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::SetPosition
  • Spatial Parameters of the Listener


IDirectSound3DListener8::GetRolloffFactor

The GetRolloffFactor method retrieves the rolloff factor, which determines the rate of attenuation over distance.

Syntax

HRESULT GetRolloffFactor(
  D3DVALUE * pflRolloffFactor
);

Parameters

pflRolloffFactor

Address of a variable that receives the rolloff factor. D3DVALUE is defined as float.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The rolloff factor has a range of DS3D_MINROLLOFFFACTOR (no rolloff) to DS3D_MAXROLLOFFFACTOR (defined as 10 times the rolloff found in the real world). The default value is DS3D_DEFAULTROLLOFFFACTOR (1.0). For more information, see Rolloff Factor.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::SetRolloffFactor
  • Rolloff Factor


IDirectSound3DListener8::GetVelocity

The GetVelocity method retrieves the listener's velocity.

Syntax

HRESULT GetVelocity(
  D3DVECTOR * pvVelocity
);

Parameters

pvVelocity

Address of a D3DVECTOR structure that receives the listener's velocity.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Velocity is used only for calculating Doppler effect. It does not change the listener's position. To move the listener, use the IDirectSound3DListener8::SetPosition method.

The default velocity is (0,0,0).

Remarks

By default, measurement units are meters per second, but this can be changed by calling the IDirectSound3DListener8::SetDistanceFactor method.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::SetVelocity
  • Spatial Parameters of the Listener


IDirectSound3DListener8::SetAllParameters

The SetAllParameters method sets all 3-D parameters of the sound environment and the listener.

Syntax

HRESULT SetAllParameters(
  LPCDS3DLISTENER pcListener,
  DWORD dwApply
);

Parameters

pcListener

Address of a DS3DLISTENER structure that contains information describing all 3-D listener parameters.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::GetAllParameters
  • Deferred Settings


IDirectSound3DListener8::SetDistanceFactor

The SetDistanceFactor method sets the distance factor, which is the number of meters in a vector unit.

Syntax

HRESULT SetDistanceFactor(
  D3DVALUE flDistanceFactor,
  DWORD dwApply
);

Parameters

flDistanceFactor

Distance factor. D3DVALUE is defined as float.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The distance factor has a range of DS3D_MINDISTANCEFACTOR to DS3D_MAXDISTANCEFACTOR, defined in Dsound.h as FLT_MIN and FLT_MAX respectively. The default value is DS3D_DEFAULTDISTANCEFACTOR, or 1.0.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::GetDistanceFactor
  • Deferred Settings
  • Distance Factor


IDirectSound3DListener8::SetDopplerFactor

The SetDopplerFactor method sets the multiplier for the Doppler effect.

Syntax

HRESULT SetDopplerFactor(
  D3DVALUE flDopplerFactor,
  DWORD dwApply
);

Parameters

flDopplerFactor

Doppler factor. D3DVALUE is defined as float.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The Doppler factor has a range of DS3D_MINDOPPLERFACTOR (no Doppler effects) to DS3D_MAXDOPPLERFACTOR (defined as 10 times the Doppler effects found in the real world). The default value is DS3D_DEFAULTDOPPLERFACTOR (1.0).

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::GetDopplerFactor
  • Deferred Settings
  • Doppler Effect


IDirectSound3DListener8::SetOrientation

The SetOrientation method sets the orientation of the listener's head.

Syntax

HRESULT SetOrientation(
  D3DVALUE xFront,
  D3DVALUE yFront,
  D3DVALUE zFront,
  D3DVALUE xTop,
  D3DVALUE yTop,
  D3DVALUE zTop,
  DWORD  dwApply
);

Parameters

xFront, yFront, zFront

Values that specify the coordinates of the front orientation vector. D3DVALUE is defined as float.

xTop, yTop, zTop

Values that specify the coordinates of the top orientation vector.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The front vector points in the direction of the listener's nose, and the top vector points up from the top of the listener's head. By default, the front vector is (0,0,1.0) and the top vector is (0,1.0,0).

The top vector must be at right angles to the front vector. If necessary, DirectSound adjusts the top vector after setting the front vector.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::GetOrientation
  • Deferred Settings
  • Spatial Parameters of the Listener


IDirectSound3DListener8::SetPosition

The SetPosition method sets the listener's position.

Syntax

HRESULT SetPosition(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z,
  DWORD dwApply
);

Parameters

x, y, and z

Values that specify the coordinates of the listener's position vector. Note that DirectSound may adjust these values to prevent floating-point overflow. D3DVALUE is defined as float.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

By default, measurement units are meters, but this can be changed by calling the IDirectSound3DListener8::SetDistanceFactor method.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::GetPosition
  • Deferred Settings
  • Spatial Parameters of the Listener


IDirectSound3DListener8::SetRolloffFactor

The SetRolloffFactor method sets the rolloff factor, which determines the rate of attenuation over distance.

Syntax

HRESULT SetRolloffFactor(
  D3DVALUE flRolloffFactor,
  DWORD dwApply
);

Parameters

flRolloffFactor

Rolloff factor. D3DVALUE is defined as float.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The rolloff factor has a range of DS3D_MINROLLOFFFACTOR (no rolloff) to DS3D_MAXROLLOFFFACTOR (defined as 10 times the rolloff found in the real world). The default value is DS3D_DEFAULTROLLOFFFACTOR (1.0). For more information, see Rolloff Factor.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::GetRolloffFactor
  • Deferred Settings
  • Rolloff Factor


IDirectSound3DListener8::SetVelocity

The SetVelocity method sets the listener's velocity.

Syntax

HRESULT SetVelocity(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z,
  DWORD dwApply
);

Parameters

x, y, and z

Values that specify the coordinates of the listener's velocity vector. DirectSound may adjust these values to prevent floating-point overflow. D3DVALUE is defined as float.

dwApply

Value that specifies when the setting should be applied. This value must be one of the following:

Value | Description
DS3D_DEFERRED | Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE | Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Velocity is used only for Doppler effects. It does not actually move the listener. To change the listener's position, use the IDirectSound3DListener8::SetPosition method. The default velocity is (0,0,0).

By default, measurement units are meters per second, but this can be changed by calling the IDirectSound3DListener8::SetDistanceFactor method.

Requirements

Header: Dsound.h
Library: Dsound3d.dll

See Also

  • IDirectSound3DListener8 Interface
  • IDirectSound3DListener8::GetVelocity
  • Deferred Settings
  • Spatial Parameters of the Listener


IDirectSoundBuffer8 Interface

The IDirectSoundBuffer8 interface is used to manage sound buffers.

The IDirectSoundBuffer8 interface supersedes IDirectSoundBuffer and adds new methods.

To obtain the interface, use the IDirectSound8::CreateSoundBuffer method to retrieve IDirectSoundBuffer, and then pass IID_IDirectSoundBuffer8 to IDirectSoundBuffer::QueryInterface.

For the primary buffer, you must use the IDirectSoundBuffer interface; IDirectSoundBuffer8 is not available. IDirectSoundBuffer is not documented separately. For documentation, see the corresponding IDirectSoundBuffer8 methods.

Not all methods of IDirectSoundBuffer are valid for primary buffers. For example, SetCurrentPosition will fail. See the reference topics for individual methods.

In addition to the methods inherited from IUnknown, the IDirectSoundBuffer8 interface exposes the following methods, arranged by category.

Effects

Method | Description
GetObjectInPath | Retrieves an interface for an effect object associated with the buffer.
SetFX | Enables effects on a buffer.

Resource management

Method | Description
AcquireResources | Allocates resources for a buffer that was created with the DSBCAPS_LOCDEFER flag.
Restore | Restores the memory allocation for a lost sound buffer

Play management

Method | Description
GetCurrentPosition | Retrieves the position of the play and write cursors in the sound buffer.
Lock | Readies all or part of the buffer for a data write and returns pointers to which data can be written.
Play | Causes the sound buffer to play, starting at the play cursor.
SetCurrentPosition | Sets the position of the play cursor, which is the point at which the next byte of data is read from the buffer.
Stop | Causes the sound buffer to stop playing.
Unlock | Releases a locked sound buffer.

Sound parameters

Method | Description
GetFrequency | Retrieves the frequency, in samples per second, at which the buffer is playing.
GetPan | Retrieves the relative volume of the left and right audio channels.
GetVolume | Retrieves the attenuation of the sound.
SetFrequency | Sets the frequency at which the audio samples are played.
SetPan | Sets the relative volume of the left and right channels.
SetVolume | Sets the attenuation of the sound.

Miscellaneous

Method | Description
GetCaps | Retrieves the capabilities of the buffer object.
GetFormat | Retrieves a description of the format of the sound data in the buffer, or the buffer size needed to retrieve the format description.
GetStatus | Retrieves the status of the sound buffer.
Initialize | Initializes a sound buffer object if it has not yet been initialized.
SetFormat | Sets the format of the primary buffer.

The following table shows which methods are supported for buffer objects obtained from a DirectMusic audiopath. Mix-in buffers accept sends from other buffers, and exist only in audiopath configurations created in DirectMusic Producer. All other buffers in the audiopath are sink-in buffers, which means that they accept data only from the synthesizer sink.

IDirectSoundBuffer8 method | Mix-in | Sink-in
AcquireResources | No | No
GetCaps | Yes | Yes
GetCurrentPosition | No | No
GetFormat | Yes | Yes
GetFrequency | No | No
GetObjectInPath | Yes | Yes
GetPan | Yes | Yes
GetStatus | Yes | Yes
GetVolume | Yes | Yes
Initialize | No | No
Lock | No | No
Play | Yes | No
Restore | No | No
SetCurrentPosition | No | No
SetFormat | No | No
SetFrequency | No | No
SetFX | Yes | Yes
SetPan | Yes | Yes
SetVolume | Yes | Yes
Stop | Yes | No
Unlock | No | No

The LPDIRECTSOUNDBUFFER8 type is defined as a pointer to the IDirectSoundBuffer interface:

typedef struct IDirectSoundBuffer8  *LPDIRECTSOUNDBUFFER8;

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • DirectSound Interfaces


IDirectSoundBuffer8::AcquireResources

The AcquireResources method allocates resources for a buffer that was created with the DSBCAPS_LOCDEFER flag in the DSBUFFERDESC structure.

Syntax

HRESULT AcquireResources(
  DWORD dwFlags,
  DWORD dwEffectsCount,
  LPDWORD pdwResultCodes
);

Parameters

dwFlags

Flags specifying how resources are to be allocated for a buffer created with the DSBCAPS_LOCDEFER flag. For a list of values, see the voice management and voice allocation flags for IDirectSoundBuffer8::Play.

dwEffectsCount

Number of elements in the pdwResultFlags array, or 0 if pdwResultCodes is NULL.

pdwResultCodes

Address of an array of DWORD variables that receives information about the effects associated with the buffer. This array must contain one element for each effect that was assigned to the buffer by IDirectSoundBuffer8::SetFX. For each effect, one of the following values is returned.

Value | Description
DSFXR_LOCHARDWARE | Effect is instantiated in hardware.
DSFXR_LOCSOFTWARE | Effect is instantiated in software.
DSFXR_FAILED | No effect was created because resources weren't available.
DSFXR_PRESENT | The effect is available but was not created because the method failed for some other reason.
DSFXR_UNKNOWN | No effect was created because the effect isn't registered on the system.

This parameter can be NULL if result codes are not wanted.

Return Values

If the method succeeds, the return value is DS_OK or DS_INCOMPLETE.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_INVALIDCALL
DSERR_INVALIDPARAM

Remarks

Normally, buffers created with DSBCAPS_LOCDEFER are not allocated resources until IDirectSoundBuffer8::Play is called. IDirectSoundBuffer8::AcquireResources can be used to allocate resources for a deferred buffer before it is played. By doing so, the application can retrieve information about effects processing and set effect parameters.

If the method fails, check the values in pdwResultCodes to determine which effects caused the failure.

A buffer with acquired resources that is not yet playing is not a candidate for premature termination by the voice management flags passed to the Play method.

Resources that have been acquired by AcquireResources are released when playback is stopped.

If the method is called on a buffer on which it has already been called, the status of the effects is returned but no additional resources are allocated.

The dwEffectsCount parameter to this function must be the same as the one passed in the call to IDirectSoundBuffer8::SetFX.

If an attempt is made to acquire resources for a buffer with the DSBCAPS_LOCHARDWARE flag on a system where hardware acceleration is not available, the method fails with either DSERR_CONTROLUNAVAIL or DSERR_INVALIDCALL, depending on the operating system.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::SetFX
  • DSBCAPS
  • Dynamic Voice Management


IDirectSoundBuffer8::GetCaps

The GetCaps method retrieves the capabilities of the buffer object.

Syntax

HRESULT GetCaps(
  LPDSBCAPS pDSBufferCaps
);

Parameters

pDSBufferCaps

Address of a DSBCAPS structure to contain the capabilities of this sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The DSBCAPS structure contains similar information to the DSBUFFERDESC structure passed to the IDirectSound8::CreateSoundBuffer method, with some additional information. This additional information can include the buffer's location, either in hardware or software, and performance measures.

The flags specified in the dwFlags member of the DSBCAPS structure are the same flags used by the DSBUFFERDESC structure. The only difference is that in the DSBCAPS structure, either DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE will be specified according to the location of the buffer memory. In the DSBUFFERDESC structure, these flags are optional and, depending on which flag is specified, force the buffer to be located in either hardware or software.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSound8::CreateSoundBuffer
  • DSBCAPS
  • DSBUFFERDESC


IDirectSoundBuffer8::GetCurrentPosition

The GetCurrentPosition method retrieves the position of the play and write cursors in the sound buffer.

Syntax

HRESULT GetCurrentPosition(
  LPDWORD pdwCurrentPlayCursor,
  LPDWORD pdwCurrentWriteCursor
);

Parameters

pdwCurrentPlayCursor

Address of a variable that receives the offset, in bytes, of the play cursor. This parameter can be NULL if the value is not wanted.

pdwCurrentWriteCursor

Address of a variable that receives the offset, in bytes, of the write cursor. This parameter can be NULL if the value is not wanted.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The write cursor is the point in the buffer ahead of which it is safe to write data to the buffer. Data should not be written to the part of the buffer after the play cursor and before the write cursor.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::SetCurrentPosition
  • Play and Write Cursors


IDirectSoundBuffer8::GetFormat

The GetFormat method retrieves a description of the format of the sound data in the buffer, or the buffer size needed to retrieve the format description.

Syntax

HRESULT GetFormat(
  LPWAVEFORMATEX pwfxFormat,
  DWORD dwSizeAllocated,
  LPDWORD pdwSizeWritten
);

Parameters

pwfxFormat

Address of a WAVEFORMATEX or WAVEFORMATEXTENSIBLE structure that receives a description of the sound data in the buffer. To retrieve the buffer size needed to contain the format description, specify NULL. In this case the variable at pdwSizeWritten receives the size of the structure needed to receive the data.

dwSizeAllocated

Size, in bytes, of the structure at pwfxFormat. If pwfxFormat is not NULL, this value must be equal to or greater than the size of the expected data.

pdwSizeWritten

Address of a variable that receives the number of bytes written to the structure at pwfxFormat. This parameter can be NULL.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The format structure can have a variable length that depends on the format. Before retrieving the format description, the application should query the buffer object for the size of the format by calling this method and specifying NULL for the pwfxFormat parameter. The necessary size of the structure is returned in the pdwSizeWritten parameter. The application can then allocate sufficient memory and call GetFormat again to retrieve the format description.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::SetFormat


IDirectSoundBuffer8::GetFrequency

The GetFrequency method retrieves the frequency, in samples per second, at which the buffer is playing.

Syntax

HRESULT GetFrequency(
  LPDWORD pdwFrequency
);

Parameters

pdwFrequency

Address of a variable that receives the frequency at which the audio buffer is being played, in hertz.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The frequency value for software buffers is in the range of DSBFREQUENCY_MIN to DSBFREQUENCY_MAX, defined in Dsound.h. Hardware buffers can return other values.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::SetFrequency
  • Playback Controls
  • Buffer Control Options


IDirectSoundBuffer8::GetObjectInPath

The GetObjectInPath method retrieves an interface for an effect object associated with the buffer.

Syntax

HRESULT GetObjectInPath(
  REFGUID rguidObject,
  DWORD dwIndex,
  REFGUID rguidInterface,
  LPVOID * ppObject
);

Parameters

rguidObject

Unique class identifier of the object being searched for, such as GUID_DSFX_STANDARD_ECHO. Set this parameter to GUID_All_Objects to search for objects of any class.

dwIndex

Index of the object within objects of that class in the path. See Remarks.

rguidInterface

Unique identifier of the desired interface. See Remarks.

ppObject

Address of a variable that receives the desired interface pointer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_OBJECTNOTFOUND

Remarks

Any DMO that has been set on a buffer by using IDirectSoundBuffer8::SetFX can be retrieved, even it has not been allocated resources.

The following interfaces can be retrieved for the various DMOs supplied with DirectX.

rguidInterface | *ppObject
IID_IDirectSoundFXGargle8 | IDirectSoundFXGargle8
IID_IDirectSoundFXChorus8 | IDirectSoundFXChorus8
IID_IDirectSoundFXFlanger8 | IDirectSoundFXFlanger8
IID_IDirectSoundFXEcho8 | IDirectSoundFXEcho8
IID_IDirectSoundFXDistortion8 | IDirectSoundFXDistortion8
IID_IDirectSoundFXCompressor8 | IDirectSoundFXCompressor8
IID_IDirectSoundFXParamEq8 | IDirectSoundFXParamEq8
IID_IDirectSoundFXWavesReverb8 | IDirectSoundFXWavesReverb8
IID_IDirectSoundFXI3DL2Reverb8 | IDirectSoundFXI3DL2Reverb8

In addition, the following interfaces are available for any of the standard DMOs. For information on these interfaces, see the Help for DirectX Media Objects.

rguidInterface | *ppObject
IID_IMediaObject | IMediaObject
IID_IMediaObjectInPlace | IMediaObjectInPlace
IID_IMediaParams | IMediaParams

Note When the DirectSound API is used to play buffers, parameter curves (envelopes) set by using the IMediaParams interface do not work, because DirectSound does not timestamp the DMO buffers.

The value in dwIndex is the index of the object within the array of effects passed to IDirectSoundBuffer8::SetFX. This is not necessarily the actual position of the object in the effects chain, because some effects might not have been created.

An object is returned solely on the basis of whether it matches rguidObject and dwIndex. It is up to the application to ensure that rguidInterface specifies an interface that can be expected to be found on the object.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundFXChorus8 Interface
  • IDirectSoundFXCompressor8 Interface
  • IDirectSoundFXDistortion8 Interface
  • IDirectSoundFXEcho8 Interface
  • IDirectSoundFXFlanger8 Interface
  • IDirectSoundFXI3DL2Reverb8 Interface
  • IDirectSoundFXParamEq8 Interface
  • DirectSound Effect GUIDs


IDirectSoundBuffer8::GetPan

The GetPan method retrieves the relative volume of the left and right audio channels.

Syntax

HRESULT GetPan(
  LPLONG plPan
);

Parameters

plPan

Address of a variable that receives the relative volume, in hundredths of a decibel.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The returned value is measured in hundredths of a decibel (dB), in the range of DSBPAN_LEFT to DSBPAN_RIGHT. These values are defined in Dsound.h as -10,000 and 10,000 respectively. The value DSBPAN_LEFT means the right channel is effectively silent. The value DSBPAN_RIGHT means the left channel is effectively silent. The neutral value is DSBPAN_CENTER, defined as 0, which means that both channels are at full volume. When one channel is attenuated, the other remains at full volume.

The pan control acts cumulatively with the volume control.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::GetVolume
  • IDirectSoundBuffer8::SetPan
  • IDirectSoundBuffer8::SetVolume
  • Buffer Control Options
  • Playback Controls


IDirectSoundBuffer8::GetStatus

The GetStatus method retrieves the status of the sound buffer.

Syntax

HRESULT GetStatus(
  LPDWORD pdwStatus
);

Parameters

pdwStatus

Address of a variable that receives the status of the sound buffer. The status can be a combination of the following flags:

Value | Description
DSBSTATUS_BUFFERLOST | The buffer is lost and must be restored before it can be played or locked.
DSBSTATUS_LOOPING | The buffer is being looped. If this value is not set, the buffer will stop when it reaches the end of the sound data. This value is returned only in combination with DSBSTATUS_PLAYING.
DSBSTATUS_PLAYING | The buffer is playing. If this value is not set, the buffer is stopped.
DSBSTATUS_LOCSOFTWARE | The buffer is playing in software. Set only for buffers created with the DSBCAPS_LOCDEFER flag.
DSBSTATUS_LOCHARDWARE | The buffer is playing in hardware. Set only for buffers created with the DSBCAPS_LOCDEFER flag.
DSBSTATUS_TERMINATED | The buffer was prematurely terminated by the voice manager and is not playing. Set only for buffers created with the DSBCAPS_LOCDEFER flag.

Remarks

DSBSTATUS_PLAYING is set if the buffer is being heard. Because of latency, a call to IDirectSoundBuffer8::Play or IDirectSoundBuffer8::Stop might not immediately change the status.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundBuffer8 Interface
  • Buffer Management


IDirectSoundBuffer8::GetVolume

The GetVolume method retrieves the attenuation of the sound.

Syntax

HRESULT GetVolume(
  LPLONG plVolume
);

Parameters

plVolume

Address of a variable that receives the attenuation, in hundredths of a decibel.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The return value is between DSBVOLUME_MAX and DSBVOLUME_MIN. These values are defined as 0 and –10,000, respectively. The value DSBVOLUME_MAX represents the original, unadjusted volume of the sound. The value DSBVOLUME_MIN indicates an audio volume attenuated by 100 dB, which, for practical purposes, is silence.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::SetVolume
  • Buffer Control Options
  • Playback Controls


IDirectSoundBuffer8::Initialize

The Initialize method initializes a sound buffer object if it has not yet been initialized.

Syntax

HRESULT Initialize(
  LPDIRECTSOUND pDirectSound,
  LPCDSBUFFERDESC pcDSBufferDesc
);

Parameters

pDirectSound

Address of the device object associated with this buffer.

pcDSBufferDesc

Address of a DSBUFFERDESC structure that contains the values used to initialize this sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values.

Return code
DSERR_INVALIDPARAM
DSERR_ALREADYINITIALIZED

Remarks

Because the IDirectSound8::CreateSoundBuffer method calls Initialize internally, applications do not need to call this method.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSound8::CreateSoundBuffer
  • DSBUFFERDESC


IDirectSoundBuffer8::Lock

The Lock method readies all or part of the buffer for a data write and returns pointers to which data can be written.

Syntax

HRESULT Lock(
  DWORD dwOffset,
  DWORD dwBytes,
  LPVOID * ppvAudioPtr1,
  LPDWORD pdwAudioBytes1,
  LPVOID * ppvAudioPtr2,
  LPDWORD pdwAudioBytes2,
  DWORD dwFlags
);

Parameters

dwOffset

Offset, in bytes, from the start of the buffer to the point where the lock begins. This parameter is ignored if DSBLOCK_FROMWRITECURSOR is specified in the dwFlags parameter.

dwBytes

Size, in bytes, of the portion of the buffer to lock. The buffer is conceptually circular, so this number can exceed the number of bytes between dwOffset and the end of the buffer.

ppvAudioPtr1

Address of a variable that receives a pointer to the first locked part of the buffer.

pdwAudioBytes1

Address of a variable that receives the number of bytes in the block at ppvAudioPtr1. If this value is less than dwBytes, the lock has wrapped and ppvAudioPtr2 points to a second block of data at the beginning of the buffer .

ppvAudioPtr2

Address of a variable that receives a pointer to the second locked part of the capture buffer. If NULL is returned, the ppvAudioPtr1 parameter points to the entire locked portion of the capture buffer.

pdwAudioBytes2

Address of a variable that receives the number of bytes in the block at ppvAudioPtr2. If ppvAudioPtr2 is NULL, this value is zero.

dwFlags

Flags modifying the lock event. The following flags are defined:

Value | Description
DSBLOCK_FROMWRITECURSOR | Start the lock at the write cursor. The dwOffset parameter is ignored.
DSBLOCK_ENTIREBUFFER | Lock the entire buffer. The dwBytes parameter is ignored.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

This method accepts an offset and a byte count, and returns two write pointers and their associated sizes. If the locked portion does not extend to the end of the buffer and wrap to the beginning, the second pointer, ppvAudioBytes2, receives NULL. If the lock does wrap, ppvAudioBytes2 points to the beginning of the buffer.

If the application passes NULL for the ppvAudioPtr2 and pdwAudioBytes2 parameters, the lock extends no further than the end of the buffer and does not wrap.

After writing data to the pointers returned by this method, the application must immediately call IDirectSoundBuffer8::Unlock to notify DirectSound that the data is ready for playback. Failure to do so can cause audio breakup or silence on some sound device configurations.

This method returns write pointers only. The application should not try to read sound data from this pointer, because the data might not be valid. For example, if the buffer is located in on-card memory, the pointer might be an address to a temporary buffer in system memory. When IDirectSoundBuffer8::Unlock is called, the contents of this temporary buffer are transferred to the on-card memory.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::GetCurrentPosition
  • Filling and Playing Static Buffers
  • Using Streaming Buffers


IDirectSoundBuffer8::Play

The Play method causes the sound buffer to play, starting at the play cursor.

Syntax

HRESULT Play(
  DWORD dwReserved1,
  DWORD dwPriority,
  DWORD dwFlags
);

Parameters

dwReserved1

Reserved. Must be 0.

dwPriority

Priority for the sound, used by the voice manager when assigning hardware mixing resources. The lowest priority is 0, and the highest priority is 0xFFFFFFFF. If the buffer was not created with the DSBCAPS_LOCDEFER flag, this value must be 0.

dwFlags

Flags specifying how to play the buffer. The following flags are defined:

Looping flag

Value | Description
DSBPLAY_LOOPING | After the end of the audio buffer is reached, play restarts at the beginning of the buffer. Play continues until explicitly stopped. This flag must be set when playing a primary buffer.

Voice allocation flags

The voice allocation flags are valid only for buffers created with the DSBCAPS_LOCDEFER flag. One of the following flags can be used to force the processing of the sound into hardware or software. If neither DBSPLAY_LOCHARDWARE nor DBSPLAY_LOCSOFTWARE is set, the sound is played in either software or hardware, depending on the availability of resources at the time the method is called. See Remarks.

Value | Description
DSBPLAY_LOCHARDWARE | Play this voice in a hardware buffer only. If the hardware has no available voices and no voice management flags are set, the call to IDirectSoundBuffer8::Play fails. This flag cannot be combined with DSBPLAY_LOCSOFTWARE.
DSBPLAY_LOCSOFTWARE | Play this voice in a software buffer only. This flag cannot be combined with DSBPLAY_LOCHARDWARE or any voice management flag.

Voice management flags

The voice management flags are valid only for buffers created with the DSBCAPS_LOCDEFER flag, and are used for sounds that are to play in hardware. These flags enable hardware resources that are already in use to be yielded to the current sound. Only buffers created with the DSBCAPS_LOCDEFER flag are candidates for premature termination. See Remarks.

Value | Description
DSBPLAY_TERMINATEBY_TIME | If the hardware has no available voices, a currently playing nonlooping buffer will be stopped to make room for the new buffer. The buffer prematurely terminated is the one with the least time left to play.
DSBPLAY_TERMINATEBY_DISTANCE | If the hardware has no available voices, a currently playing buffer will be stopped to make room for the new buffer. The buffer prematurely terminated will be selected from buffers that have the buffer's DSBCAPS_ MUTE3DATMAXDISTANCE flag set and are beyond their maximum distance. If there are no such buffers, the method fails.
DSBPLAY_TERMINATEBY_PRIORITY | If the hardware has no available voices, a currently playing buffer will be stopped to make room for the new buffer. The buffer prematurely terminated will be the one with the lowest priority as set by the dwPriority parameter passed to IDirectSoundBuffer8::Play for the buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

If IDirectSound8::SetCooperativeLevel has not been called, the method returns DS_OK, but no sound will be produced until a cooperative level has been set.

If the application is multithreaded, the thread that plays the buffer must continue to exist as long as the buffer is playing. Buffers created on WDM drivers stop playing when the thread is terminated.

If the buffer specified in the method is already playing, the call to the method succeeds and the buffer continues to play. However, the flags defined in the most recent call supersede flags defined in previous calls.

When called on the primary buffer, this method causes the buffer to start playing to the sound device. If the application has set the DSSCL_WRITEPRIMARY cooperative level, any audio data put in the primary buffer by the application is sent to the sound device. Under any other cooperative level, the primary buffer plays silence if no secondary buffers are playing. Primary buffers must be played with the DSBPLAY_LOOPING flag set.

If the method is called with a voice allocation or voice management flag set on a buffer that was not created with the DSBCAPS_LOCDEFER flag, the call fails with DSERR_INVALIDPARAM.

DSBPLAY_TERMINATEBY_TIME and DSBPLAY_TERMINATEBY_DISTANCE cannot be combined, but either may be combined with DSBPLAY_TERMINATEBY_PRIORITY, in which case the DSBPLAY_TERMINATEBY_TIME or DSBPLAY_TERMINATEBY_DISTANCE flag is used to determine which buffer should be terminated in the event of a priority tie.

The following table shows the behavior of the method under various combinations of the voice allocation and voice management flags when no free hardware voices are available.

 | DSBPLAY_LOCHARDWARE | Neither DSBPLAY_LOCHARDWARE nor DSBPLAY_LOCSOFTWARE | DSBPLAY_LOCSOFTWARE
DSBPLAY_TERMINATEBY_TIME | Sound with least time left to play is terminated and the new sound plays on the released voice. | Sound with least time left to play is terminated and the new sound plays on the released voice. | New sound plays in software.
DSBPLAY_TERMINATEBY_DISTANCE | If any sounds currently playing in hardware are beyond their maximum distance and have the DSBCAPS_MUTE3DATMAXDISTANCE flag set, one of them is terminated and the new sound plays in hardware. Otherwise, the call fails. | If any sounds currently playing in hardware are beyond their maximum distance and have the DSBCAPS_MUTE3DATMAXDISTANCE flag set, one of them is terminated and the new sound plays in hardware. Otherwise, the new sound plays in software. | New sound plays in software.
DSBPLAY_TERMINATEBY_PRIORITY | If the new sound's priority is higher than or equal to that of any sound currently playing in hardware, one of the lowest-priority sounds is terminated and the new sound plays in hardware. Otherwise, the call fails. | If the new sound's priority is higher than or equal to that of any sound currently playing in hardware, one of the lowest-priority sounds is terminated and the new sound plays in hardware. Otherwise, the new sound plays in software. | New sound plays in software.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSound8::SetCooperativeLevel
  • Dynamic Voice Management
  • Filling and Playing Static Buffers
  • Using Streaming Buffers


IDirectSoundBuffer8::Restore

The Restore method restores the memory allocation for a lost sound buffer.

Syntax

HRESULT Restore();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_PRIOLEVELNEEDED

Remarks

If the application does not have the input focus, IDirectSoundBuffer8::Restore might not succeed. For example, if the application with the input focus has the DSSCL_WRITEPRIMARY cooperative level, no other application will be able to restore its buffers. Similarly, an application with the DSSCL_WRITEPRIMARY cooperative level must have the input focus to restore its primary buffer.

After DirectSound restores the buffer memory, the application must rewrite the buffer with valid sound data. DirectSound cannot restore the contents of the memory, only the memory itself.

The application can receive notification that a buffer is lost when it specifies that buffer in a call to the IDirectSoundBuffer8::Lock or IDirectSoundBuffer8::Play method. These methods return DSERR_BUFFERLOST to indicate a lost buffer. The IDirectSoundBuffer8::GetStatus method can also be used to retrieve the status of the sound buffer and test for the DSBSTATUS_BUFFERLOST flag.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::GetStatus
  • IDirectSoundBuffer8::Lock
  • IDirectSoundBuffer8::Play
  • Buffer Management


IDirectSoundBuffer8::SetCurrentPosition

The SetCurrentPosition method sets the position of the play cursor, which is the point at which the next byte of data is read from the buffer.

Syntax

HRESULT SetCurrentPosition(
  DWORD dwNewPosition
);

Parameters

dwNewPosition

Offset of the play cursor, in bytes, from the beginning of the buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

This method cannot be called on the primary buffer.

If the buffer is playing, the cursor immediately moves to the new position and play continues from that point. If it is not playing, playback will begin from the new position the next time the IDirectSoundBuffer8::Play method is called.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::GetCurrentPosition
  • IDirectSoundBuffer8::Play
  • Play and Write Cursors


IDirectSoundBuffer8::SetFormat

The SetFormat method sets the format of the primary buffer. Whenever this application has the input focus, DirectSound will set the primary buffer to the specified format.

Because primary sound buffers do not support the IDirectSoundBuffer8 interface, this method must be called on IDirectSoundBuffer.

On WDM drivers, setting the primary buffer format has no effect. The output format is determined by the kernel mixer. For more information, see DirectSound Driver Models.

Syntax

HRESULT SetFormat(
  LPCWAVEFORMATEX pcfxFormat
);

Parameters

pcfxFormat

Address of a WAVEFORMATEX structure that describes the new format for the primary sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_BADFORMAT
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY
DSERR_PRIOLEVELNEEDED
DSERR_UNSUPPORTED

Remarks

The format of the primary buffer should be set before secondary buffers are created.

The method fails if the application has the DSSCL_NORMAL cooperative level.

If the application is using DirectSound at the DSSCL_WRITEPRIMARY cooperative level, the buffer must be stopped before SetFormat is called. If the format is not supported, the method fails.

If the cooperative level is DSSCL_PRIORITY, DirectSound stops the primary buffer, changes the format, and restarts the buffer. The method succeeds even if the hardware does not support the requested format; DirectSound sets the buffer to the closest supported format. To determine whether this has happened, an application can call the IDirectSoundBuffer8::GetFormat method for the primary buffer and compare the result with the format that was requested with the SetFormat method.

This method is not available for secondary sound buffers. If a new format is required, the application must create a new DirectSoundBuffer object.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::GetFormat


IDirectSoundBuffer8::SetFrequency

The SetFrequency method sets the frequency at which the audio samples are played.

Syntax

HRESULT SetFrequency(
  DWORD dwFrequency
);

Parameters

dwFrequency

Frequency, in hertz (Hz), at which to play the audio samples. A value of DSBFREQUENCY_ORIGINAL resets the frequency to the default value of the buffer format.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

Increasing or decreasing the frequency changes the perceived pitch of the audio data. This method does not affect the format of the buffer.

Before setting the frequency, you should ascertain whether the frequency is supported by checking the dwMinSecondarySampleRate and dwMaxSecondarySampleRate members of the DSCAPS structure for the device. Some operating systems do not support frequencies greater than 100,000 Hz.

This method is not valid for the primary buffer.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSound8::CreateSoundBuffer
  • IDirectSound8::GetCaps
  • IDirectSoundBuffer8::GetFrequency
  • IDirectSoundBuffer8::Play
  • IDirectSoundBuffer8::SetFormat
  • Buffer Control Options
  • Playback Controls


IDirectSoundBuffer8::SetFX

The SetFX method enables effects on a buffer.

For this method to succeed, CoInitialize must have been called. This is done automatically in applications that create DirectSound by using IDirectMusicPerformance8::InitAudio. However, applications that create DirectSound by using DirectSoundCreate8 must also call CoInitialize.

The buffer must not be playing or locked.

Syntax

HRESULT SetFX(
  DWORD dwEffectsCount,
  LPDSEFFECTDESC pDSFXDesc,
  LPDWORD pdwResultCodes
);

Parameters

dwEffectsCount

Number of elements in the pDSFXDesc and pdwResultCodes arrays. If this value is 0, pDSFXDesc and pdwResultCodes must both be NULL. Set to 0 to remove all effects from the buffer.

pDSFXDesc

Address of an array of DSEFFECTDESC structures, of size dwEffectsCount, that specifies the effects wanted on the buffer. Must be NULL if dwEffectsCount is 0.

pdwResultCodes

Address of an array of DWORD elements, of size dwEffectsCount. Each element receives one of the following values indicating the result of the attempt to create the corresponding effect in the pDSFXDesc array.

Value | Description
DSFXR_LOCHARDWARE | Effect is instantiated in hardware.
DSFXR_LOCSOFTWARE | Effect is instantiated in software.
DSFXR_UNALLOCATED | Effect has not yet been assigned to hardware or software. This value is returned if the buffer was created with the DSBCAPS_LOCDEFER flag in DSBUFFERDESC.
DSFXR_FAILED | No effect was created because resources weren't available.
DSFXR_PRESENT | Effect is available but was not created because one of the other effects requested could not be created. If any of the effects requested cannot be created, none of them are, and the call fails.
DSFXR_UNKNOWN | Effect is not registered on the system, and the method failed as a result.

This parameter must be NULL if dwEffectsCount is 0, or can be NULL if results are not wanted.

Return Values

If the method succeeds, the return value is DS_OK or DS_INCOMPLETE.

If the method fails, the return value may be one of the following error values:

Return code
CO_E_NOTINITIALIZED
DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_INVALIDCALL
DSERR_NOINTERFACE
DSERR_PRIOLEVELNEEDED

In addition, the method can return an error value from DMO methods, including IMediaObject::SetInputType and IMediaObject::SetOutputType. See the DirectShow documentation for possible error values.

Remarks

If the method fails, the value for each effect in pdwResultCodes is either DSFXF_PRESENT or DSFXR_UNKNOWN. Check these values to determine which effects caused the failure.

For the method to succeed, the buffer must have been created with the DSBCAPS_CTRLFX flag and must not be playing or locked.

If the method returns DSERR_NOINTERFACE or another COM error, check the result code array for DSFXR_PRESENT or DSFXR_UNKNOWN to ascertain which effect caused the error. If the method returns DSERR_INVALIDPARAM, check the result codes for DSFXR_FAILED to see which effects failed to acquire resources.

If the buffer is part of a DirectMusic audiopath, the audiopath must be inactive.

An effect must be set on a buffer before the effect interface can be obtained. To obtain the effect interface, use IDirectSoundBuffer8::GetObjectInPath.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::AcquireResources
  • DSBCAPS
  • Buffer Control Options
  • Setting Effects on Buffers


IDirectSoundBuffer8::SetPan

The SetPan method sets the relative volume of the left and right channels.

Syntax

HRESULT SetPan(
  LONG lPan
);

Parameters

lPan

Relative volume between the left and right channels.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The returned value is measured in hundredths of a decibel (dB), in the range of DSBPAN_LEFT to DSBPAN_RIGHT. These values are defined in Dsound.h as -10,000 and 10,000 respectively. The value DSBPAN_LEFT means the right channel is attenuated by 100 dB and is effectively silent. The value DSBPAN_RIGHT means the left channel is silent. The neutral value is DSBPAN_CENTER, defined as 0, which means that both channels are at full volume. When one channel is attenuated, the other remains at full volume.

The pan control acts cumulatively with the volume control.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::GetPan
  • IDirectSoundBuffer8::GetVolume
  • IDirectSoundBuffer8::SetVolume
  • Buffer Control Options
  • Playback Controls


IDirectSoundBuffer8::SetVolume

The SetVolume method sets the attenuation of the sound.

Syntax

HRESULT SetVolume(
  LONG lVolume
);

Parameters

lVolume

Attenuation, in hundredths of a decibel (dB).

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

Allowable values are between DSBVOLUME_MAX (no attenuation) and DSBVOLUME_MIN (silence). These values are defined in Dsound.h as 0 and –10,000 respectively. The value DSBVOLUME_MAX represents the original, unadjusted volume of the stream. The value DSBVOLUME_MIN indicates an audio volume attenuated by 100 dB, which, for all practical purposes, is silence. DirectSound does not support amplification.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::GetPan
  • IDirectSoundBuffer8::GetVolume
  • IDirectSoundBuffer8::SetPan
  • Buffer Control Options
  • Playback Controls


IDirectSoundBuffer8::Stop

The Stop method causes the sound buffer to stop playing.

Syntax

HRESULT Stop();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_PRIOLEVELNEEDED

Remarks

For secondary sound buffers, IDirectSoundBuffer8::Stop sets the play cursor to the sample that follows the last sample played. This means that when the IDirectSoundBuffer8::Play method is next called on the buffer, it will continue playing where it left off.

For the primary buffer, if an application has the DSSCL_WRITEPRIMARY level, this method will stop the buffer and reset the play cursor to 0 (the beginning of the buffer). This is necessary because the primary buffers on most sound cards can play only from the beginning of the buffer.

However, if IDirectSoundBuffer8::Stop is called on a primary buffer and the application has a cooperative level other than DSSCL_WRITEPRIMARY, this method simply reverses the effects of IDirectSoundBuffer8::Play. It configures the primary buffer to stop if no secondary buffers are playing. If other buffers are playing in this or other applications, the primary buffer will not actually stop until they are stopped. This method is useful because playing the primary buffer consumes processing overhead even if the buffer is playing sound data with the amplitude of 0 decibels.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::Play


IDirectSoundBuffer8::Unlock

The Unlock method releases a locked sound buffer.

Syntax

HRESULT Unlock(
  LPVOID pvAudioPtr1,
  DWORD dwAudioBytes1,
  LPVOID pvAudioPtr2,
  DWORD dwAudioBytes2
);

Parameters

pvAudioPtr1

Address of the value retrieved in the ppvAudioPtr1 parameter of the IDirectSoundBuffer8::Lock method.

dwAudioBytes1

Number of bytes written to the portion of the buffer at pvAudioPtr1. See Remarks.

pvAudioPtr2

Address of the value retrieved in the ppvAudioPtr2 parameter of the IDirectSoundBuffer8::Lock method.

dwAudioBytes2

Number of bytes written to the portion of the buffer at pvAudioPtr2. See Remarks.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

An application must pass both pointers, pvAudioPtr1 and pvAudioPtr2, returned by the IDirectSoundBuffer8::Lock method to ensure the correct pairing of IDirectSoundBuffer8::Lock and IDirectSoundBuffer8::Unlock. The second pointer is needed even if nothing was written to the second pointer.

The values in dwAudioBytes1 and dwAudioBytes2 must specify the number of bytes actually written to each part of the buffer, which might be less than the size of the lock. DirectSound uses these values to determine how much data to commit to the device.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundBuffer8 Interface
  • IDirectSoundBuffer8::GetCurrentPosition
  • IDirectSoundBuffer8::Lock
  • Filling and Playing Static Buffers
  • Using Streaming Buffers


IDirectSoundCapture8 Interface

The IDirectSoundCapture8 interface is used to create sound capture buffers.

The interface is obtained by using the DirectSoundCaptureCreate8 or DirectSoundFullDuplexCreate8 functions, or by using CoCreateInstance or CoCreateInstanceEx to create an object of class CLSID_DirectSoundCapture8.

IDirectSoundCapture8 is a define for IDirectSoundCapture. The two interface names are interchangeable. However, objects supporting this interface can have different functionality, depending on their class. For more information, see DirectSoundCaptureCreate8 and IDirectSoundCapture8::CreateCaptureBuffer.

In addition to the methods inherited from IUnknown, the IDirectSoundCapture8 interface exposes the following methods.

Method | Description
CreateCaptureBuffer | Creates a buffer for capturing waveform audio.
GetCaps | Retrieves the capabilities of the capture device.
Initialize | Initializes a capture device object created by using CoCreateInstance.

The LPDIRECTSOUNDCAPTURE type is defined as a pointer to the IDirectSoundCapture interface:

typedef struct IDirectSoundCapture *LPDIRECTSOUNDCAPTURE;

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • DirectSound Interfaces
  • Creating the Capture Device Object


IDirectSoundCapture8::CreateCaptureBuffer

The CreateCaptureBuffer method creates a buffer for capturing waveform audio.

Syntax

HRESULT CreateCaptureBuffer(
  LPCDSCBUFFERDESC pcDSCBufferDesc,
  LPDIRECTSOUNDCAPTUREBUFFER * ppDSCBuffer,
  LPUNKNOWN pUnkOuter
);

Parameters

pcDSCBufferDesc

Pointer to a DSCBUFFERDESC structure containing values for the capture buffer being created.

ppDSCBuffer

Address of a variable that receives an IDirectSoundCaptureBuffer interface pointer. Use QueryInterface to obtain IDirectSoundCaptureBuffer8. See Remarks.

pUnkOuter

Address of the controlling object's IUnknown interface for COM aggregation. Must be NULL.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values.

Return code
DSERR_INVALIDPARAM
DSERR_BADFORMAT
DSERR_GENERIC
DSERR_NODRIVER
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED

Remarks

On Microsoft Windows 98 and Windows 2000, each capture device supports a single buffer.

The IDirectSoundCaptureBuffer8 interface is supported only on buffers created by an object of class CLSID_DirectSoundCapture8. If the IDirectSoundCapture8 interface was obtained from DirectSoundCaptureCreate8, IDirectSoundCaptureBuffer8 is supported. If IDirectSoundCapture8 was obtained from the earlier DirectSoundCaptureCreate function, only IDirectSoundCaptureBuffer is supported.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundCapture8 Interface
  • Creating a Capture Buffer


IDirectSoundCapture8::GetCaps

The GetCaps method retrieves the capabilities of the capture device.

Syntax

HRESULT GetCaps(
  LPDSCCAPS pDSCCaps
);

Parameters

pDSCCaps

Pointer to a DSCCAPS structure to be receive information about the capture device. When the method is called, the dwSize member must specify the size of the structure in bytes.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_UNSUPPORTED
DSERR_NODRIVER
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundCapture8 Interface
  • Capture Device Capabilities


IDirectSoundCapture8::Initialize

The Initialize method initializes a capture device object created by using CoCreateInstance. Calling this method is not required when the DirectSoundCaptureCreate8 or DirectSoundFullDuplexCreate8 function is used to create the object.

Syntax

HRESULT Initialize(
  LPCGUID pcGuidDevice
);

Parameters

pcGuidDevice

Address of the GUID specifying the sound driver to which the DirectSoundCapture object binds. Use NULL to select the primary sound driver.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_NODRIVER
DSERR_OUTOFMEMORY
DSERR_ALREADYINITIALIZED

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundCapture8 Interface


IDirectSoundCaptureBuffer8 Interface

The IDirectSoundCaptureBuffer8 interface is used to manipulate sound capture buffers.

To obtain the IDirectSoundCaptureBuffer8 interface, call the IDirectSoundCapture8::CreateCaptureBuffer method to obtain IDirectSoundCaptureBuffer, then pass IID_IDirectSoundCaptureBuffer8 to IDirectSoundCaptureBuffer::QueryInterface.

Note IDirectSoundCaptureBuffer8 cannot be obtained if the IDirectSoundCapture8 interface was obtained by using the DirectSoundCaptureCreate function. See DirectSoundCaptureCreate8.

In addition to the methods inherited from IUnknown, the IDirectSoundCaptureBuffer8 interface exposes the following methods, arranged by category.

Capture management

Method | Description
Lock | Locks a portion of the buffer, allowing the application to read or write audio data.
Start | Begins capturing data into the buffer.
Stop | Stops the buffer so that it is no longer capturing data.
Unlock | Unlocks the buffer.

Effects

Method | Description
GetFXStatus | Retrieves the status of capture effects.
GetObjectInPath | Retrieves an interface to an effect object associated with the buffer.

Initialization

Method | Description
Initialize | Initializes a capture buffer object. Not used by applications.

Information

Method | Description
GetCaps | Retrieves the capabilities of the buffer.
GetCurrentPosition | Retrieves the positions of the capture and read cursors in the buffer.
GetFormat | Retrieves the waveform format of the capture buffer.
GetStatus | Retrieves the status of the capture buffer.

The LPDIRECTSOUNDCAPTUREBUFFER8 type is defined as a pointer to the IDirectSoundCaptureBuffer8 interface:

typedef struct IDirectSoundCaptureBuffer8 *LPDIRECTSOUNDCAPTUREBUFFER8;

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • DirectSound Interfaces


IDirectSoundCaptureBuffer8::GetCaps

The GetCaps method retrieves the capabilities of the buffer.

Syntax

HRESULT GetCaps(
  LPDSCBCAPS pDSCBCaps
);

Parameters

pDSCBCaps

Pointer to a DSCBCAPS structure that receives information about the capture buffer. On input, the dwSize member must specify the size of the structure in bytes.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_UNSUPPORTED
DSERR_OUTOFMEMORY

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundCaptureBuffer8 Interface


IDirectSoundCaptureBuffer8::GetCurrentPosition

The GetCurrentPosition method retrieves the positions of the capture and read cursors in the buffer.

The capture cursor is ahead of the read cursor. The data after the read position up to and including the capture position is not necessarily valid data.

Syntax

HRESULT GetCurrentPosition(
  LPDWORD pdwCapturePosition,
  LPDWORD pdwReadPosition
);

Parameters

pdwCapturePosition

Address of a variable that receives the offset from the start of the buffer, in bytes, of the capture cursor. The parameter can be NULL if this value is not wanted.

pdwReadPosition

Address of a variable that receives the offset from the start of the buffer, in bytes, of the read cursor.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_NODRIVER
DSERR_OUTOFMEMORY

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundCaptureBuffer8 Interface
  • Capture Buffer Information


IDirectSoundCaptureBuffer8::GetFormat

The GetFormat method retrieves the waveform format of the capture buffer.

Syntax

HRESULT GetFormat(
  LPWAVEFORMATEX pwfxFormat,
  DWORD dwSizeAllocated,
  LPDWORD pdwSizeWritten
);

Parameters

pwfxFormat

Address of a WAVEFORMATEX structure that receives a description of the sound data in the capture buffer. To retrieve the buffer size needed to contain the format description, specify NULL.; in this case, the DWORD pointed to by the pdwSizeWritten parameter receives the size of the structure needed to receive complete format information.

dwSizeAllocated

Size, in bytes, of the WAVEFORMATEX structure. DirectSoundCapture writes, at most, dwSizeAllocated bytes to the structure.

pdwSizeWritten

Address of a variable that receives the number of bytes written to the WAVEFORMATEX structure; or, if pwfxFormat is NULL, the size of the WAVEFORMATEX structure that would be necessary to receive the information. This parameter can be NULL if the value is not wanted.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundCaptureBuffer8 Interface
  • Capture Buffer Information


IDirectSoundCaptureBuffer8::GetFXStatus

The GetFXStatus method retrieves the status of capture effects.

Syntax

HRESULT GetFXStatus(
  DWORD dwFXCount,
  LPDWORD pdwFXStatus
);

Parameters

dwFXCount

Number of elements in the pdwFXStatus array.

pdwFXStatus

Address of an array of DWORD variables that receive the status of each effect. This should contain the same number of elements as the array passed in the dwFXCount member of the DSCBUFFERDESC structure passed to DirectSoundFullDuplexCreate8 or IDirectSoundCapture8::CreateCaptureBuffer. The possible values returned in the array are as follows:

Value | Description
DSCFXR_LOCHARDWARE | Effect is instantiated in hardware.
DSCFXR_LOCSOFTWARE | Effect is instantiated in software.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundCaptureBuffer8 Interface
  • Capture Buffer Effects


IDirectSoundCaptureBuffer8::GetObjectInPath

The GetObjectInPath method retrieves an interface to an effect object associated with the buffer.

Syntax

HRESULT GetObjectInPath(
  REFGUID rguidObject,
  DWORD dwIndex,
  REFGUID rguidInterface,
  LPVOID * ppObject
);

Parameters

rguidObject

Value of type REFGUID that specifies the unique class identifier of the object being searched for, such as GUID_DSCFX_CLASS_AEC.

dwIndex

Index of the object within objects of that class in the path. See Remarks.

rguidInterface

Unique identifier of the desired interface, such as IID_IDirectSoundCaptureFXAec8.

ppObject

Address of a variable that receives the desired interface pointer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_OBJECTNOTFOUND

Remarks

The value in dwIndex is the index of the object within the array of effects in the DSCBUFFERDESC structure passed to DirectSoundFullDuplexCreate8 or IDirectSoundCapture8::CreateCaptureBuffer.

An object is returned solely on the basis of whether it matches rguidObject and dwIndex. It is up to the application to ensure that rguidInterface specifies an interface that can be expected to be found on the object.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundCaptureBuffer8 Interface
  • Capture Buffer Effects


IDirectSoundCaptureBuffer8::GetStatus

The GetStatus method retrieves the status of the capture buffer.

Syntax

HRESULT GetStatus(
  LPDWORD pdwStatus
);

Parameters

pdwStatus

Address of a variable that receives the status of the capture buffer. The status can be set to one or more of the following:

Value | Description
DSCBSTATUS_CAPTURING | The buffer is capturing audio data.
DSCBSTATUS_LOOPING | The buffer is looping.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundCaptureBuffer8 Interface
  • Capture Buffer Information


IDirectSoundCaptureBuffer8::Initialize

The Initialize method initializes a capture buffer object. Because the IDirectSoundCapture8::CreateCaptureBuffer method and the DirectSoundFullDuplexCreate8 function call the IDirectSoundCaptureBuffer8::Initialize method internally, this method is not used by applications.

Syntax

HRESULT Initialize(
  LPDIRECTSOUNDCAPTURE pDirectSoundCapture,
  LPCDSCBUFFERDESC pcDSCBufferDesc
);

Parameters

pDirectSoundCapture

Address of the DirectSoundCapture object associated with this DirectSoundCaptureBuffer object.

pcDSCBufferDesc

Address of a DSCBUFFERDESC structure that contains the values used to initialize this sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_ALREADYINITIALIZED

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundCaptureBuffer8 Interface


IDirectSoundCaptureBuffer8::Lock

The Lock method locks a portion of the buffer. Locking the buffer returns pointers into the buffer, allowing the application to read or write audio data into memory.

Syntax

HRESULT Lock(
  DWORD dwOffset,
  DWORD dwBytes,
  LPVOID *ppvAudioPtr1,
  LPDWORD pdwAudioBytes1,
  LPVOID *ppvAudioPtr2,
  LPDWORD pdwAudioBytes2,
  DWORD dwFlags
);

Parameters

dwOffset

Offset, in bytes, from the start of the buffer to the point where the lock begins.

dwBytes

Size, in bytes, of the portion of the buffer to lock. Because the buffer is conceptually circular, this number can exceed the number of bytes between dwOffset and the end of the buffer.

ppvAudioPtr1

Address of a variable that receives a pointer to the first locked part of the buffer.

pdwAudioBytes1

Address of a variable that receives the number of bytes in the block at ppvAudioPtr1. If this value is less than dwBytes, the lock has wrapped and ppvAudioPtr2 points to a second block of data at the beginning of the buffer.

ppvAudioPtr2

Address of a variable that receives a pointer to the second locked part of the capture buffer. If NULL is returned, the ppvAudioPtr1 parameter points to the entire locked portion of the capture buffer.

pdwAudioBytes2

Address of a variable that receives the number of bytes in the block at ppvAudioPtr2. If ppvAudioPtr2 is NULL, this value is zero.

dwFlags

Flags modifying the lock event. This value can be zero or the following flag:

Value | Description
DSCBLOCK_ENTIREBUFFER | Ignore dwBytes and lock the entire capture buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following values:

Return code
DSERR_INVALIDPARAM
DSERR_INVALIDCALL

Remarks

This method accepts an offset and a byte count, and returns two read pointers and their associated sizes. If the locked portion does not extend to the end of the buffer and wrap to the beginning, the second pointer, ppvAudioBytes2, receives NULL. If the lock does wrap, ppvAudioBytes2 points to the beginning of the buffer.

If the application passes NULL for the ppvAudioPtr2 and pdwAudioBytes2 parameters, the lock extends no further than the end of the buffer and does not wrap.

The application should read data from the pointers returned by this method and then immediately call IDirectSoundCaptureBuffer8::Unlock. The sound buffer should not remain locked while it is running; if it does, the capture cursor will reach the locked bytes and audio problems may result.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundCaptureBuffer8 Interface
  • Using the Capture Buffer


IDirectSoundCaptureBuffer8::Start

The Start method begins capturing data into the buffer. If the buffer is already capturing, the method has no effect.

Syntax

HRESULT Start(
  DWORD dwFlags
);

Parameters

dwFlags

Flags that specify the behavior of the buffer when capturing sound data. The following flag is defined:

Value | Description
DSCBSTART_LOOPING | After the end of the buffer is reached, capture restarts at the beginning and continues until explicitly stopped.

Remarks

If the buffer is already capturing, a call to this method using a different value in dwFlags might not change the value returned by IDirectSoundCaptureBuffer8::GetStatus.

If the application is multithreaded, the thread that starts the buffer must continue to exist as long as the buffer is capturing. Buffers created on WDM drivers stop capturing when the thread is terminated.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_NODRIVER
DSERR_OUTOFMEMORY

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundCaptureBuffer8 Interface
  • Using the Capture Buffer


IDirectSoundCaptureBuffer8::Stop

The Stop method stops the buffer so that it is no longer capturing data. If the buffer is not capturing, the method has no effect.

Syntax

HRESULT Stop();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_NODRIVER
DSERR_OUTOFMEMORY

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundCaptureBuffer8 Interface
  • Using the Capture Buffer


IDirectSoundCaptureBuffer8::Unlock

The Unlock method unlocks the buffer.

Syntax

HRESULT Unlock(
  LPVOID pvAudioPtr1,
  DWORD dwAudioBytes1,
  LPVOID pvAudioPtr2,
  DWORD dwAudioBytes2
);

Parameters

pvAudioPtr1

Address of the value retrieved in the ppvAudioPtr1 parameter of the IDirectSoundCaptureBuffer8::Lock method.

dwAudioBytes1

Number of bytes read from the pvAudioPtr1 parameter. See Remarks.

pvAudioPtr2

Address of the value retrieved in the ppvAudioPtr2 parameter of the IDirectSoundCaptureBuffer8::Lock method.

dwAudioBytes2

Number of bytes read from the pvAudioPtr2 parameter. See Remarks.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following values:

Return code
DSERR_INVALIDPARAM
DSERR_INVALIDCALL

Remarks

An application must pass both pointers, pvAudioPtr1 and pvAudioPtr2, returned by the IDirectSoundCaptureBuffer8::Lock method to ensure the correct pairing of IDirectSoundCaptureBuffer8::Lock and IDirectSoundCaptureBuffer8::Unlock. The second pointer is needed even if zero bytes were written to the second pointer.

The values in dwAudioBytes1 and dwAudioBytes2 must specify the number of bytes actually read from each part of the buffer, which might be less than the size of the lock. DirectSound uses these values to determine how much data to transfer from the device.

Make sure that the capture buffer does not remain locked for long periods of time.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundCaptureBuffer8 Interface
  • Using the Capture Buffer


IDirectSoundCaptureFXAec8 Interface

The IDirectSoundCaptureFXAec8 interface is used to set and retrieve parameters on a capture buffer that supports acoustic echo cancellation. This interface requires Microsoft® Windows® XP or later operating systems.

IDirectSoundCaptureFXAec8 is a define for IDirectSoundCaptureFXAec. The interface names are interchangeable.

This interface is obtained by calling IDirectSoundCaptureBuffer8::GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundCaptureFXAec8 interface exposes the following methods.

Method | Description
GetAllParameters | Retrieves the acoustic echo cancellation parameters of a buffer.
GetStatus | Retrieves the status of the effect.
Reset | Resets the effect to its initial state.
SetAllParameters | Sets the acoustic echo cancellation parameters of a buffer.

The LPDIRECTSOUNDCAPTUREFXAEC8 type is defined as a pointer to the IDirectSoundCaptureFXAec8 interface:

typedef struct IDirectSoundCaptureFXAec8 *LPDIRECTSOUNDCAPTUREFXAEC8;

Requirements

Header: Dsound.h
Library: Dsdmo.dll

Operating System: Requires Microsoft Windows XP or later.

See Also

  • DirectSound Interfaces
  • Capture Buffer Effects


IDirectSoundCaptureFXAec8::GetAllParameters

The GetAllParameters method retrieves the acoustic echo cancellation parameters of a buffer.

Syntax

HRESULT GetAllParameters(
  LPDSCFXAec pDscFxAec
);

Parameters

pDscFxAec

Address of a DSCFXAec structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following values.

Return code
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

Operating System: Requires Microsoft Windows XP or later.

See Also

  • IDirectSoundCaptureFXAec8 Interface
  • Capture Buffer Effects


IDirectSoundCaptureFXAec8::GetStatus

The IDirectSoundCaptureFXAec8::GetStatus method retrieves the status of the effect.

Syntax

HRESULT GetStatus(
  PDWORD pdwStatus
);

Parameters

pdwStatus

Address of a DWORD variable to receive the status. The following flags are defined. See Remarks.

Constant | Value
DSCFX_AEC_STATUS_HISTORY_UNINITIALIZED | 0x0
DSCFX_AEC_STATUS_HISTORY_CONTINUOUSLY_CONVERGED | 0x1
DSCFX_AEC_STATUS_HISTORY_PREVIOUSLY_DIVERGED | 0x2
DSCFX_AEC_STATUS_CURRENTLY_CONVERGED | 0x8

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following values.

Return code
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY

Remarks

The three least significant bits in *pdwStatus describe the convergence history; that is, the success of the effect in canceling the echo. The convergence history can be used by the application to determine if the algorithm has converged and remained in the converged state since it started processing data.

Initially, the AEC algorithm sets the three lower bits to 0 for the uninitialized state (DSCFX_AEC_STATUS_HISTORY_UNINITIALIZED). When the AEC algorithm has converged, the convergence history is switched to the DSCFX_AEC_STATUS_HISTORY_CONTINUOUSLY_CONVERGED state. If the AEC algorithm ever loses convergence, the convergence history is then transitioned to the DSCFX_AEC_STATUS_HISTORY_PREVIOUSLY_DIVERGED state. A transition from DSCFX_AEC_STATUS_HISTORY_UNINITIALIZED to DSCFX_AEC_STATUS_HISTORY_PREVIOUSLY_DIVERGED is also possible. The convergence history remains in the DSCFX_AEC_STATUS_HISTORY_PREVIOUSLY_DIVERGED state until the algorithm is reset or timely data is no longer arriving on the capture or render stream.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

Operating System: Requires Microsoft Windows XP or later.

See Also

  • IDirectSoundCaptureFXAec8 Interface
  • Capture Buffer Effects


IDirectSoundCaptureFXAec8::Reset

The IDirectSoundCaptureFXAec8::Reset method resets the effect to its initial state.

Syntax

HRESULT Reset();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_OUTOFMEMORY.

Remarks

Applications should not reset an effect except when necessary because it has entered an incorrect state. This might be done in response to user input. An effect must not be reset arbitrarily at startup, because another application might be using the same effect.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

Operating System: Requires Microsoft Windows XP or later.

See Also

  • IDirectSoundCaptureFXAec8 Interface
  • Capture Buffer Effects


IDirectSoundCaptureFXAec8::SetAllParameters

The SetAllParameters method sets the acoustic echo cancellation parameters of a buffer.

Syntax

HRESULT SetAllParameters(
  LPCDSCFXAec  pcDscFxAec
);

Parameters

pcDscFxAec

Address of a DSCFXAec structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following values.

Return code
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY

Requirements

Header: Dsound.h
Library: Dsdmo.dll

Operating System: Requires Microsoft Windows XP or later.

See Also

  • IDirectSoundCaptureFXAec8 Interface
  • Capture Buffer Effects


IDirectSoundCaptureFXNoiseSuppress8 Interface

The IDirectSoundCaptureFXNoiseSuppress8 interface is used to set and retrieve parameters on a capture buffer that supports noise suppression. This interface requires Microsoft Windows XP or later.

IDirectSoundCaptureFXNoiseSuppress8 is a define for IDirectSoundCaptureFXNoiseSuppress. The interface names are interchangeable.

This interface is obtained by calling IDirectSoundCaptureBuffer8::GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundCaptureFXNoiseSuppress8 interface exposes the following methods.

Method | Description
GetAllParameters | Retrieves the noise suppression parameters of a buffer.
Reset | Resets the effect to its initial state.
SetAllParameters | Sets the noise suppression parameters of a buffer.

The LPDIRECTSOUNDNOISESUPPRESS8 type is defined as a pointer to the IDirectSoundNoiseSuppress8 interface:

typedef struct IDirectSoundCaptureFXNoiseSuppress8  *LPDIRECTSOUNDCAPTUREFXNOISESUPPRESS8;

Requirements

Header: Dsound.h
Library: Dsdmo.dll

Operating System: Requires Microsoft Windows XP or later.

See Also

  • DirectSound Interfaces
  • Capture Buffer Effects


IDirectSoundCaptureFXNoiseSuppress8::GetAllParameters

The GetAllParameters method retrieves the noise suppression parameters of a buffer.

Syntax

HRESULT GetAllParameters(
  LPDSCFXNoiseSuppress pDsFxNoiseSuppress
);

Parameters

pDscFxNoiseSuppress

Address of a DSCFXNoiseSuppress structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following values:

Return code
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY

Requirements

Header: Dsound.h
Library: Dsdmo.dll

Operating System: Requires Microsoft Windows XP or later.

See Also

  • IDirectSoundCaptureFXNoiseSuppress8 Interface
  • Capture Buffer Effects


IDirectSoundCaptureFXNoiseSuppress8::Reset

The IDirectSoundCaptureFXNoiseSuppress8::Reset method resets the effect to its initial state.

Syntax

HRESULT Reset();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_OUTOFMEMORY.

Remarks

Applications should not reset an effect except when necessary because it has entered an incorrect state. This might be done in response to user input. An effect must not be reset arbitrarily at startup, because another application might be using the same effect.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

Operating System: Requires Microsoft Windows XP or later.

See Also

  • IDirectSoundCaptureFXNoiseSuppress8 Interface
  • Capture Buffer Effects


IDirectSoundCaptureFXNoiseSuppress8::SetAllParameters

The SetAllParameters method sets the noise suppression parameters of a buffer.

Syntax

HRESULT SetAllParameters(
  LPCDSCFXNoiseSuppression  pcDscFxNoiseSuppress
);

Parameters

pcDscFxNoiseSuppress

Address of a DSCFXNoiseSuppress structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following values:

Return code
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY

Requirements

Header: Dsound.h
Library: Dsdmo.dll

Operating System: Requires Microsoft Windows XP or later.

See Also

  • IDirectSoundCaptureFXNoiseSuppress8 Interface
  • Capture Buffer Effects


IDirectSoundFullDuplex8 Interface

The IDirectSoundFullDuplex8 interface represents a full-duplex stream.

The interface is obtained by using the DirectSoundFullDuplexCreate8 function. This function initializes DirectSound capture and playback.

The interface can also be obtained by using CoCreateInstance or CoCreateInstanceEx to create an object of class CLSID_DirectSoundFullDuplex8.

Note An object of this type can be created on earlier operating systems by using CoCreateInstance or CoCreateInstanceEx. However, a call to Initialize will fail.

IDirectSoundFullDuplex8 is a define for IDirectSoundFullDuplex. The interface names are interchangeable.

In addition to the methods inherited from IUnknown, the IDirectSoundFullDuplex8 interface exposes the following method.

Method | Description
Initialize | Initializes a full duplex object that was created by using CoCreateInstance.

The LPDIRECTSOUNDFULLDUPLEX type is defined as a pointer to IDirectSoundFullDuplex.

typedef struct IDirectSoundFullDuplex *LPDIRECTSOUNDFULLDUPLEX;

Requirements

Header: Dsound.h
Library: Dsound.dll

Operating System: Requires Microsoft Windows XP or later.

See Also

  • DirectSound Interfaces


IDirectSoundFullDuplex8::Initialize

The Initialize method initializes a full duplex object that was created by using CoCreateInstance.

Syntax

HRESULT Initialize(
  LPCGUID  pCaptureGuid,
  LPCGUID  pRenderGuid,
  LPCDSCBUFFERDESC  lpDscBufferDesc,
  LPCDSBUFFERDESC  lpDsBufferDesc,
  HWND  hWnd,
  DWORD  dwLevel,
  LPLPDIRECTSOUNDCAPTUREBUFFER8  lplpDirectSoundCaptureBuffer8,
  LPLPDIRECTSOUNDBUFFER8  lplpDirectSoundBuffer8
);

Parameters

pCaptureGuid

Address of the GUID that identifies the sound capture device for full duplex input. Must be one of the GUIDs returned by DirectSoundCaptureEnumerate, NULL for the default capture device, or one of the following values.

Value | Description
DSDEVID_DefaultCapture | System-wide default audio capture device.
DSDEVID_DefaultVoiceCapture | Default voice capture device.

pRenderGuid

Address of the GUID that identifies the sound rendering device for full-duplex output. Must be one of the GUIDs returned by DirectSoundEnumerate, NULL for the default rendering device, or one of the following values:

Value | Description
DSDEVID_DefaultPlayback | System-wide default audio playback device.
DSDEVID_DefaultVoicePlayback | Default voice playback device.

lpDscBufferDesc

Address of a DSCBUFFERDESC structure that specifies the characteristics of the capture buffer.

lpDsBufferDesc

Address of a DSBUFFERDESC structure that specifies the characteristics of the render buffer.

hWnd

Handle to the application window.

dwLevel

Cooperative level for the device. For more information, see IDirectSound8::SetCooperativeLevel.

lplpDirectSoundCaptureBuffer8

Address of a variable that receives the IDirectSoundCaptureBuffer8 interface of the capture buffer.

lplpDirectSoundBuffer8

Address of a variable that receives the IDirectSoundBuffer8 interface of the render buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If it fails, the return value may be one of the following values:

Return code
DSERR_ALREADYINITIALIZED
DSERR_BADFORMAT
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_NODRIVER
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED

Requirements

Header: Dsound.h
Library: Dsound.dll

Operating System: Requires Microsoft Windows XP or later.

See Also

  • IDirectSoundFullDuplex8 Interface


IDirectSoundFXChorus8 Interface

The IDirectSoundFXChorus8 interface is used to set and retrieve effect parameters on a buffer that supports chorus.

This interface is obtained by calling IDirectSoundBuffer8::GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundFXChorus8 interface exposes the following methods.

Method | Description
GetAllParameters | Retrieves the chorus parameters of a buffer.
SetAllParameters | Sets the chorus parameters of a buffer.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • DirectSound Interfaces
  • Using Effects


IDirectSoundFXChorus8::GetAllParameters

The GetAllParameters method retrieves the chorus parameters of a buffer.

Syntax

HRESULT GetAllParameters(
  LPDSFXChorus pDsFxChorus
);

Parameters

pDsFxChorus

Address of a DSFXChorus structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • IDirectSoundFXChorus8 Interface
  • Effect Parameters


IDirectSoundFXChorus8::SetAllParameters

The SetAllParameters method sets the chorus parameters of a buffer.

Syntax

HRESULT SetAllParameters(
  LPCDSFXChorus  pcDsFxChorus
);

Parameters

pcDsFxChorus

Address of a DSFXChorus structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • IDirectSoundFXChorus8 Interface
  • Effect Parameters


IDirectSoundFXCompressor8 Interface

The IDirectSoundFXCompressor8 interface is used to set and retrieve effect parameters on a buffer that supports compression.

This interface is obtained by calling IDirectSoundBuffer8::GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundFXCompressor8 interface exposes the following methods.

Method | Description
GetAllParameters | Retrieves the compressor parameters of a buffer.
SetAllParameters | Sets the compressor parameters of a buffer.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • DirectSound Interfaces
  • Using Effects


IDirectSoundFXCompressor8::GetAllParameters

The GetAllParameters method retrieves the compression parameters of a buffer.

Syntax

HRESULT GetAllParameters(
  LPDSFXCompressor pDsFxCompressor
);

Parameters

pDsFxCompressor

Address of a DSFXCompressor structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • IDirectSoundFXCompressor8 Interface
  • Effect Parameters


IDirectSoundFXCompressor8::SetAllParameters

The SetAllParameters method sets the compression parameters of a buffer.

Syntax

HRESULT SetAllParameters(
  LPCDSFXCompressor pcDsFxCompressor
);

Parameters

pcDsFxCompressor

Address of a DSFXCompressor structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • IDirectSoundFXCompressor8 Interface
  • Effect Parameters


IDirectSoundFXDistortion8 Interface

The IDirectSoundFXDistortion8 interface is used to set and retrieve effect parameters on a buffer that supports distortion.

This interface is obtained by calling IDirectSoundBuffer8::GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundFXDistortion8 interface exposes the following methods.

Method | Description
GetAllParameters | Retrieves the distortion parameters of a buffer.
SetAllParameters | Sets the distortion parameters of a buffer.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • DirectSound Interfaces
  • Using Effects


IDirectSoundFXDistortion8::GetAllParameters

The GetAllParameters method retrieves the distortion parameters of a buffer.

Syntax

HRESULT GetAllParameters(
  LPDSFXDistortion  pDsFxDistortion
);

Parameters

pDsFxDistortion

Address of a DSFXDistortion structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • IDirectSoundFXDistortion8 Interface
  • Effect Parameters


IDirectSoundFXDistortion8::SetAllParameters

The SetAllParameters method sets the distortion parameters of a buffer.

Syntax

HRESULT SetAllParameters(
  LPCDSFXDistortion  pcDsFxDistortion
);

Parameters

pcDsFxDistortion

Address of a DSFXDistortion structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK or S_FALSE. See the Remarks for DSFXDistortion.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • IDirectSoundFXDistortion8 Interface
  • Effect Parameters


IDirectSoundFXEcho8 Interface

The IDirectSoundFXEcho8 interface is used to set and retrieve effect parameters on a buffer that supports echo.

This interface is obtained by calling IDirectSoundBuffer8::GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundFXEcho8 interface exposes the following methods.

Method | Description
GetAllParameters | Retrieves the echo parameters of a buffer.
SetAllParameters | Sets the echo parameters of a buffer.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • DirectSound Interfaces
  • Using Effects


IDirectSoundFXEcho8::GetAllParameters

The GetAllParameters method retrieves the echo parameters of a buffer.

Syntax

HRESULT GetAllParameters(
  LPDSFXEcho pDsFxEcho
);

Parameters

pDsFxEcho

Address of a DSFXEcho structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • IDirectSoundFXEcho8 Interface
  • Effect Parameters


IDirectSoundFXEcho8::SetAllParameters

The SetAllParameters method sets the echo parameters of a buffer.

Syntax

HRESULT SetAllParameters(
  LPCDSFXEcho  pcDsFxEcho
);

Parameters

pcDsFxEcho

Address of a DSFXEcho structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • IDirectSoundFXEcho8 Interface
  • Effect Parameters


IDirectSoundFXFlanger8 Interface

The IDirectSoundFXFlanger8 interface is used to set and retrieve effect parameters on a buffer that supports flange.

This interface is obtained by calling IDirectSoundBuffer8::GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundFXFlanger8 interface exposes the following methods.

Method | Description
GetAllParameters | Retrieves the flanger parameters of a buffer.
SetAllParameters | Sets the flanger parameters of a buffer.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • DirectSound Interfaces
  • Using Effects


IDirectSoundFXFlanger8::GetAllParameters

The GetAllParameters method retrieves the flange parameters of a buffer.

Syntax

HRESULT GetAllParameters(
  LPDSFXFlanger  pDsFxFlanger
);

Parameters

pDsFxFlanger

Address of a DSFXFlanger structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • IDirectSoundFXFlanger8 Interface
  • Effect Parameters


IDirectSoundFXFlanger8::SetAllParameters

The SetAllParameters method sets the flange parameters of a buffer.

Syntax

HRESULT SetAllParameters(
  LPCDSFXFlanger pcDsFxFlanger
);

Parameters

pcDsFxFlanger

Address of a DSFXFlanger structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • IDirectSoundFXFlanger8 Interface
  • Effect Parameters


IDirectSoundFXGargle8 Interface

The IDirectSoundFXGargle8 interface is used to set and retrieve effect parameters on a buffer that supports amplitude modulation.

This interface is obtained by calling IDirectSoundBuffer8::GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundFXGargle8 interface exposes the following methods.

Method | Description
GetAllParameters | Retrieves the gargle parameters of a buffer.
SetAllParameters | Sets the gargle parameters of a buffer.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • DirectSound Interfaces
  • Using Effects


IDirectSoundFXGargle8::GetAllParameters

The GetAllParameters method retrieves the amplitude modulation parameters of a buffer.

Syntax

HRESULT GetAllParameters(
  LPDSFXGargle  pDsFxGargle
);

Parameters

pDsFxGargle

Address of a DSFXGargle structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value can be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • IDirectSoundFXGargle8 Interface
  • Effect Parameters


IDirectSoundFXGargle8::SetAllParameters

The SetAllParameters method sets the amplitude modulation parameters of a buffer.

Syntax

HRESULT SetAllParameters(
  LPCDSFXGargle  pcDsFxGargle
);

Parameters

pcDsFxGargle

Address of a DSFXGargle structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value can be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • IDirectSoundFXGargle8 Interface
  • Effect Parameters


IDirectSoundFXI3DL2Reverb8 Interface

The IDirectSoundFXI3DL2Reverb8 interface is used to set and retrieve effect parameters on a buffer that supports I3DL2 (Interactive 3D Audio Level 2) reverberation effects.

This interface is obtained by calling IDirectSoundBuffer8::GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundFXI3DL2Reverb8 interface exposes the following methods.

Parameters

Method | Description
GetAllParameters | Retrieves the I3DL2 environmental reverberation parameters of a buffer.
GetQuality | Retrieves the quality of the environmental reverberation effect.
SetAllParameters | Sets the I3DL2 environmental reverberation parameters of a buffer.
SetQuality | Sets the quality of the environmental reverberation effect.

Presets

Method | Description
GetPreset | Retrieves an identifier for standard reverberation parameters of a buffer.
SetPreset | Sets standard reverberation parameters of a buffer.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • DirectSound Interfaces
  • Environmental Reverberation
  • Using Effects


IDirectSoundFXI3DL2Reverb8::GetAllParameters

The GetAllParameters method retrieves the I3DL2 environmental reverberation parameters of a buffer.

Syntax

HRESULT GetAllParameters(
  LPDSFXI3DL2Reverb pDsFxI3DL2Reverb
);

Parameters

pDsFxI3DL2Reverb

Address of a DSFXI3DL2Reverb structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • IDirectSoundFXI3DL2Reverb8 Interface
  • Effect Parameters
  • Environmental Reverberation


IDirectSoundFXI3DL2Reverb8::GetPreset

The GetPreset method retrieves an identifier for standard reverberation parameters of a buffer.

Syntax

HRESULT GetPreset(
  LPDWORD  pdwPreset
);

Parameters

pdwPreset

Address of a DWORD that receives one of the preset identifiers. For a list of defined values, see IDirectSoundFXI3DL2Reverb8::SetPreset.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_INVALIDCALL

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • IDirectSoundFXI3DL2Reverb8 Interface
  • Environmental Reverberation


IDirectSoundFXI3DL2Reverb8::GetQuality

The GetQuality method retrieves the quality of the environmental reverberation effect.

Syntax

HRESULT GetQuality(
  LONG * plQuality
);

Parameters

plQuality

Address of a LONG variable to receive the quality of the effect.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • IDirectSoundFXI3DL2Reverb8 Interface
  • IDirectSoundFXI3DL2Reverb8::SetQuality
  • Environmental Reverberation


IDirectSoundFXI3DL2Reverb8::SetAllParameters

The SetAllParameters method sets the I3DL2 environmental reverberation parameters of a buffer.

Syntax

HRESULT SetAllParameters(
  LPCDSFXI3DL2Reverb  pcDsFxI3DL2Reverb
);

Parameters

pcDsFxI3DL2Reverb

Address of a DSFXI3DL2Reverb structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • IDirectSoundFXI3DL2Reverb8 Interface
  • Effect Parameters
  • Environmental Reverberation


IDirectSoundFXI3DL2Reverb8::SetPreset

The SetPreset method sets standard reverberation parameters of a buffer.

Syntax

HRESULT SetPreset(
  DWORD  dwPreset
);

Parameters

dwPreset

Value that specifies a preset. The following constants are defined. See Dsound.h for the default parameters associated with each preset.

Value
DSFX_I3DL2_ENVIRONMENT_PRESET_DEFAULT
DSFX_I3DL2_ENVIRONMENT_PRESET_GENERIC
DSFX_I3DL2_ENVIRONMENT_PRESET_PADDEDCELL
DSFX_I3DL2_ENVIRONMENT_PRESET_ROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_BATHROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_LIVINGROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_STONEROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_AUDITORIUM
DSFX_I3DL2_ENVIRONMENT_PRESET_CONCERTHALL
DSFX_I3DL2_ENVIRONMENT_PRESET_CAVE
DSFX_I3DL2_ENVIRONMENT_PRESET_ARENA
DSFX_I3DL2_ENVIRONMENT_PRESET_HANGAR
DSFX_I3DL2_ENVIRONMENT_PRESET_CARPETEDHALLWAY
DSFX_I3DL2_ENVIRONMENT_PRESET_HALLWAY
DSFX_I3DL2_ENVIRONMENT_PRESET_STONECORRIDOR
DSFX_I3DL2_ENVIRONMENT_PRESET_ALLEY
DSFX_I3DL2_ENVIRONMENT_PRESET_FOREST
DSFX_I3DL2_ENVIRONMENT_PRESET_CITY
DSFX_I3DL2_ENVIRONMENT_PRESET_MOUNTAINS
DSFX_I3DL2_ENVIRONMENT_PRESET_QUARRY
DSFX_I3DL2_ENVIRONMENT_PRESET_PLAIN
DSFX_I3DL2_ENVIRONMENT_PRESET_PARKINGLOT
DSFX_I3DL2_ENVIRONMENT_PRESET_SEWERPIPE
DSFX_I3DL2_ENVIRONMENT_PRESET_UNDERWATER
DSFX_I3DL2_ENVIRONMENT_PRESET_SMALLROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_MEDIUMROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_LARGEROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_MEDIUMHALL
DSFX_I3DL2_ENVIRONMENT_PRESET_LARGEHALL
DSFX_I3DL2_ENVIRONMENT_PRESET_PLATE

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • IDirectSoundFXI3DL2Reverb8 Interface
  • Effect Parameters
  • Environmental Reverberation


IDirectSoundFXI3DL2Reverb8::SetQuality

The SetQuality method sets the quality of the environmental reverberation effect. Higher values produce better quality at the expense of processing time.

Syntax

HRESULT SetQuality(
  LONG lQuality
);

Parameters

lQuality

Quality of the effect, in the range from DSFX_I3DL2REVERB_QUALITY_MIN to DSFX_I3DL2REVERB_QUALITY_MAX. The default value is 2.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • IDirectSoundFXI3DL2Reverb8 Interface
  • IDirectSoundFXI3DL2Reverb8::GetQuality
  • Effect Parameters
  • Environmental Reverberation


IDirectSoundFXParamEq8 Interface

The IDirectSoundFXParamEq8 interface is used to set and retrieve effect parameters on a buffer that supports parametric equalizer effects.

In addition to the methods inherited from IUnknown, the IDirectSoundFXParamEq8 interface exposes the following methods.

Method | Description
GetAllParameters | Retrieves the parametric equalizer parameters of a buffer.
SetAllParameters | Sets the parametric equalizer parameters of a buffer.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • DirectSound Interfaces
  • Using Effects


IDirectSoundFXParamEq8::GetAllParameters

The GetAllParameters method retrieves the parametric equalizer parameters of a buffer.

Syntax

HRESULT GetAllParameters(
  LPDSFXParamEq pDsFxParamEq
);

Parameters

pDsFxParamEq

Address of a DSFXParamEq structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • IDirectSoundFXParamEq8 Interface
  • Effect Parameters


IDirectSoundFXParamEq8::SetAllParameters

The SetAllParameters method sets the parametric equalizer parameters of a buffer.

Syntax

HRESULT SetAllParameters(
  LPCDSFXParamEq  pcDsFxParamEq
);

Parameters

pcDsFxParamEq

Address of a DSFXParamEq structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK or S_FALSE. See the Remarks for DSFXParamEq.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • IDirectSoundFXParamEq8 Interface
  • Effect Parameters


IDirectSoundFXWavesReverb8 Interface

The IDirectSoundFXWavesReverb8 interface is used to set and retrieve effect parameters on a buffer that supports Waves reverberation.

This interface is obtained by calling IDirectSoundBuffer8::GetObjectInPath on the buffer that supports the effect.

In addition to the methods inherited from IUnknown, the IDirectSoundFXWavesReverb8 interface exposes the following methods.

Method | Description
GetAllParameters | Retrieves the Waves reverb parameters of a buffer.
SetAllParameters | Sets the Waves reverb equalizer parameters of a buffer.

Remarks

The Waves reverberation DMO is based on the Waves MaxxVerb technology, which is licenced to Microsoft.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • DirectSound Interfaces
  • Using Effects


IDirectSoundFXWavesReverb8::GetAllParameters

The GetAllParameters method retrieves the music reverberation parameters of a buffer.

Syntax

HRESULT GetAllParameters(
  LPDSFXWavesReverb  pDsFXWavesReverb
);

Parameters

pDsFXWavesReverb

Address of a DSFXWavesReverb structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • IDirectSoundFXWavesReverb8 Interface
  • Effect Parameters


IDirectSoundFXWavesReverb8::SetAllParameters

The SetAllParameters method sets the music reverberation parameters of a buffer.

Syntax

HRESULT SetAllParameters(
  LPCDSFXWavesReverb  pcDsFXWavesReverb
);

Parameters

pcDsFXWavesReverb

Address of a DSFXWavesReverb structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsdmo.dll

See Also

  • IDirectSoundFXWavesReverb8 Interface
  • Effect Parameters


IDirectSoundNotify8 Interface

The IDirectSoundNotify8 interface sets up notification events for a playback or capture buffer.

IDirectSoundNotify8 is a define for IDirectSoundNotify. The two interface names are interchangeable.

The interface is obtained by calling the QueryInterface method of an existing interface on a DirectSound buffer object. Secondary buffers support notifications only if they are created with the DSBCAPS_CTRLPOSITIONNOTIFY flag.

In addition to the methods inherited from IUnknown, the IDirectSoundNotify8 interface exposes the following method.

Method | Description
SetNotificationPositions | Sets the notification positions. During capture or playback, whenever the read or play cursor reaches one of the specified offsets, the associated event is signaled.

The LPDIRECTSOUNDNOTIFY type is defined as a pointer to the IDirectSoundNotify interface:

typedef struct IDirectSoundNotify  *LPDIRECTSOUNDNOTIFY;

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • DirectSound Interfaces
  • Play Buffer Notification


IDirectSoundNotify8::SetNotificationPositions

The SetNotificationPositions method sets the notification positions. During capture or playback, whenever the read or play cursor reaches one of the specified offsets, the associated event is signaled.

Syntax

HRESULT SetNotificationPositions(
  DWORD dwPositionNotifies,
  LPCDSBPOSITIONNOTIFY pcPositionNotifies
);

Parameters

dwPositionNotifies

Number of DSBPOSITIONNOTIFY structures.

pcPositionNotifies

Pointer to an array of DSBPOSITIONNOTIFY structures.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

Return code
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY

Remarks

The value DSBPN_OFFSETSTOP can be specified in the dwOffset member to tell DirectSound to signal the associated event when the IDirectSoundBuffer8::Stop or IDirectSoundCaptureBuffer8::Stop method is called or when the end of the buffer has been reached and the playback is not looping. If it is used, this should be the last item in the position-notify array.

If a position-notify array has already been set, the method replaces the previous array.

The buffer must be stopped when this method is called.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IDirectSoundNotify8 Interface


IKsPropertySet Interface

The IKsPropertySet interface allows drivers to provide extended capabilities that can be used without API extensions. DirectSound supports this interface for accessing properties of sound drivers.

The IKsPropertySet interface is part of the WDM KS (Win32® driver model kernel streaming) architecture.

Note The declaration of this interface in Dsound.h is different from that in Ksproxy.h and Strmif.h. If your project includes Ksproxy.h or Strmif.h but you wish to use the DirectSound implementation, be sure to include Dsound.h first. Failing to do so may cause your application to stop responding when a method of IKsPropertySet is called.

To retrieve this interface, call the QueryInterface method of any interface on a DirectSound buffer.

In addition to the methods inherited from IUnknown, the IKsPropertySet interface exposes the following methods.

Method | Description
Get | Retrieves data for an item in a property set.
QuerySupport | Ascertains whether a property in a property set is supported on the port or device.
Set | Sets the value of a property in a property set.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • DirectSound Interfaces
  • Property Sets for DirectSound Buffers


IKsPropertySet::Get

The Get method retrieves data for an item in a property set.

Syntax

HRESULT Get(
  REFGUID rguidPropSet,
  ULONG ulId,
  LPVOID pInstanceData,
  ULONG ulInstanceLength,
  LPVOID pPropertyData,
  ULONG ulDataLength,
  PULONG pulBytesReturned
);

Parameters

rguidPropSet

Reference to (C++) or address of (C) a GUID representing the property set to be accessed.

ulId

Item within the property set to be accessed. Items are indexed from 0 and are always the same for a given property set GUID.

pInstanceData

Instance data for the get call.

ulInstanceLength

Number of bytes pointed to by pInstanceData.

pPropertyData

Data to set for this item.

ulDataLength

Number of bytes pointed to by pPropertyData

pulBytesReturned

Address of a variable that receives the number of bytes written into pPropertyData.

Return Values

Return values are determined by the designer of the property set.

If the method succeeds, the return value may be S_OK.

If it fails, the method may return one E_POINTER.

Remarks

The format of the data in both pInstanceData and pPropertyData is item-specific.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IKsPropertySet Interface
  • Property Sets for DirectSound Buffers


IKsPropertySet::QuerySupport

The QuerySupport method ascertains whether a property in a property set is supported on the port or device.

Syntax

HRESULT QuerySupport(
  REFGUID rguidPropSet,
  ULONG ulId,
  PULONG pulTypeSupport
);

Parameters

rguidPropSet

Reference to (C++) or address of (C) a GUID representing the property set to be queried.

ulId

Item within the property set to be accessed. Items are indexed from 0 and are always the same for a given property set.

pulTypeSupport

Address of a variable that receives information about support for the property. This variable can receive one or both of the following flags. See Remarks.

Value | Description
KSPROPERTY_SUPPORT_GET | The property item may be retrieved.
KSPROPERTY_SUPPORT_SET | The property item may be set.

Return Values

Return values are determined by the designer of the property set.

If the method succeeds, the return value may be S_OK. (See Remarks.)

If it fails, the method may return one of the following error values:

Return code
E_NOTIMPL (See Remarks.)
E_POINTER

Remarks

Whether it is valid to support some properties within the set but not others depends on the definition of the property set. Consult the hardware manufacturer's specification for the property set of interest.

Some implementations may return S_OK when the property is not supported, and others may return E_NOTIMPL. To be sure that a property is supported, check both the return value of the method and the value returned in pulTypeSupport. If S_OK is returned but pulTypeSupport does not contain a valid flag, the property is not supported.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IKsPropertySet Interface
  • Property Sets for DirectSound Buffers


IKsPropertySet::Set

The Set method sets the value of a property in a property set.

Syntax

HRESULT Set(
  REFGUID rguidPropSet,
  ULONG ulId,
  LPVOID pInstanceData,
  ULONG ulInstanceLength,
  LPVOID pPropertyData,
  ULONG ulDataLength
);

Parameters

rguidPropSet

Reference to (C++) or address of (C) a GUID representing the property set to be accessed.

ulId

Item within the property set to be accessed. Items are indexed from 0 and are always the same for a given property set.

pInstanceData

Instance data for the set call. If there are multiple objects within the port that this operation could act on, the instance data specifies which object should be used. No standard property set items at the DirectMusic® API level use instance data; however, vendor-defined extensions are free to use it.

ulInstanceLength

Number of bytes pointed to by pInstanceData.

pPropertyData

Property data to set for this item.

ulDataLength

Number of bytes pointed to by pPropertyData.

Return Values

Return values are determined by the designer of the property set.

If the method succeeds, the return value may be S_OK.

If it fails, the method may return E_POINTER.

Remarks

The format of the data in both pInstanceData and pPropertyData is item-specific.

Requirements

Header: Dsound.h
Library: Dsound.dll

See Also

  • IKsPropertySet Interface
  • Property Sets for DirectSound Buffers


DirectSound Callback Function

This section contains reference information for the following DirectSound callback function.

Function | Description
DSEnumCallback | Application-defined callback function that enumerates the DirectSound drivers.


DSEnumCallback

The DSEnumCallback function is an application-defined callback function that enumerates the DirectSound drivers. The system calls this function in response to the application's call to the DirectSoundEnumerate or DirectSoundCaptureEnumerate function.

Syntax

BOOL CALLBACK DSEnumCallback(
  LPGUID  lpGuid,
  LPCSTR  lpcstrDescription,
  LPCSTR  lpcstrModule,
  LPVOID  lpContext
);

Parameters

lpGuid

Address of the GUID that identifies the device being enumerated, or NULL for the primary device. This value can be passed to the DirectSoundCreate8 or DirectSoundCaptureCreate8 function to create a device object for that driver.

lpcstrDescription

Address of a null-terminated string that provides a textual description of the DirectSound device.

lpcstrModule

Address of a null-terminated string that specifies the module name of the DirectSound driver corresponding to this device.

lpContext

Address of application-defined data. This is the pointer passed to DirectSoundEnumerate or DirectSoundCaptureEnumerate as the lpContext parameter.

Return Values

Returns TRUE to continue enumerating drivers, or FALSE to stop.

Remarks

The memory pointed to by lpGuid, lpcstrDescription, and lpcstrModule is local in scope. If you want to save these values, you must allocate them in global memory.

The primary device is enumerated twice, first with NULL in lpGuid and then with its GUID in that parameter.

Requirements

Header: Dsound.h
Unicode: Implemented in Unicode and ANSI versions.

See Also

  • DirectSoundEnumerate
  • Enumerating Sound Devices
  • Enumerating Capture Devices


DirectSound Functions

This section contains reference information for the following DirectSound and DirectSoundCapture global functions.

Function | Description
DirectSoundCaptureCreate8 | Creates and initializes an object that supports the IDirectSoundCapture8 interface.
DirectSoundCaptureEnumerate | Enumerates the DirectSoundCapture objects installed in the system.
DirectSoundCreate8 | Creates and initializes an object that supports the IDirectSound8 interface.
DirectSoundEnumerate | Enumerates the DirectSound drivers installed in the system.
DirectSoundFullDuplexCreate8 | Creates the DirectSound and DirectSoundCapture objects and returns the IDirectSoundFullDuplex8 interface.
GetDeviceID | Retrieves the unique device identifier of the default playback and capture devices selected by the user.


DirectSoundCaptureCreate8

The DirectSoundCaptureCreate8 function creates and initializes an object that supports the IDirectSoundCapture8 interface.

This function creates an object that supports capture effects. Although the older DirectSoundCaptureCreate function can also be used to obtain the IDirectSoundCapture8 interface, the object created by that function cannot be used to create capture buffers that support the IDirectSoundCaptureBuffer8 interface.

Syntax

HRESULT WINAPI DirectSoundCaptureCreate8(
  LPCGUID lpcGUID,
  LPDIRECTSOUNDCAPTURE8 *lplpDSC,
  LPUNKNOWN pUnkOuter
);

Parameters

lpcGUID

Address of the GUID that identifies the sound capture device. The value of this parameter must be one of the GUIDs returned by DirectSoundCaptureEnumerate, or NULL for the default device, or one of the following values.

Value | Description
DSDEVID_DefaultCapture | System-wide default audio capture device.
DSDEVID_DefaultVoiceCapture | Default voice capture device.

lplpDSC

Address of a variable to receive an IDirectSoundCapture8 interface pointer.

pUnkOuter

Address of the controlling object's IUnknown interface for COM aggregation. Must be NULL, because aggregation is not supported.

Return Values

If the function succeeds, it returns DS_OK. If it fails, the return value may be one of the following values.

Return code
DSERR_ALLOCATED
DSERR_INVALIDPARAM
DSERR_NOAGGREGATION
DSERR_OUTOFMEMORY

Remarks

On sound cards that do not support full duplex, this method will fail and return DSERR_ALLOCATED.

Requirements

Header: Dsound.h
Library: Dsound.lib.
Unicode: Implemented in Unicode and ANSI versions.

See Also

  • Creating the Capture Device Object


DirectSoundCaptureEnumerate

The DirectSoundCaptureEnumerate function enumerates the DirectSoundCapture objects installed in the system.

Syntax

HRESULT WINAPI DirectSoundCaptureEnumerate(
  LPDSENUMCALLBACK  lpDSEnumCallback,
  LPVOID  lpContext
);

Parameters

lpDSEnumCallback

Address of the DSEnumCallback function that will be called for each DirectSoundCapture object installed in the system.

lpContext

Address of the user-defined context passed to the enumeration callback function every time that function is called.

Return Values

If the function succeeds, it returns DS_OK. If it fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsound.lib.
Unicode: Implemented in Unicode and ANSI versions.

See Also

  • Enumerating Capture Devices


DirectSoundCreate8

The DirectSoundCreate8 function creates and initializes an object that supports the IDirectSound8 interface.

Syntax

HRESULT WINAPI DirectSoundCreate8(
  LPCGUID  lpcGuidDevice,
  LPDIRECTSOUND8 * ppDS8,
  LPUNKNOWN  pUnkOuter
);

Parameters

lpcGuidDevice

Address of the GUID that identifies the sound device. The value of this parameter must be one of the GUIDs returned by DirectSoundEnumerate, or NULL for the default device, or one of the following values.

Value | Description
DSDEVID_DefaultPlayback | System-wide default audio playback device. Equivalent to NULL.
DSDEVID_DefaultVoicePlayback | Default voice playback device.

ppDS8

Address of a variable to receive an IDirectSound8 interface pointer.

pUnkOuter

Address of the controlling object's IUnknown interface for COM aggregation. Must be NULL, because aggregation is not supported.

Return Values

If the function succeeds, it returns DS_OK. If it fails, the return value may be one of the following.

Return code
DSERR_ALLOCATED
DSERR_INVALIDPARAM
DSERR_NOAGGREGATION
DSERR_NODRIVER
DSERR_OUTOFMEMORY

Remarks

The application must call the IDirectSound8::SetCooperativeLevel method immediately after creating a device object.

Requirements

Header: Dsound.h
Library: Dsound.lib.
Unicode: Implemented in Unicode and ANSI versions.

See Also

  • IDirectSound8::GetCaps
  • IDirectSound8::SetCooperativeLevel
  • Creating the Device Object


DirectSoundEnumerate

The DirectSoundEnumerate function enumerates the DirectSound drivers installed in the system.

Syntax

HRESULT WINAPI DirectSoundEnumerate(
  LPDSENUMCALLBACK  lpDSEnumCallback,
  LPVOID  lpContext
);

Parameters

lpDSEnumCallback

Address of the DSEnumCallback function that will be called for each device installed in the system.

lpContext

Address of the user-defined context passed to the enumeration callback function every time that function is called.

Return Values

If the function succeeds, it returns DS_OK. If it fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Dsound.h
Library: Dsound.lib.
Unicode: Implemented in Unicode and ANSI versions.

See Also

  • Enumerating Sound Devices


DirectSoundFullDuplexCreate8

The DirectSoundFullDuplexCreate8 function creates the DirectSound and DirectSoundCapture objects and returns the IDirectSoundFullDuplex8 interface. This function requires Microsoft Windows XP. Full duplex can be implemented on other operating systems, but the capture and rendering devices must be created separately.

Syntax

HRESULT WINAPI DirectSoundFullDuplexCreate8(
  LPCGUID  pcGuidCaptureDevice,
  LPCGUID  pcGuidRenderDevice,
  LPCDSCBUFFERDESC  pcDSCBufferDesc,
  LPCDSBUFFERDESC  pcDSBufferDesc,
  HWND  hWnd,
  DWORD  dwLevel,
  LPDIRECTSOUNDFULLDUPLEX*  ppDSFD,
  LPDIRECTSOUNDCAPTUREBUFFER8  *ppDSCBuffer8,
  LPDIRECTSOUNDBUFFER8  *ppDSBuffer8,
  LPUNKNOWN  pUnkOuter
);

Parameters

pcGuidCaptureDevice

Address of the GUID that identifies the sound capture device for full duplex input. Must be one of the GUIDs returned by DirectSoundCaptureEnumerate, or NULL for the default capture device, or one of the following values.

Value | Description
DSDEVID_DefaultCapture | System-wide default audio capture device.
DSDEVID_DefaultVoiceCapture | Default voice capture device.

pcGuidRenderDevice

Address of the GUID that identifies the sound render device for full-duplex output. Must be one of the GUIDs returned by DirectSoundEnumerate, or NULL for the default render device, or one of the following values.

Value | Description
DSDEVID_DefaultPlayback | System-wide default audio playback device.
DSDEVID_DefaultVoicePlayback | Default voice playback device.

pcDSCBufferDesc

Address of a DSCBUFFERDESC structure that specifies the characteristics of the capture buffer.

pcDSBufferDesc

Address of a DSBUFFERDESC structure that specifies the characteristics of the render buffer.

hWnd

Handle to the application window.

dwLevel

Cooperative level for the device. For more information, see IDirectSound8::SetCooperativeLevel.

ppDSFD

Address of a variable that receives the IDirectSoundFullDuplex8 interface pointer.

ppDSCBuffer8

Address of a variable that receives the IDirectSoundCaptureBuffer8 interface of the capture buffer.

ppDSBuffer8

Address of a variable that receives the IDirectSoundBuffer8 interface of the render buffer.

pUnkOuter

Address of the controlling object's IUnknown interface for COM aggregation. Must be NULL, because aggregation is not supported.

Return Values

If the function succeeds, it returns DS_OK. If it fails, the return value may be one of the following.

Return code
DSERR_ALLOCATED
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_NOAGGREGATION
DSERR_NODRIVER
DSERR_OUTOFMEMORY

Requirements

Header: Dsound.h
Library: Dsound.lib.
Unicode: Implemented in Unicode and ANSI versions.

See Also

  • Creating the Capture Device Object
  • Creating the Device Object


GetDeviceID

The GetDeviceID function retrieves the unique device identifier of the default playback and capture devices selected by the user in Control Panel.

Syntax

HRESULT GetDeviceID(
  LPCGUID  pGuidSrc,
  LPGUID  pGuidDest
);

Parameters

pGuidSrc

Address of a variable that specifies a valid device identifier, or the address of one of the following predefined variables.

Value | Description
DSDEVID_DefaultPlayback | System-wide default audio playback device.
DSDEVID_DefaultCapture | System-wide default audio capture device.
DSDEVID_DefaultVoicePlayback | Default voice playback device.
DSDEVID_DefaultVoiceCapture | Default voice capture device.

pGuidDest

Address of a variable that receives the unique identifier of the device.

Return Values

If the function succeeds, it returns DS_OK. If it fails, the return value may be DSERR_INVALIDPARAM.

Remarks

If pGuidSrc points to a valid device identifier, the same value is returned in pGuidDest. If pGuidSrc is one of the listed constants, pGuidDest returns the address of the corresponding device GUID.

Requirements

Header: Dsound.h
Library: Dsound.lib.
Unicode: Implemented in Unicode and ANSI versions.


DirectSound Structures

This section contains reference information for the following structures used with DirectSound.

Structure | Description
D3DVECTOR | Describes a vector.
DS3DBUFFER | Contains all information necessary to uniquely describe the location, orientation, and motion of a 3-D sound buffer.
DS3DLISTENER | Describes the 3-D world parameters and position of the listener.
DSBCAPS | Describes the capabilities of a DirectSound buffer object.
DSBPOSITIONNOTIFY | Describes a notification position.
DSBUFFERDESC | Describes the characteristics of a buffer.
DSCAPS | Describes the capabilities of a device.
DSCBCAPS | Describes the capabilities of a capture buffer.
DSCBUFFERDESC | Describes a capture buffer.
DSCCAPS | Describes the capabilities of a capture device.
DSCEFFECTDESC | Contains parameters for an effect associated with a capture buffer.
DSCFXAec | Contains parameters for acoustic echo cancellation in a capture buffer.
DSCFXNoiseSuppress | Contains parameters for noise suppression in a capture buffer.
DSEFFECTDESC | Describes an effect associated with a buffer.
DSFXI3DL2Reverb | Contains parameters for an I3DL2 (Interactive 3D Audio Level 2) reverberation effect.
DSFXChorus | Contains parameters for a chorus effect.
DSFXCompressor | Contains parameters for a compression effect.
DSFXDistortion | Contains parameters for a distortion effect.
DSFXEcho | Contains parameters for an echo effect.
DSFXFlanger | Contains parameters for a flange effect.
DSFXGargle | Contains parameters for an amplitude modulation effect.
DSFXParamEq | Contains parameters for a parametric equalizer effect.
DSFXWavesReverb | Contains parameters for a Waves reverberation effect.
WAVEFORMATEX | Defines the format of waveform-audio data.
WAVEFORMATEXTENSIBLE | Defines the format of waveform-audio data for formats having more than two channels or higher resolutions than allowed by WAVEFORMATEX.

Note The memory for all DirectX structures must be initialized to 0 before use. In addition, all structures that contain a dwSize member must set the member to the size of the structure, in bytes, before use. The following example performs these tasks on a common structure, DSCAPS:

DSCAPS dscaps;

ZeroMemory(&dscaps, sizeof(dscaps));
dscaps.dwSize = sizeof(dscaps);


D3DVECTOR

The D3DVECTOR structure defines a vector.

Syntax

typedef struct _D3DVECTOR {
    float x;
    float y;
    float z;
} D3DVECTOR;

Members

x, y, z

Values for the axes of the vector.

Requirements

Header: Dsound.h

See Also

  • Coordinates of 3-D Space


DS3DBUFFER

The DS3DBUFFER structure contains all information necessary to uniquely describe the location, orientation, and motion of a 3-D sound buffer. This structure is used with the IDirectSound3DBuffer8::GetAllParameters and IDirectSound3DBuffer8::SetAllParameters methods.

Syntax

typedef struct {
  DWORD      dwSize;
  D3DVECTOR  vPosition;
  D3DVECTOR  vVelocity;
  DWORD      dwInsideConeAngle;
  DWORD      dwOutsideConeAngle;
  D3DVECTOR  vConeOrientation;
  LONG       lConeOutsideVolume;
  D3DVALUE   flMinDistance;
  D3DVALUE   flMaxDistance;
  DWORD      dwMode;
} DS3DBUFFER, *LPDS3DBUFFER;

typedef const DS3DBUFFER *LPCDS3DBUFFER;

Members

dwSize

Size of the structure, in bytes. This member must be initialized before the structure is used.

vPosition

A D3DVECTOR structure that describes the current position of the 3-D sound buffer.

vVelocity

A D3DVECTOR structure that describes the current velocity of the 3-D sound buffer.

dwInsideConeAngle

The angle of the inside sound projection cone.

dwOutsideConeAngle

The angle of the outside sound projection cone.

vConeOrientation

A D3DVECTOR structure that describes the current orientation of this 3-D buffer's sound projection cone.

lConeOutsideVolume

The cone outside volume.

flMinDistance

The minimum distance.

flMaxDistance

The maximum distance.

dwMode

The 3-D sound processing mode to be set. This value must be one of the values shown in the following table.

Value | Description
DS3DMODE_DISABLE | 3-D sound processing is disabled. The sound will appear to originate from the center of the listener's head.
DS3DMODE_HEADRELATIVE | Sound parameters (position, velocity, and orientation) are relative to the listener's parameters. In this mode, the absolute parameters of the sound are updated automatically as the listener's parameters change, so that the relative parameters remain constant. In other words, the sound moves with the listener.
DS3DMODE_NORMAL | Default. The parameters of the sound are relative to world space.

Requirements

Header: Dsound.h

See Also

  • DirectSound 3-D Buffers


DS3DLISTENER

The DS3DLISTENER structure describes the 3-D world parameters and the position of the listener. This structure is used with the IDirectSound3DListener8::GetAllParameters and IDirectSound3DListener8::SetAllParameters methods.

Syntax

typedef struct {
  DWORD      dwSize;
  D3DVECTOR  vPosition;
  D3DVECTOR  vVelocity;
  D3DVECTOR  vOrientFront;
  D3DVECTOR  vOrientTop;
  D3DVALUE   flDistanceFactor;
  D3DVALUE   flRolloffFactor;
  D3DVALUE   flDopplerFactor;
} DS3DLISTENER, *LPDS3DLISTENER;

typedef const DS3DLISTENER *LPCDS3DLISTENER;

Members

dwSize

Size of the structure, in bytes. This member must be initialized before the structure is used.

vPosition

D3DVECTOR structure that describes the listener's position.

vVelocity

D3DVECTOR structure that describes the listener's velocity.

vOrientFront

D3DVECTOR structure that describes the listener's front orientation.

vOrientTop

D3DVECTOR structure that describes the listener's top orientation.

flDistanceFactor

Number of meters in a vector unit.

flRolloffFactor

Ratio of attenuation over distance to that in the real world.

flDopplerFactor

Ratio of Doppler effect to that in the real world.

Requirements

Header: Dsound.h

See Also

  • DirectSound 3-D Listeners


DSBCAPS

The DSBCAPS structure describes the capabilities of a DirectSound buffer object. It is used by the IDirectSoundBuffer8::GetCaps method.

Syntax

typedef struct {
  DWORD  dwSize;
  DWORD  dwFlags;
  DWORD  dwBufferBytes;
  DWORD  dwUnlockTransferRate;
  DWORD  dwPlayCpuOverhead;
} DSBCAPS, *LPDSBCAPS;

typedef const DSBCAPS *LPCDSBCAPS;

Members

dwSize

Size of the structure, in bytes. This member must be initialized before the structure is used.

dwFlags

Flags that specify buffer-object capabilities. Use one or more of the values shown in the following table.

Value | Description
DSBCAPS_CTRL3D | The buffer has 3-D control capability.
DSBCAPS_CTRLFREQUENCY | The buffer has frequency control capability.
DSBCAPS_CTRLFX | The buffer supports effects processing.
DSBCAPS_CTRLPAN | The buffer has pan control capability.
DSBCAPS_CTRLVOLUME | The buffer has volume control capability.
DSBCAPS_CTRLPOSITIONNOTIFY | The buffer has position notification capability. See the Remarks for DSBUFFERDESC.
DSBCAPS_GETCURRENTPOSITION2 | The buffer uses the new behavior of the play cursor when IDirectSoundBuffer8::GetCurrentPosition is called. In the first version of DirectSound, the play cursor was significantly ahead of the actual playing sound on emulated sound cards; it was directly behind the write cursor. Now, if the DSBCAPS_GETCURRENTPOSITION2 flag is specified, the application can get a more accurate play cursor. If this flag is not specified, the old behavior is preserved for compatibility. This flag affects only emulated devices; if a DirectSound driver is present, the play cursor is accurate for DirectSound in all versions of DirectX.
DSBCAPS_GLOBALFOCUS | The buffer is a global sound buffer. With this flag set, an application using DirectSound can continue to play its buffers if the user switches focus to another application, even if the new application uses DirectSound. The one exception is if you switch focus to a DirectSound application that uses the DSSCL_WRITEPRIMARY flag for its cooperative level. In this case, the global sounds from other applications will not be audible.
DSBCAPS_LOCDEFER | The buffer can be assigned to a hardware or software resource at play time, or when IDirectSoundBuffer8::AcquireResources is called.
DSBCAPS_LOCHARDWARE | The buffer uses hardware mixing.
DSBCAPS_LOCSOFTWARE | The buffer is in software memory and uses software mixing.
DSBCAPS_MUTE3DATMAXDISTANCE | The sound is reduced to silence at the maximum distance. The buffer will stop playing when the maximum distance is exceeded, so that processor time is not wasted. Applies only to software buffers.
DSBCAPS_PRIMARYBUFFER | The buffer is a primary buffer.
DSBCAPS_STATIC | The buffer is in on-board hardware memory.
DSBCAPS_STICKYFOCUS | The buffer has sticky focus. If the user switches to another application not using DirectSound, the buffer is still audible. However, if the user switches to another DirectSound application, the buffer is muted.

dwBufferBytes

Size of this buffer, in bytes.

dwUnlockTransferRate

The rate, in kilobytes per second, at which data is transferred to the buffer memory when IDirectSoundBuffer8::Unlock is called. High-performance applications can use this value to determine the time required for IDirectSoundBuffer8::Unlock to execute. For software buffers located in system memory, the rate will be very high because no processing is required. For hardware buffers, the rate might be slower because the buffer might have to be downloaded to the sound card, which might have a limited transfer rate.

dwPlayCpuOverhead

The processing overhead as a percentage of main processor cycles needed to mix this sound buffer. For hardware buffers, this member will be zero because the mixing is performed by the sound device. For software buffers, this member depends on the buffer format and the speed of the system processor.

Remarks

The DSBCAPS structure contains information similar to that found in the DSBUFFERDESC structure passed to the IDirectSound8::CreateSoundBuffer method, with some additional information. Additional information includes the location of the buffer (hardware or software) and some cost measures (such as the time to download the buffer if located in hardware, and the processing overhead to play the buffer if it is mixed in software).

The dwFlags member contains the same flags used by the DSBUFFERDESC structure. The only difference is that in the DSBCAPS structure, either the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flag is specified, according to the location of the buffer. In the DSBUFFERDESC structure, these flags are optional and are used to force the buffer to be located in either hardware or software.

Requirements

Header: Dsound.h

See Also

  • IDirectSound8::CreateSoundBuffer
  • IDirectSoundBuffer8::GetCaps


DSBPOSITIONNOTIFY

The DSBPOSITIONNOTIFY structure describes a notification position. It is used by the IDirectSoundNotify8::SetNotificationPositions method.

Syntax

typedef struct {
  DWORD   dwOffset;
  HANDLE  hEventNotify;
} DSBPOSITIONNOTIFY, *LPDSBPOSITIONNOTIFY;

typedef const DSBPOSITIONNOTIFY *LPCDSBPOSITIONNOTIFY;

Members

dwOffset

Offset from the beginning of the buffer where the notify event is to be triggered, or DSBPN_OFFSETSTOP.

hEventNotify

Handle to the event to be signaled when the offset has been reached.

Remarks

The DSBPN_OFFSETSTOP value in the dwOffset member causes the event to be signaled when playback or capture stops, either because the end of the buffer has been reached (and playback or capture is not looping) or because the application called the IDirectSoundBuffer8::Stop or IDirectSoundCaptureBuffer8::Stop method.

When a playback buffer was created with DSBCAPS_LOCDEFER and DSBCAPS_CTRLPOSITIONNOTIFY along with any voice management flag, it is possible that a sound that has notifications set, but not yet reached, will be terminated by the voice manager. In this case, no event is signaled.

Requirements

Header: Dsound.h

See Also

  • Play Buffer Notification
  • Capture Buffer Notification


DSBUFFERDESC

The DSBUFFERDESC structure describes the characteristics of a new buffer object. It is used by the IDirectSound8::CreateSoundBuffer method and by the DirectSoundFullDuplexCreate8 function.

An earlier version of this structure, DSBUFFERDESC1, is maintained in Dsound.h for compatibility with DirectX 7 and earlier.

Syntax

typedef struct {
  DWORD     dwSize;
  DWORD     dwFlags;
  DWORD     dwBufferBytes;
  DWORD     dwReserved;
  LPWAVEFORMATEX  lpwfxFormat;
  GUID      guid3DAlgorithm;
} DSBUFFERDESC, *LPDSBUFFERDESC;

typedef const DSBUFFERDESC *LPCDSBUFFERDESC;

Members

dwSize

Size of the structure, in bytes. This member must be initialized before the structure is used.

dwFlags

Flags specifying the capabilities of the buffer. The following values are defined.

Value | Description
DSBCAPS_CTRL3D | The buffer has 3-D control capability. Cannot be combined with DSBCAPS_CTRLPAN, and cannot be set for a buffer with a stereo format in lpwfxFormat.
DSBCAPS_CTRLFREQUENCY | The buffer has frequency control capability.
DSBCAPS_CTRLFX | The buffer supports effects processing. The buffer must be large enough to hold at least DSBSIZE_FX_MIN milliseconds of data.
DSBCAPS_CTRLPAN | The buffer has pan control capability. Cannot be combined with DSBCAPS_CTRL3D.
DSBCAPS_CTRLPOSITIONNOTIFY | The buffer has position notification capability. See Remarks.
DSBCAPS_CTRLVOLUME | The buffer has volume control capability.
DSBCAPS_GETCURRENTPOSITION2 | The IDirectSoundBuffer8::GetCurrentPosition method uses the new behavior of the play cursor. In DirectSound in DirectX 1, the play cursor was significantly ahead of the actual playing sound on emulated sound cards; it was directly behind the write cursor. Now, if the DSBCAPS_GETCURRENTPOSITION2 flag is specified, the application can get a more accurate play cursor. If this flag is not specified, the old behavior is preserved for compatibility. Note that this flag affects only emulated sound cards. If a DirectSound driver is present, the play cursor is accurate for DirectSound in all versions of DirectX.
DSBCAPS_GLOBALFOCUS | The buffer is a global sound buffer. With this flag set, an application using DirectSound can continue to play its buffers if the user switches focus to another application, even if the new application uses DirectSound. The one exception is if you switch focus to a DirectSound application that uses the DSSCL_WRITEPRIMARY flag for its cooperative level. In this case, the global sounds from other applications will not be audible.
DSBCAPS_LOCDEFER | The buffer can be assigned to a hardware or software resource at play time. This flag must be set for buffers that use voice management.
DSBCAPS_LOCHARDWARE | The buffer must use hardware mixing, If the device does not support hardware mixing or if the required hardware memory is not available, the call to IDirectSound8::CreateSoundBuffer method will fail. The application must ensure that a mixing channel is available for this buffer; this condition is not guaranteed. If neither this flag nor DSBCAPS_LOCSOFTWARE is specified, the buffer is placed in hardware if resources are available, or in software if hardware resources are not available. Hardware buffers are not supported in 64-bit operating systems.
DSBCAPS_LOCSOFTWARE | The buffer must be in software memory and use software mixing, even if DSBCAPS_STATIC is specified and hardware resources are available.
DSBCAPS_MUTE3DATMAXDISTANCE | The sound is reduced to silence at the maximum distance. The buffer will stop playing when the maximum distance is exceeded, so that processor time is not wasted. Applies only to software buffers.
DSBCAPS_PRIMARYBUFFER | The buffer is a primary buffer. If this value is not specified, a secondary sound buffer is created. Cannot be combined with DSBCAPS_CTRLFX.
DSBCAPS_STATIC | The buffer is placed in on-board hardware memory, if available. No error occurs if such memory is not available. This flag has no effect on cards using the PCI bus. Cannot be combined with DSBCAPS_CTRLFX.
DSBCAPS_STICKYFOCUS | The buffer has sticky focus. If the user switches to another application not using DirectSound, the application's normal buffers are muted, but sticky focus buffers are still audible.

dwBufferBytes

Size of the new buffer, in bytes. This value must be 0 when creating a buffer with the DSBCAPS_PRIMARYBUFFER flag. For secondary buffers, the minimum and maximum sizes allowed are specified by DSBSIZE_MIN and DSBSIZE_MAX, defined in Dsound.h.

dwReserved

Reserved. Must be 0.

lpwfxFormat

Address of a WAVEFORMATEX or WAVEFORMATEXTENSIBLE structure specifying the waveform format for the buffer. This value must be NULL for primary buffers.

guid3DAlgorithm

Unique identifier of the two-speaker virtualization algorithm to be used by DirectSound3D hardware emulation. If DSBCAPS_CTRL3D is not set in dwFlags, this member must be GUID_NULL (DS3DALG_DEFAULT).

The following algorithm identifiers are defined.

Value | Description | Availability
DS3DALG_DEFAULT | DirectSound uses the default algorithm. In most cases this is DS3DALG_NO_VIRTUALIZATION. On WDM drivers, if the user has selected a surround sound speaker configuration in Control Panel, the sound is panned among the available directional speakers. | Applies to software mixing only. Available on WDM or Vxd Drivers.
DS3DALG_NO_VIRTUALIZATION | 3-D output is mapped onto normal left and right stereo panning. At 90 degrees to the left, the sound is coming out of only the left speaker; at 90 degrees to the right, sound is coming out of only the right speaker. The vertical axis is ignored except for scaling of volume due to distance. Doppler shift and volume scaling are still applied, but the 3-D filtering is not performed on this buffer. This is the most efficient software implementation, but provides no virtual 3-D audio effect. When the DS3DALG_NO_VIRTUALIZATION algorithm is specified, HRTF processing will not be done. Because DS3DALG_NO_VIRTUALIZATION uses only normal stereo panning, a buffer created with this algorithm may be accelerated by a 2-D hardware voice if no free 3-D hardware voices are available. | Applies to software mixing only. Available on WDM or Vxd Drivers.
DS3DALG_HRTF_FULL | The 3-D API is processed with the high quality 3-D audio algorithm. This algorithm gives the highest quality 3-D audio effect, but uses more CPU cycles. See Remarks. | Applies to software mixing only. Available on Microsoft Windows 98 Second Edition and later operating systems when using WDM drivers.
DS3DALG_HRTF_LIGHT | The 3-D API is processed with the efficient 3-D audio algorithm. This algorithm gives a good 3-D audio effect, but uses fewer CPU cycles than DS3DALG_HRTF_FULL. | Applies to software mixing only. Available on Windows 98 Second Edition and later operating systems when using WDM drivers.

Remarks

When creating a primary buffer, applications must set the dwBufferBytes member to zero. DirectSound will determine the best buffer size for the particular sound device in use. To determine the size of a created primary buffer, call IDirectSoundBuffer8::GetCaps.

The DSBCAPS_CTRLDEFAULT flag is no longer supported. This flag was defined as DSBCAPS_CTRLPAN | DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLFREQUENCY. By specifying only the flags you need, you cut down on unnecessary resource usage.

On VXD drivers, a sound buffer created with DSBCAPS_CTRLPOSITIONNOTIFY is always a software buffer, because the VXD driver model does not support notifications. With WDM drivers, a notification-enabled buffer can be in hardware, if hardware resources are available.

The DSBCAPS_LOCHARDWARE and DSBCAPS_LOCSOFTWARE flags are optional and mutually exclusive. DSBCAPS_LOCHARDWARE forces the buffer to reside in hardware, meaning that it will be mixed by the sound card. DSBCAPS_LOCSOFTWARE forces the buffer to reside in software, where it is mixed by the CPU. These flags are also defined for the dwFlags member of the DSBCAPS structure.

The 3-D algorithms represent selection of the software emulation layer only—that is, the software algorithm that is used when no hardware is present for acceleration. In order to maximize hardware utilization, DS3DALG_NO_VIRTUALIZATION is treated as a special case. If no free 3-D hardware voices are available, the buffer is then treated as a 2-D buffer, but with 3-D control. Specifically, when a sound buffer is created with DS3DALG_NO_VIRTUALIZATION, or when the buffer is played if the buffer was created with DSBPLAY_LOCDEFER, the following procedure is followed:

  1. If a free hardware 3-D voice is available, that 3-D hardware voice is used.
  2. If no free hardware 3-D voices are available and a 2-D hardware voice is available, that 2-D hardware voice will be used. This is possible because the DS3DALG_NO_VIRTUALIZATION algorithm is a simple stereo pan algorithm
  3. If no free 2-D or 3-D hardware voices are available, the voice will be played in software using the DS3DALG_NO_VIRTUALIZATION algorithm.

If a speaker configuration other than DSSPEAKER_HEADPHONE or DSSPEAKER_STEREO is in effect, the processing will be done as if for a two-speaker configuration.

If a buffer is created using one of the HRTF algorithms, and the HRTF algorithm is not available on the system (for example, a non-WDM system), a success code, DS_NO_VIRTUALIZATION, is returned. The sound buffer created will use DS3DALG_NO_VIRTUALIZATION instead. For this reason, applications should use the SUCCEEDED or FAILED macros rather than checking explicitly for DS_OK when calling CreateSoundBuffer.

Requirements

Header: Dsound.h

See Also

  • DirectSound Buffers
  • Dynamic Voice Management
  • IDirectSound8::CreateSoundBuffer


DSCAPS

The DSCAPS structure describes the capabilities of a device. It is used by the IDirectSound8::GetCaps method.

Syntax

typedef {
  DWORD  dwSize;
  DWORD  dwFlags;
  DWORD  dwMinSecondarySampleRate;
  DWORD  dwMaxSecondarySampleRate;
  DWORD  dwPrimaryBuffers;
  DWORD  dwMaxHwMixingAllBuffers;
  DWORD  dwMaxHwMixingStaticBuffers;
  DWORD  dwMaxHwMixingStreamingBuffers;
  DWORD  dwFreeHwMixingAllBuffers;
  DWORD  dwFreeHwMixingStaticBuffers;
  DWORD  dwFreeHwMixingStreamingBuffers;
  DWORD  dwMaxHw3DAllBuffers;
  DWORD  dwMaxHw3DStaticBuffers;
  DWORD  dwMaxHw3DStreamingBuffers;
  DWORD  dwFreeHw3DAllBuffers;
  DWORD  dwFreeHw3DStaticBuffers;
  DWORD  dwFreeHw3DStreamingBuffers;
  DWORD  dwTotalHwMemBytes;
  DWORD  dwFreeHwMemBytes;
  DWORD  dwMaxContigFreeHwMemBytes;
  DWORD  dwUnlockTransferRateHwBuffers;
  DWORD  dwPlayCpuOverheadSwBuffers;
  DWORD  dwReserved1;
  DWORD  dwReserved2;
} DSCAPS, *LPDSCAPS;

typedef const DSCAPS *LPCDSCAPS;

Members

dwSize

Size of the structure, in bytes. This member must be initialized before the structure is used.

dwFlags

Flags describing device capabilities. Can include the values shown in the following table.

Value | Description
DSCAPS_CERTIFIED | The driver has been tested and certified by Microsoft. This flag is always set for WDM drivers. To test for certification, use IDirectSound8::VerifyCertification.
DSCAPS_CONTINUOUSRATE | The device supports all sample rates between the dwMinSecondarySampleRate and dwMaxSecondarySampleRate member values. Typically, this means that the actual output rate will be within +/- 10 hertz (Hz) of the requested frequency.
DSCAPS_EMULDRIVER | The device does not have a DirectSound driver installed, so it is being emulated through the waveform-audio functions. Performance degradation should be expected.
DSCAPS_PRIMARY16BIT | The device supports a primary buffer with 16-bit samples.
DSCAPS_PRIMARY8BIT | The device supports primary buffers with 8-bit samples.
DSCAPS_PRIMARYMONO | The device supports monophonic primary buffers.
DSCAPS_PRIMARYSTEREO | The device supports stereo primary buffers.
DSCAPS_SECONDARY16BIT | The device supports hardware-mixed secondary sound buffers with 16-bit samples.
DSCAPS_SECONDARY8BIT | The device supports hardware-mixed secondary buffers with 8-bit samples.
DSCAPS_SECONDARYMONO | The device supports hardware-mixed monophonic secondary buffers.
DSCAPS_SECONDARYSTEREO | The device supports hardware-mixed stereo secondary buffers.

dwMinSecondarySampleRate, dwMaxSecondarySampleRate

Minimum and maximum sample rate specifications that are supported by this device's hardware secondary sound buffers.

dwPrimaryBuffers

Number of primary buffers supported. This value will always be 1.

dwMaxHwMixingAllBuffers

Number of buffers that can be mixed in hardware. This member can be less than the sum of dwMaxHwMixingStaticBuffers and dwMaxHwMixingStreamingBuffers. Resource tradeoffs frequently occur.

dwMaxHwMixingStaticBuffers

Maximum number of static buffers.

dwMaxHwMixingStreamingBuffers

Maximum number of streaming sound buffers.

dwFreeHwMixingAllBuffers

Number of unallocated buffers. On WDM drivers, this includes dwFreeHw3DAllBuffers.

dwFreeHwMixingStaticBuffers

Number of unallocated static buffers.

dwFreeHwMixingStreamingBuffers

Number of unallocated streaming buffers.

dwMaxHw3DAllBuffers

Maximum number of 3-D buffers.

dwMaxHw3DStaticBuffers

Maximum number of static 3-D buffers.

dwMaxHw3DStreamingBuffers

Maximum number of streaming 3-D buffers.

dwFreeHw3DAllBuffers

Number of unallocated 3-D buffers.

dwFreeHw3DStaticBuffers

Number of unallocated static 3-D buffers.

dwFreeHw3DStreamingBuffers

Number of unallocated streaming 3-D buffers.

dwTotalHwMemBytes

Size, in bytes, of the amount of memory on the sound card that stores static sound buffers.

dwFreeHwMemBytes

Size, in bytes, of the free memory on the sound card.

dwMaxContigFreeHwMemBytes

Size, in bytes, of the largest contiguous block of free memory on the sound card.

dwUnlockTransferRateHwBuffers

The rate, in kilobytes per second, at which data can be transferred to hardware static sound buffers. This and the number of bytes transferred determines the duration of a call to the IDirectSoundBuffer8::Unlock method.

dwPlayCpuOverheadSwBuffers

The processing overhead, as a percentage of main processor cycles, needed to mix software buffers. This varies according to the bus type, the processor type, and the clock speed.

dwReserved1

Not used.

dwReserved2

Not used.

Remarks

Some audio cards may be unable to report accurately the number of available or free hardware buffers. This can happen, for example, when the card can play more sounds at lower sampling rates than at higher rates. In general, a nonzero value in any of the members relating to number of free hardware buffers signifies that at least one hardware resource of the appropriate type is available.

The unlock transfer rate for software buffers is 0, because the data need not be transferred anywhere. Similarly, the play processing overhead for hardware buffers is 0 because the mixing is done by the sound device.

Requirements

Header: Dsound.h

See Also

  • IDirectSound8::GetCaps


DSCBCAPS

The DSCBCAPS structure describes the capabilities of a capture buffer. It is used by the IDirectSoundCaptureBuffer8::GetCaps method.

Syntax

typedef struct {
  DWORD  dwSize;
  DWORD  dwFlags;
  DWORD  dwBufferBytes;
  DWORD  dwReserved;
} DSCBCAPS, *LPDSCBCAPS;

typedef const DSCBCAPS *LPCDSCBCAPS;

Members

dwSize

Size of the structure, in bytes. This member must be initialized before the structure is used.

dwFlags

Specifies device capabilities. Can be zero or DSCBCAPS_WAVEMAPPED. The Win32 wave mapper will be used for formats not supported by the device.

dwBufferBytes

The size, in bytes, of the capture buffer.

dwReserved

Reserved for future use.

Requirements

Header: Dsound.h


DSCBUFFERDESC

The DSCBUFFERDESC structure describes a capture buffer. It is used by the IDirectSoundCapture8::CreateCaptureBuffer method and by the DirectSoundFullDuplexCreate8 function.

An earlier version of this structure, DSCBUFFERDESC1, is maintained in Dsound.h for compatibility with DirectX 7 and earlier.

Syntax

typedef struct {
  DWORD     dwSize;
  DWORD     dwFlags;
  DWORD     dwBufferBytes;
  DWORD     dwReserved;
  LPWAVEFORMATEX  lpwfxFormat;
  DWORD     dwFXCount;
  LPDSCEFFECTDESC lpDSCFXDesc;
} DSCBUFFERDESC, *LPDSCBUFFERDESC;

typedef const DSCBUFFERDESC *LPCDSCBUFFERDESC;

Members

dwSize

Size of the structure, in bytes. This member must be initialized before the structure is used.

dwFlags

Specifies device capabilities. Can be zero, or one or more of the flags shown in the following table.

Value | Description
DSCBCAPS_CTRLFX | The buffer supports effects. See Remarks.
DSCBCAPS_WAVEMAPPED | The Win32 wave mapper will be used for formats not supported by the device.

dwBufferBytes

Size of capture buffer to create, in bytes.

dwReserved

Reserved for future use.

lpwfxFormat

Pointer to a WAVEFORMATEX structure containing the format in which to capture the data.

dwFXCount

Number of elements in the array pointed to by lpDSCFXDesc. Must be zero unless DSCBCAPS_CTRLFX is present in dwFlags.

lpDSCFXDesc

Address of an array of DSCEFFECTDESC structures that describe effects supported by hardware for the buffer. User-mode DMOs are not supported.

Remarks

The DSCBCAPS_CTRLFX flag is supported only on buffers created by an object of class CLSID_DirectSoundCapture8. If the IDirectSoundCapture8 interface was obtained from the DirectSoundCaptureCreate8 function, this flag is supported; if it was obtained from the earlier DirectSoundCaptureCreate function, it is not supported.

Capture effects require Microsoft® Windows® XP.

Requirements

Header: Dsound.h


DSCCAPS

The DSCCAPS structure describes the capabilities of the capture device. It is used by the IDirectSoundCapture8::GetCaps method.

Syntax

typedef struct {
  DWORD  dwSize;
  DWORD  dwFlags;
  DWORD  dwFormats;
  DWORD  dwChannels;
} DSCCAPS, *LPDSCCAPS;

typedef const DSCCAPS *LPCDSCCAPS;

Members

dwSize

Size of the structure, in bytes. This member must be initialized before the structure is used.

dwFlags

Specifies device capabilities. Can be zero or one or more of the following flags.

Value | Description
DSCCAPS_CERTIFIED | The driver for the device is a certified WDM driver.
DSCCAPS_EMULDRIVER | There is no DirectSoundCapture driver for the device, so the standard waveform audio functions are being used.
DSCCAPS_MULTIPLECAPTURE | Multiple capture objects can be used simultaneously on the capture device.

dwFormats

Standard formats that are supported. These are equivalent to the values in the WAVEINCAPS structure used in the Win32 waveform audio functions, and are defined in MMSystem.h in the Platform SDK.

dwChannels

Number of channels supported by the device, where 1 is mono, 2 is stereo, and so on.

Requirements

Header: Dsound.h


DSCEFFECTDESC

The DSCEFFECTDESC structure contains parameters for an effect associated with a capture buffer.

Syntax

typedef struct _DSCEFFECTDESC {
  DWORD   dwSize;
  DWORD   dwFlags;
  GUID    guidDSCFXClass;
  GUID    guidDSCFXInstance;
  DWORD   dwReserved1;
  DWORD   dwReserved2;
} DSCEFFECTDESC, *LPDSCEFFECTDESC;

typedef const DSCEFFECTDESC *LPCDSCEFFECTDESC;

Members

dwSize

Size of the structure, in bytes.

dwFlags

Flags that specify desired parameters of the effect. When this structure is passed to DirectSoundFullDuplexCreate8, or IDirectSoundCapture8::CreateCaptureBuffer, this member must be one of the values shown in the following table.

Value | Description
DSCFX_LOCHARDWARE | Effect specified by guidDSCFXInstance must be in hardware.
DSCFX_LOCSOFTWARE | Effect specified by guidDSCFXInstance must be in software.

On return, this member can contain one of the values shown in the following table.

Value | Description
DSCFXR_LOCHARDWARE | Effect was created in hardware.
DSCFXR_LOCSOFTWARE | Effect was created in software.

guidDSCFXClass

Value of type GUID that specifies the class identifier of the effect. The following standard identifiers are defined.

Value | Description
GUID_DSCFX_CLASS_AEC | Acoustic echo cancellation.
GUID_DSCFX_CLASS_NS | Noise suppression.

guidDSCFXInstance

Value of type GUID that specifies the unique identifier of the preferred effect. The following standard identifiers are defined.

Value | Description
GUID_DSCFX_MS_AEC | Microsoft acoustic echo cancellation. Available in software only.
GUID_DSCFX_MS_NS | Microsoft noise suppression. Available in software only.
GUID_DSCFX_SYSTEM_AEC | System default acoustic echo cancellation.
GUID_DSCFX_SYSTEM_NS | System default noise suppression.

dwReserved1

Reserved. Must be zero.

dwReserved2

Reserved. Must be zero.

Requirements

Header: Dsound.h


DSCFXAec

The DSCFXAec structure contains parameters for acoustic echo cancellation in a capture buffer.

Structure

typedef struct _DSCFXAec {
  BOOL  fEnable;
  BOOL  fNoiseFill;
  DWORD  dwMode;
} DSCFXAec, *LPDSCFXAec;

typedef const DSCFXAec *LPCDSCFXAec;

Members

fEnable

Boolean value that specifies whether the effect is enabled.

fNoiseFill

Boolean value that specifies whether to enable background comfort noise, which makes the capture signal sound more natural by preventing periods of dead silence. By default, background comfort noise is not enabled.

dwMode

Operation mode. This member contains one of the following values.

Constant | Description
DSCFX_AEC_MODE_PASS_THROUGH | The effect is passing capture and render data through without modifying it.
DSCFX_AEC_MODE_HALF_DUPLEX | The effect is running in half duplex mode. Not presently supported.
DSCFX_AEC_MODE_FULL_DUPLEX | The effect is running in full duplex mode.

Remarks

The dwMode member is ignored when this structure is passed to IDirectSoundCaptureFXAec8::SetAllParameters.

Requirements

Header: Dsound.h

See Also

  • IDirectSoundCaptureFXAec8::GetAllParameters
  • IDirectSoundCaptureFXAec8::SetAllParameters


DSCFXNoiseSuppress

The DSCFXNoiseSuppress structure contains parameters for noise suppression in a capture buffer.

Syntax

typedef struct _DSCFXNoiseSuppress {
  BOOL  fEnable;
} DSCFXNoiseSuppress, *LPDSCFXNoiseSuppress;

typedef const DSCFXNoiseSuppress *LPCDSCFXNoiseSuppress;

Members

fEnable

Boolean value that specifies whether the effect is enabled.

Requirements

Header: Dsound.h

See Also

  • IDirectSoundCaptureFXNoiseSuppress8::GetAllParameters
  • IDirectSoundCaptureFXNoiseSuppress8::SetAllParameters


DSEFFECTDESC

The DSEFFECTDESC structure describes an effect associated with a buffer.

Syntax

typedef struct _DSEFFECTDESC {
  DWORD      dwSize;
  DWORD      dwFlags;
  GUID       guidDSFXClass;
  DWORD_PTR  dwReserved1;
  DWORD_PTR  dwReserved2
} DSEFFECTDESC, *LPDSEFFECTDESC;

typedef const DSEFFECTDESC *LPCDSEFFECTDESC;

Members

dwSize

Size of the structure, in bytes.

dwFlags

Flags. Can be zero or one of the following values.

Value | Description
DSFX_LOCHARDWARE | Effect must be in hardware. If the effect is not available in hardware, IDirectSoundBuffer8::SetFX raises an error. Because DirectX 9.0 does not support hardware acceleration of effects, this flag should not be used.
DSFX_LOCSOFTWARE | Effect must be in software, even if the hardware supports acceleration of guidDSFXClass. If the effect is not available in software, SetFX raises an error. In DirectX 9.0, all effects are in software regardless of whether this flag is set.

guidDSFXClass

Class identifier of the effect. The following standard effect classes are defined.

Value | Description
GUID_DSFX_STANDARD_CHORUS | Chorus
GUID_DSFX_STANDARD_COMPRESSOR | Compressor
GUID_DSFX_STANDARD_DISTORTION | Distortion
GUID_DSFX_STANDARD_ECHO | Echo
GUID_DSFX_STANDARD_FLANGER | Flanger
GUID_DSFX_STANDARD_GARGLE | Gargle
GUID_DSFX_STANDARD_I3DL2REVERB | Interactive 3D Level 2 reverb
GUID_DSFX_STANDARD_PARAMEQ | Parametric equalizer
GUID_DSFX_WAVES_REVERB | Waves reverb

dwReserved1

Reserved for future use.

dwReserved2

Reserved for future use.

Remarks

Custom effects can be implemented as DMOs. Effect DMOs must implement the IMediaObject and IMediaObjectInPlace interfaces.

If dwFlags is zero, the effect is placed in hardware if possible. If the hardware does not support the effect (always the case in DirectX 9.0), software is used. If the effect is not available at all, the call to SetFX fails.

Requirements

Header: Dsound.h

See Also

  • DSBCAPS
  • IDirectSoundBuffer8::SetFX
  • Using Effects


DSFXI3DL2Reverb

The DSFXI3DL2Reverb structure contains parameters for an I3DL2 (Interactive 3D Audio Level 2) reverberation effect.

Syntax

typedef struct _DSFXI3DL2Reverb {
  LONG  lRoom;
  LONG  lRoomHF;
  FLOAT flRoomRolloffFactor;
  FLOAT flDecayTime;
  FLOAT flDecayHFRatio;
  LONG  lReflections;
  FLOAT flReflectionsDelay;
  LONG  lReverb;
  FLOAT flReverbDelay;
  FLOAT flDiffusion;
  FLOAT flDensity;
  FLOAT flHFReference;
} DSFXI3DL2Reverb, *LPDSFXI3DL2Reverb;

typedef const DSFXI3DL2Reverb *LPCDSFXI3DL2Reverb;

Members

lRoom

Attenuation of the room effect, in millibels (mB), in the range from DSFX_I3DL2REVERB_ROOM_MIN to DSFX_I3DL2REVERB_ROOM_MAX. The default value is DSFX_I3DL2REVERB_ROOM_DEFAULT, or -1000 mB.

lRoomHF

Attenuation of the room high-frequency effect, in mB, in the range from DSFX_I3DL2REVERB_ROOMHF_MIN to DSFX_I3DL2REVERB_ROOMHF_MAX. The default value is DSFX_I3DL2REVERB_ROOMHF_DEFAULT, or -100 mB.

flRoomRolloffFactor

Rolloff factor for the reflected signals, in the range from DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR_MIN to DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR_MAX. The default value is DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR_DEFAULT, or 0.0. The rolloff factor for the direct path is controlled by the DirectSound listener.

flDecayTime

Decay time, in seconds, in the range from DSFX_I3DL2REVERB_DECAYTIME_MIN to DSFX_I3DL2REVERB_DECAYTIME_MAX. The default value is DSFX_I3DL2REVERB_DECAYTIME_DEFAULT, or 1.49 second.

flDecayHFRatio

Ratio of the decay time at high frequencies to the decay time at low frequencies, in the range from DSFX_I3DL2REVERB_DECAYHFRATIO_MIN to DSFX_I3DL2REVERB_DECAYHFRATIO_MAX. The default value is DSFX_I3DL2REVERB_DECAYHFRATIO_DEFAULT, or 0.83.

lReflections

Attenuation of early reflections relative to lRoom, in mB, in the range from DSFX_I3DL2REVERB_REFLECTIONS_MIN to DSFX_I3DL2REVERB_REFLECTIONS_MAX. The default value is DSFX_I3DL2REVERB_REFLECTIONS_DEFAULT, or -2602 mB.

flReflectionsDelay

Delay time of the first reflection relative to the direct path, in seconds, in the range from DSFX_I3DL2REVERB_REFLECTIONSDELAY_MIN to DSFX_I3DL2REVERB_REFLECTIONSDELAY_DEFAULT. The default value is 0.007 seconds.

lReverb

Attenuation of late reverberation relative to lRoom, in mB, in the range -from DSFX_I3DL2REVERB_REVERB_MIN to DSFX_I3DL2REVERB_REVERB_MAX. The default value is DSFX_I3DL2REVERB_REVERB_DEFAULT, or 200 mB.

flReverbDelay

Time limit between the early reflections and the late reverberation relative to the time of the first reflection, in seconds, in the range from DSFX_I3DL2REVERB_REVERBDELAY_MIN to DSFX_I3DL2REVERB_REVERBDELAY_MAX. The default value is DSFX_I3DL2REVERB_REVERBDELAY_DEFAULT, or 0.011 seconds.

flDiffusion

Echo density in the late reverberation decay, in percent, in the range from DSFX_I3DL2REVERB_DIFFUSION_MIN to DSFX_I3DL2REVERB_DIFFUSION_MAX. The default value is DSFX_I3DL2REVERB_DIFFUSION_DEFAULT, or 100.0 percent.

flDensity

Modal density in the late reverberation decay, in percent, in the range from DSFX_I3DL2REVERB_DENSITY_MIN to DSFX_I3DL2REVERB_DENSITY_MAX. The default value is DSFX_I3DL2REVERB_DENSITY_DEFAULT, or 100.0 percent.

flHFReference

Reference high frequency, in hertz, in the range from DSFX_I3DL2REVERB_HFREFERENCE_MIN to DSFX_I3DL2REVERB_HFREFERENCE_MAX. The default value is DSFX_I3DL2REVERB_HFREFERENCE_DEFAULT, or 5000.0 Hz.

Requirements

Header: Dsound.h

See Also

  • IDirectSoundFXI3DL2Reverb8 Interface


DSFXChorus

The DSFXChorus structure contains parameters for a chorus effect.

Syntax

typedef struct _DSFXChorus {
  FLOAT   fWetDryMix;
  FLOAT   fDepth;
  FLOAT   fFeedback;
  FLOAT   fFrequency;
  LONG    lWaveform;
  FLOAT   fDelay;
  LONG    lPhase;
} DSFXChorus, *LPDSFXChorus;

typedef const DSFXChorus *LPCDSFXChorus;

Members

fWetDryMix

Ratio of wet (processed) signal to dry (unprocessed) signal. Must be in the range from DSFXCHORUS_WETDRYMIX_MIN through DSFXCHORUS_WETDRYMIX_MAX (all wet). The default value is 50.

fDepth

Percentage by which the delay time is modulated by the low-frequency oscillator, in hundredths of a percentage point. Must be in the range from DSFXCHORUS_DEPTH_MIN through DSFXCHORUS_DEPTH_MAX. The default value is 10.

fFeedback

Percentage of output signal to feed back into the effect's input, in the range from DSFXCHORUS_FEEDBACK_MIN to DSFXCHORUS_FEEDBACK_MAX. The default value is 25.

fFrequency

Frequency of the LFO, in the range from DSFXCHORUS_FREQUENCY_MIN to DSFXCHORUS_FREQUENCY_MAX. The default value is 1.1.

lWaveform

Waveform shape of the LFO. Defined values are DSFXCHORUS_WAVE_TRIANGLE and DSFXCHORUS_WAVE_SIN. By default, the waveform is a sine.

fDelay

Number of milliseconds the input is delayed before it is played back, in the range from DSFXCHORUS_DELAY_MIN to DSFXCHORUS_DELAY_MAX. The default value is 16 ms.

lPhase

Phase differential between left and right LFOs, in the range from DSFXCHORUS_PHASE_MIN through DSFXCHORUS_PHASE_MAX. Possible values are defined as follows.

Value
DSFXCHORUS_PHASE_NEG_180
DSFXCHORUS_PHASE_NEG_90
DSFXCHORUS_PHASE_ZERO
DSFXCHORUS_PHASE_90
DSFXCHORUS_PHASE_180

The default value is DSFXCHORUS_PHASE_90.

Requirements

Header: Dsound.h

See Also

  • Chorus
  • IDirectSoundFXChorus8 Interface


DSFXCompressor

The DSFXCompressor structure contains parameters for a compression effect.

Syntax

typedef struct _DSFXCompressor {
  FLOAT  fGain;
  FLOAT  fAttack;
  FLOAT  fRelease;
  FLOAT  fThreshold;
  FLOAT  fRatio;
  FLOAT  fPredelay;
} DSFXCompressor, *LPDSFXCompressor;

typedef const DSFXCompressor *LPCDSFXCompressor;

Members

fGain

Output gain of signal after compression, in the range from DSFXCOMPRESSOR_GAIN_MIN to DSFXCOMPRESSOR_GAIN_MAX. The default value is 0 dB.

fAttack

Time before compression reaches its full value, in the range from DSFXCOMPRESSOR_ATTACK_MIN to DSFXCOMPRESSOR_ATTACK_MAX. The default value is 10 ms.

fRelease

Speed at which compression is stopped after input drops below fThreshold, in the range from DSFXCOMPRESSOR_RELEASE_MIN to DSFXCOMPRESSOR_RELEASE_MAX. The default value is 200 ms.

fThreshold

Point at which compression begins, in decibels, in the range from DSFXCOMPRESSOR_THRESHOLD_MIN to DSFXCOMPRESSOR_THRESHOLD_MAX. The default value is -20 dB.

fRatio

Compression ratio, in the range from DSFXCOMPRESSOR_RATIO_MIN to DSFXCOMPRESSOR_RATIO_MAX. The default value is 3, which means 3:1 compression.

fPredelay

Time after lThreshold is reached before attack phase is started, in milliseconds, in the range from DSFXCOMPRESSOR_PREDELAY_MIN to DSFXCOMPRESSOR_PREDELAY_MAX. The default value is 4 ms.

Requirements

Header: Dsound.h

See Also

  • Compression
  • IDirectSoundFXCompressor8 Interface


DSFXDistortion

The DSFXDistortion structure contains parameters for a distortion effect.

Syntax

typedef struct _DSFXDistortion {
  FLOAT  fGain;
  FLOAT  fEdge;
  FLOAT  fPostEQCenterFrequency;
  FLOAT  fPostEQBandwidth;
  FLOAT  fPreLowpassCutoff;
} DSFXDistortion, *LPDSFXDistortion;

typedef const DSFXDistortion *LPCDSFXDistortion;

Members

fGain

Amount of signal change after distortion, in the range from DSFXDISTORTION_GAIN_MIN through DSFXDISTORTION_GAIN_MAX. The default value is -18 dB.

fEdge

Percentage of distortion intensity, in the range in the range from DSFXDISTORTION_EDGE_MIN through DSFXDISTORTION_EDGE_MAX. The default value is 15 percent.

fPostEQCenterFrequency

Center frequency of harmonic content addition, in the range from DSFXDISTORTION_POSTEQCENTERFREQUENCY_MIN through DSFXDISTORTION_POSTEQCENTERFREQUENCY_MAX. The default value is 2400 Hz.

fPostEQBandwidth

Width of frequency band that determines range of harmonic content addition, in the range from DSFXDISTORTION_POSTEQBANDWIDTH_MIN through DSFXDISTORTION_POSTEQBANDWIDTH_MAX. The default value is 2400 Hz.

fPreLowpassCutoff

Filter cutoff for high-frequency harmonics attenuation, in the range from DSFXDISTORTION_PRELOWPASSCUTOFF_MIN through DSFXDISTORTION_PRELOWPASSCUTOFF_MAX. The default value is 8000 Hz.

Remarks

The values in fPostEQBandwidth, fPostEQCenterFrequency, and fPreLowpassCutoff cannot exceed one-third of the frequency of the buffer. If an attempt is made to set a value greater than this, but within the range of accepted values, the parameter is set to the nearest supported value and S_FALSE is returned by IDirectSoundFXDistortion8::SetAllParameters.

Requirements

Header: Dsound.h

See Also

  • Distortion
  • IDirectSoundFXDistortion8 Interface


DSFXEcho

The DSFXEcho structure contains parameters for an echo effect.

Syntax

typedef struct _DSFXEcho {
  FLOAT  fWetDryMix;
  FLOAT  fFeedback;
  FLOAT  fLeftDelay;
  FLOAT  fRightDelay;
  LONG   lPanDelay;
} DSFXEcho, *LPDSFXEcho;

typedef const DSFXEcho *LPCDSFXEcho;

Members

fWetDryMix

Ratio of wet (processed) signal to dry (unprocessed) signal. Must be in the range from DSFXECHO_WETDRYMIX_MIN through DSFXECHO_WETDRYMIX_MAX (all wet). The default value is 50.

fFeedback

Percentage of output fed back into input, in the range from DSFXECHO_FEEDBACK_MIN through DSFXECHO_FEEDBACK_MAX. The default value is 50.

fLeftDelay

Delay for left channel, in milliseconds, in the range from DSFXECHO_LEFTDELAY_MIN through DSFXECHO_LEFTDELAY_MAX. The default value is 500 ms.

fRightDelay

Delay for right channel, in milliseconds, in the range from DSFXECHO_RIGHTDELAY_MIN through DSFXECHO_RIGHTDELAY_MAX. The default value is 500 ms.

lPanDelay

Value that specifies whether to swap left and right delays with each successive echo. The default value is zero, meaning no swap. Possible values are defined as DSFXECHO_PANDELAY_MIN (equivalent to FALSE) and DSFXECHO_PANDELAY_MAX (equivalent to TRUE).

Requirements

Header: Dsound.h

See Also

  • Echo
  • IDirectSoundFXEcho8 Interface


DSFXFlanger

The DSFXFlanger structure contains parameters for a flange effect.

Syntax

typedef struct _DSFXFlanger {
  FLOAT  fWetDryMix;
  FLOAT  fDepth;
  FLOAT  fFeedback;
  FLOAT  fFrequency;
  LONG   lWaveform;
  FLOAT  fDelay;
  LONG   lPhase;
} DSFXFlanger, *LPDSFXFlanger;

typedef const DSFXFlanger *LPCDSFXFlanger;

Members

fWetDryMix

Ratio of wet (processed) signal to dry (unprocessed) signal. Must be in the range from DSFXFLANGER_WETDRYMIX_MIN through DSFXFLANGER_WETDRYMIX_MAX (all wet). The default value is 50.

fDepth

Percentage by which the delay time is modulated by the low-frequency oscillator (LFO), in hundredths of a percentage point. Must be in the range from DSFXFLANGER_DEPTH_MIN through DSFXFLANGER_DEPTH_MAX. The default value is 100.

fFeedback

Percentage of output signal to feed back into the effect's input, in the range from DSFXFLANGER_FEEDBACK_MIN to DSFXFLANGER_FEEDBACK_MAX. The default value is -50.

fFrequency

Frequency of the LFO, in the range from DSFXFLANGER_FREQUENCY_MIN to DSFXFLANGER_FREQUENCY_MAX. The default value is 0.25.

lWaveform

Waveform shape of the LFO. By default, the waveform is a sine. Possible values are defined in the following table.

Value | Description
DSFXFLANGER_WAVE_TRIANGLE | Triangle.
DSFXFLANGER_WAVE_SIN | Sine.

fDelay

Number of milliseconds the input is delayed before it is played back, in the range from DSFXFLANGER_DELAY_MIN to DSFXFLANGER_DELAY_MAX. The default value is 2 ms.

lPhase

Phase differential between left and right LFOs, in the range from DSFXFLANGER_PHASE_MIN through DSFXFLANGER_PHASE_MAX. Possible values are defined in the following table.

Value
DSFXFLANGER_PHASE_NEG_180
DSFXFLANGER_PHASE_NEG_90
DSFXFLANGER_PHASE_ZERO
DSFXFLANGER_PHASE_90
DSFXFLANGER_PHASE_180

The default value is DSFXFLANGER_PHASE_ZERO.

Requirements

Header: Dsound.h

See Also

  • Flange
  • IDirectSoundFXFlanger8 Interface


DSFXGargle

The DSFXGargle structure contains parameters for an amplitude modulation effect.

Syntax

typedef struct _DSFXGargle {
  DWORD  dwRateHz;
  DWORD  dwWaveShape;
} DSFXGargle, *LPDSFXGargle;

typedef const DSFXGargle *LPCDSFXGargle;

Members

dwRateHz

Rate of modulation, in Hertz. Must be in the range from DSFXGARGLE_RATEHZ_MIN through DSFXGARGLE_RATEHZ_MAX. The default value is 20.

dwWaveShape

Shape of the modulation waveform. The following values are defined.

Value | Description
DSFXGARGLE_WAVE_TRIANGLE | Triangular waveform.
DSFXGARGLE_WAVE_SQUARE | Square waveform.

The default value is DSFXGARGLE_WAVE_TRIANGLE.

Requirements

Header: Dsound.h

See Also

  • Gargle
  • IDirectSoundFXGargle8 Interface


DSFXParamEq

The DSFXParamEq structure contains parameters for a parametric equalizer effect.

Syntax

typedef struct _DSFXParamEq {
  FLOAT  fCenter;
  FLOAT  fBandwidth;
  FLOAT  fGain;
} DSFXParamEq, *LPDSFXParamEq;

Members

fCenter

Center frequency, in hertz, in the range from DSFXPARAMEQ_CENTER_MIN to DSFXPARAMEQ_CENTER_MAX. The default value is 8000.

fBandwidth

Bandwidth, in semitones, in the range from DSFXPARAMEQ_BANDWIDTH_MIN to DSFXPARAMEQ_BANDWIDTH_MAX. The default value is 12.

fGain

Gain, in the range from DSFXPARAMEQ_GAIN_MIN to DSFXPARAMEQ_GAIN_MAX. The default value is 0.

Remarks

The value in fCenter cannot exceed one-third of the sampling frequency of the buffer. If an attempt is made to set a value greater than this, but within the range of accepted values, the parameter is set to the nearest supported value and S_FALSE is returned by IDirectSoundFXParamEq8::SetAllParameters.

Requirements

Header: Dsound.h

See Also

  • IDirectSoundFXParamEq8 Interface
  • Parametric Equalizer


DSFXWavesReverb

The DSFXWavesReverb structure contains parameters for a Waves reverberation effect.

Syntax

typedef struct _DSFXWavesReverb {
  FLOAT  fInGain;
  FLOAT  fReverbMix;
  FLOAT  fReverbTime;
  FLOAT  fHighFreqRTRatio;
} DSFXWavesReverb, *LPDSFXWavesReverb;

typedef const DSFXWavesReverb *LPCDSFXWavesReverb;

Members

fInGain

Input gain of signal, in decibels (dB), in the range from DSFX_WAVESREVERB_INGAIN_MIN through DSFX_WAVESREVERB_INGAIN_MAX. The default value is DSFX_WAVESREVERB_INGAIN_DEFAULT, or 0 dB.

fReverbMix

Reverb mix, in dB, in the range from DSFX_WAVESREVERB_REVERBMIX_MIN through DSFX_WAVESREVERB_REVERBMIX_MAX. The default value is DSFX_WAVESREVERB_REVERBMIX_DEFAULT, or 0 dB.

fReverbTime

Reverb time, in milliseconds, in the range from DSFX_WAVESREVERB_REVERBTIME_MIN through DSFX_WAVESREVERB_REVERBTIME_MAX. The default value is DSFX_WAVESREVERB_REVERBTIME_DEFAULT, or 1000.

fHighFreqRTRatio

High-frequency reverb time ratio, in the range from DSFX_WAVESREVERB_HIGHFREQRTRATIO_MIN through DSFX_WAVESREVERB_HIGHFREQRTRATIO_MAX. The default value is DSFX_WAVESREVERB_HIGHFREQRTRATIO_DEFAULT, or 0.001.

Requirements

Header: Dsound.h

See Also

  • IDirectSoundFXWavesReverb8 Interface


WAVEFORMATEX

The WAVEFORMATEX structure defines the format of waveform-audio data. Only format information common to all waveform-audio data formats is included in this structure. For formats that require additional information, this structure is included as the first member in another structure, along with the additional information.

This structure is part of the Platform SDK and is not declared in Dsound.h. It is documented here for convenience.

Syntax

typedef struct {
  WORD  wFormatTag;
  WORD  nChannels;
  DWORD nSamplesPerSec;
  DWORD nAvgBytesPerSec;
  WORD  nBlockAlign;
  WORD  wBitsPerSample;
  WORD  cbSize;
} WAVEFORMATEX;

Members

wFormatTag

Waveform-audio format type. Format tags are registered with Microsoft Corporation for many compression algorithms. A complete list of format tags can be found in the Mmreg.h header file. For one- or two-channel PCM data, this value should be WAVE_FORMAT_PCM.

nChannels

Number of channels in the waveform-audio data. Monaural data uses one channel and stereo data uses two channels.

nSamplesPerSec

Sample rate, in samples per second (hertz). If wFormatTag is WAVE_FORMAT_PCM, then common values for nSamplesPerSec are 8.0 kHz, 11.025 kHz, 22.05 kHz, and 44.1 kHz. For non-PCM formats, this member must be computed according to the manufacturer's specification of the format tag.

nAvgBytesPerSec

Required average data-transfer rate, in bytes per second, for the format tag. If wFormatTag is WAVE_FORMAT_PCM, nAvgBytesPerSec should be equal to the product of nSamplesPerSec and nBlockAlign. For non-PCM formats, this member must be computed according to the manufacturer's specification of the format tag.

nBlockAlign

Block alignment, in bytes. The block alignment is the minimum atomic unit of data for the wFormatTag format type. If wFormatTag is WAVE_FORMAT_PCM or WAVE_FORMAT_EXTENSIBLE, nBlockAlign must be equal to the product of nChannels and wBitsPerSample divided by 8 (bits per byte). For non-PCM formats, this member must be computed according to the manufacturer's specification of the format tag.

Software must process a multiple of nBlockAlign bytes of data at a time. Data written to and read from a device must always start at the beginning of a block. For example, it is illegal to start playback of PCM data in the middle of a sample (that is, on a non-block-aligned boundary).

wBitsPerSample

Bits per sample for the wFormatTag format type. If wFormatTag is WAVE_FORMAT_PCM, then wBitsPerSample should be equal to 8 or 16. For non-PCM formats, this member must be set according to the manufacturer's specification of the format tag. If wFormatTag is WAVE_FORMAT_EXTENSIBLE, this value can be any integer multiple of 8. Some compression schemes cannot define a value for wBitsPerSample, so this member can be zero.

cbSize

Size, in bytes, of extra format information appended to the end of the WAVEFORMATEX structure. This information can be used by non-PCM formats to store extra attributes for the wFormatTag. If no extra information is required by the wFormatTag, this member must be set to zero. For WAVE_FORMAT_PCM formats (and only WAVE_FORMAT_PCM formats), this member is ignored.

Requirements

Header: Mmreg.h.

See Also

  • WAVEFORMATEXTENSIBLE


WAVEFORMATEXTENSIBLE

The WAVEFORMATEXTENSIBLE structure defines the format of waveform-audio data for formats having more than two channels or higher sample resolutions than allowed by WAVEFORMATEX.

This structure is not part of the DirectSound API but is documented here for convenience.

Syntax

typedef struct {
  WAVEFORMATEX  Format;
  union {
    WORD  wValidBitsPerSample;
    WORD  wSamplesPerBlock;
    WORD  wReserved;
  } Samples;
  DWORD   dwChannelMask;
  GUID    SubFormat;
} WAVEFORMATEXTENSIBLE, *PWAVEFORMATEXTENSIBLE;

Members

Format

WAVEFORMATEX structure that specifies the basic format. The wFormatTag member must be WAVE_FORMAT_EXTENSIBLE, defined in Mmreg.h. The cbSize member must be at least 22.

wValidBitsPerSample

Number of bits of precision in the signal. Usually equal to WAVEFORMATEX.wBitsPerSample. However, wBitsPerSample is the container size and must be a multiple of 8, whereas wValidBitsPerSample can be any value not exceeding the container size. For example, if the format uses 20-bit samples, wBitsPerSample must be at least 24, but wValidBitsPerSample is 20.

wSamplesPerBlock

Number of samples contained in one compressed block of audio data. This value is used in buffer estimation. This value is used with compressed formats that have a fixed number of samples within each block. This value can be set to zero if a variable number of samples is contained in each block of compressed audio data. In this case, buffer estimation and position information needs to be obtained in other ways.

wReserved

Reserved for internal use by operating system. Set to zero.

dwChannelMask

Bitmask specifying the assignment of channels in the stream to speaker positions. See Remarks.

SubFormat

Subformat of the data, such as KSDATAFORMAT_SUBTYPE_PCM. The subformat information is similar to that provided by the tag in the WAVEFORMATEX structure's wFormatTag member.

Remarks

WAVEFORMATEXTENSIBLE can describe any format that can be described by WAVEFORMATEX, but provides additional support for more than two channels, for greater precision in the number of bits per sample, and for new compression schemes.

WAVEFORMATEXTENSIBLE can safely be cast to WAVEFORMATEX, because it simply configures the extra bytes specified by WAVEFORMATEX.cbSize. DirectSound recognizes the WAVE_FORMAT_EXTENSIBLE format tag and correctly plays multiple-channel and compressed formats in hardware buffers, as long as these formats are supported by the driver.

The dwChannelMask member specifies which channels are present in the multichannel stream. The least significant bit corresponds with the front left speaker, the next least significant bit corresponds to the front right speaker, and so on. The bits, in order of significance, are defined in Ksmedia.h and Mmreg.h as follows.

Speaker position | Flag bit
SPEAKER_FRONT_LEFT | 0x1
SPEAKER_FRONT_RIGHT | 0x2
SPEAKER_FRONT_CENTER | 0x4
SPEAKER_LOW_FREQUENCY | 0x8
SPEAKER_BACK_LEFT | 0x10
SPEAKER_BACK_RIGHT | 0x20
SPEAKER_FRONT_LEFT_OF_CENTER | 0x40
SPEAKER_FRONT_RIGHT_OF_CENTER | 0x80
SPEAKER_BACK_CENTER | 0x100
SPEAKER_SIDE_LEFT | 0x200
SPEAKER_SIDE_RIGHT | 0x400
SPEAKER_TOP_CENTER | 0x800
SPEAKER_TOP_FRONT_LEFT | 0x1000
SPEAKER_TOP_FRONT_CENTER | 0x2000
SPEAKER_TOP_FRONT_RIGHT | 0x4000
SPEAKER_TOP_BACK_LEFT | 0x8000
SPEAKER_TOP_BACK_CENTER | 0x10000
SPEAKER_TOP_BACK_RIGHT | 0x20000

For more information on this structure, see the document Multiple Channel Audio Data and WAVE Files, available at www.microsoft.com.

Requirements

Header: Mmreg.h, Ksproxy.h.

See Also

  • Multichannel and High-Resolution WAV Formats


DirectSound GUIDs

This section lists globally unique identifiers used in DirectSound. The following topics are covered:

  • DirectSound Interface GUIDs
  • DirectSound Component GUIDs
  • DirectSound Device GUIDs
  • DirectSound Effect GUIDs


DirectSound Interface GUIDs

The following GUIDs are used as interface identifiers (IIDs) to obtain DirectSound interfaces.

IID | Interface
IID_IDirectSound3DBuffer8 | IDirectSound3DBuffer8
IID_IDirectSound3DListener8 | IDirectSound3DListener8
IID_IDirectSound8 | IDirectSound8
IID_IDirectSoundBuffer8 | IDirectSoundBuffer8
IID_IDirectSoundCapture8 | IDirectSoundCapture8
IID_IDirectSoundCaptureBuffer8 | IDirectSoundCaptureBuffer8
IID_IDirectSoundCaptureFXAec8 | IDirectSoundCaptureFXAec8
IID_IDirectSoundCaptureFXNoiseSuppress8 | IDirectSoundCaptureFXNoiseSuppress8
IID_IDirectSoundFullDuplex8 | IDirectSoundFullDuplex8
IID_IDirectSoundFXChorus8 | IDirectSoundFXChorus8
IID_IDirectSoundFXCompressor8 | IDirectSoundFXCompressor8
IID_IDirectSoundFXDistortion8 | IDirectSoundFXDistortion8
IID_IDirectSoundFXEcho8 | IDirectSoundFXEcho8
IID_IDirectSoundFXFlanger8 | IDirectSoundFXFlanger8
IID_IDirectSoundFXGargle8 | IDirectSoundFXGargle8
IID_IDirectSoundFXI3DL2Reverb8 | IDirectSoundFXI3DL2Reverb8
IID_IDirectSoundFXParamEq8 | IDirectSoundFXParamEq8
IID_IDirectSoundFXWavesReverb8 | IDirectSoundFXWavesReverb8
IID_IDirectSoundNotify8 | IDirectSoundNotify8
IID_IKsPropertySet | IKsPropertySet

Note Where an interface has not changed from previous versions of DirectX, the IID in the table is defined in Dsound.h as the original IID. For example, IID_IDirectSound3DBuffer8 is defined as IID_IDirectSound3DBuffer, because IDirectSoundBuffer8 is the same as IDirectSoundBuffer.


DirectSound Component GUIDs

The following GUIDS are used as class identifiers (CLSIDs) in the creation of DirectSound components.

CLSID | Component
CLSID_DirectSound | DirectSound playback device
CLSID_DirectSound8 | DirectSound8 playback device
CLSID_DirectSoundCapture | DirectSoundCapture device
CLSID_DirectSoundCapture8 | DirectSoundCapture8 device
CLSID_DirectSoundFullDuplex | Full duplex device

Note For information about the differences between the older and newer versions of playback and capture device components, see IDirectSound8 Interface and IDirectSoundCapture8::CreateCaptureBuffer.


DirectSound Device GUIDs

The following GUIDs are used to identify default playback and capture devices.

Device ID | Description
DSDEVID_DefaultPlayback | System-wide default audio playback device.
DSDEVID_DefaultCapture | System-wide default audio capture device.
DSDEVID_DefaultVoicePlayback | Default voice playback device.
DSDEVID_DefaultVoiceCapture | Default voice capture device.

See Also

  • Creating the Device Object
  • Creating the Capture Device Object
  • DirectSoundCaptureCreate8
  • DirectSoundCreate8
  • DirectSoundFullDuplexCreate8
  • GetDeviceID
  • IDirectSoundFullDuplex8::Initialize


DirectSound Effect GUIDs

The following GUIDs are used to identify capture and playback effects.

GUID | Description
GUID_DSCFX_CLASS_AEC | Acoustic echo cancellation capture effect
GUID_DSCFX_CLASS_NS | Noise suppression capture effect
GUID_DSCFX_MS_AEC | Microsoft acoustic echo cancellation capture effect
GUID_DSCFX_MS_NS | Microsoft noise suppression capture effect
GUID_DSCFX_SYSTEM_AEC | System default acoustic echo cancellation capture effect
GUID_DSCFX_SYSTEM_NS | System default noise suppression capture effect
GUID_DSFX_STANDARD_CHORUS | Chorus effect
GUID_DSFX_STANDARD_COMPRESSOR | Compressor effect
GUID_DSFX_STANDARD_DISTORTION | Distortion effect
GUID_DSFX_STANDARD_ECHO | Echo effect
GUID_DSFX_STANDARD_FLANGER | Flanger effect
GUID_DSFX_STANDARD_GARGLE | Gargle effect
GUID_DSFX_STANDARD_I3DL2REVERB | Environmental reverberation effect
GUID_DSFX_STANDARD_PARAMEQ | Parametric equalizer effect
GUID_DSFX_WAVES_REVERB | Waves reverberation effect

See Also

  • IDirectSoundBuffer8::GetObjectInPath
  • DSCEFFECTDESC
  • DSEFFECTDESC


DirectSound Return Values

This section provides a brief explanation of the various error codes that can be returned by DirectSound methods. For a partial list of the specific codes that each method can return, see the individual method descriptions.

Note The lists of error codes in method descriptions are not necessarily comprehensive. Applications should always check for method failure and not just for specific codes. For example, most methods can return DSERR_NODRIVER if the driver is removed while the application is running, or DSERR_OUTOFMEMORY if no more memory is available for operations.

Error codes are presented in the following sections:

  • DirectSound Return Values by Number
  • DirectSound Return Values by Name


DirectSound Return Values by Number

The following table lists DirectSound return values sorted by hexadecimal value. For a description, click on the constant.

Hexadecimal | Constant
0x00000000 | DS_OK
0x00000007 | DSERR_OUTOFMEMORY
0x000001AE | DSERR_NOINTERFACE
0x0878000A | DS_NO_VIRTUALIZATION
0x08780014 | DS_INCOMPLETE
0x80004001 | DSERR_UNSUPPORTED
0x80004005 | DSERR_GENERIC
0x80070005 | DSERR_ACCESSDENIED
0x80070057 | DSERR_INVALIDPARAM
0x8878000A | DSERR_ALLOCATED
0x8878001E | DSERR_CONTROLUNAVAIL
0x88780032 | DSERR_INVALIDCALL
0x88780046 | DSERR_PRIOLEVELNEEDED
0x88780064 | DSERR_BADFORMAT
0x88780078 | DSERR_NODRIVER
0x88780082 | DSERR_ALREADYINITIALIZED
0x88780096 | DSERR_BUFFERLOST
0x887800A0 | DSERR_OTHERAPPHASPRIO
0x887800AA | DSERR_UNINITIALIZED
0x887810B4 | DSERR_BUFFERTOOSMALL
0x887810BE | DSERR_DS8_REQUIRED
0x887810C8 | DSERR_SENDLOOP
0x887810D2 | DSERR_BADSENDBUFFERGUID
0x887810DC | DSERR_FXUNAVAILABLE
0x88781161 | DSERR_OBJECTNOTFOUND


DirectSound Return Values by Name

The following list describes all DirectSound return values. To find a constant from its value, see DirectSound Return Values by Number.

DS_OK

The method succeeded.

DS_NO_VIRTUALIZATION

The buffer was created, but another 3-D algorithm was substituted.

DS_INCOMPLETE

The method succeeded, but not all the optional effects were obtained.

DSERR_ACCESSDENIED

The request failed because access was denied.

DSERR_ALLOCATED

The request failed because resources, such as a priority level, were already in use by another caller.

DSERR_ALREADYINITIALIZED

The object is already initialized.

DSERR_BADFORMAT

The specified wave format is not supported.

DSERR_BADSENDBUFFERGUID

The GUID specified in an audiopath file does not match a valid mix-in buffer.

DSERR_BUFFERLOST

The buffer memory has been lost and must be restored.

DSERR_BUFFERTOOSMALL

The buffer size is not great enough to enable effects processing.

DSERR_CONTROLUNAVAIL

The buffer control (volume, pan, and so on) requested by the caller is not available. Controls must be specified when the buffer is created, using the dwFlags member of DSBUFFERDESC.

DSERR_DS8_REQUIRED

A DirectSound object of class CLSID_DirectSound8 or later is required for the requested functionality. For more information, see IDirectSound8 Interface.

DSERR_FXUNAVAILABLE

The effects requested could not be found on the system, or they are in the wrong order or in the wrong location; for example, an effect expected in hardware was found in software.

DSERR_GENERIC

An undetermined error occurred inside the DirectSound subsystem.

DSERR_INVALIDCALL

This function is not valid for the current state of this object.

DSERR_INVALIDPARAM

An invalid parameter was passed to the returning function.

DSERR_NOAGGREGATION

The object does not support aggregation.

DSERR_NODRIVER

No sound driver is available for use, or the given GUID is not a valid DirectSound device ID.

DSERR_NOINTERFACE

The requested COM interface is not available.

DSERR_OBJECTNOTFOUND

The requested object was not found.

DSERR_OTHERAPPHASPRIO

Another application has a higher priority level, preventing this call from succeeding.

DSERR_OUTOFMEMORY

The DirectSound subsystem could not allocate sufficient memory to complete the caller's request.

DSERR_PRIOLEVELNEEDED

A cooperative level of DSSCL_PRIORITY or higher is required.

DSERR_SENDLOOP

A circular loop of send effects was detected.

DSERR_UNINITIALIZED

The IDirectSound8::Initialize method has not been called or has not been called successfully before other methods were called.

DSERR_UNSUPPORTED

The function called is not supported at this time.


DirectX Glossary
Microsoft DirectX 9.0 SDK Update (October 2004)

DirectX Glossary

A | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
alpha | In computer graphics, the measure of a pixel's opacity. A pixel with the maximum alpha value is opaque, one with a value of zero is transparent, and one with an intermediate value is translucent.
alpha blend | Method for combining two images that uses both pixel colors and alpha values to determine the color of the resulting pixel. This allows an image to be rendered on top of another image, with a blend of both images showing. When blending two pixels, the color components of both pixels are first scaled by their alpha values. Then, the bottom pixel is scaled by the inverse of the top pixel alpha value and added to the top pixel to form the final blended color.
alpha channel | Opacity of an image defined by an alpha value per pixel, interleaved with the color components (for example, ARGB), an alpha value per pixel stored in a separate alpha surface, or a constant alpha value for the entire surface.
alpha color component | Portion of a 32-bit color that determines its opacity. In this case, the alpha value per pixel is interleaved with the color components (for example, ARGB). Less commonly, this term refers to an image with an alpha value per pixel stored in a separate alpha surface.
alpha constant | Level of opacity (alpha value) applied to an entire surface.
alpha edge blend | Particular use of alpha blending (and alpha channel information) to reduce aliasing by blending edges, based on pixel coverage information.
ambient | Description of a light source that illuminates everything in a scene, regardless of the orientation, position, and surface characteristics of the objects in the scene. Because it illuminates a scene with equal strength everywhere, the position and orientation of the frame that an ambient light source is attached to are inconsequential. Multiple ambient light sources are combined within a scene.
anisotropic filtering | Mipmap filtering mode that compensates for anisotropic distortion.
anisotropy | Distortion visible in the image of a 3-D object whose surface is oriented at an angle with respect to the viewing plane. The anisotropy is measured as the elongation (length divided by width) of a screen pixel that is inverse-mapped into texture space.
ARGB | Alpha (opacity), red, green, and blue components of a pixel. Each color is represented in memory by data in BGRA order.
array object | Group of objects organized into an array. Array objects make it simpler to apply operations to the entire group. The Component Object Model (COM) interfaces that enable you to work with array objects contain the GetElement and GetSize methods. These methods retrieve a pointer to an element in the array and the size of the array, respectively.
articulation | A series of adjustments applied by a synthesizer to the pitch, volume, and other parameters of an instrument sound to make it more realistic.
attach | To connect multiple DirectDrawSurface objects into complex structures, such as those needed to support 3-D page flipping with z-buffers. Attachment is not bidirectional, and a surface cannot be attached to itself. Emulated surfaces (in system memory) cannot be attached to non-emulated surfaces. Unless one surface is a texture map, the two attached surfaces must be the same size.
attached | Physically connected to the system. A device may be installed but not currently attached.
attack | Period at the beginning of a force-feedback effect when the magnitude is reaching its basic or sustain level.
B | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
back buffer | Nonvisible surface to which bitmaps and other images can be drawn while the front buffer displays the currently visible image.
back clipping plane | Far boundary of a viewing frustum beyond which objects are not rendered. See also "front clipping plane."
bank select | A MIDI controller that enables instruments to be chosen from different groups or banks, each identified by a 2-byte code.
billboard | Primitive inserted into a 3-D scene that is oriented so that one face is toward the viewer. A texture, usually an animated sprite, is applied to the billboard to give the appearance of a 3-D object in the scene.
billboarding | 2-D technique of simulating the appearance of a 3-D object in a scene. An application inserts a primitive, typically rectangular, into the scene, orients it so that one face is toward the viewer, and applies a texture or a set of textures. The texture or set of textures gives the appearance of an animated 3-D object.
bit block transfer (bitblt or blit) | A graphics function that moves blocks of bits from one bitmap to another in the most efficient manner supported by the hardware.
bitblt | Bit block transfer (bitblt). A graphics function that moves blocks of bits from one bitmap to another in the most efficient manner supported by the hardware.
blend factor | Description of how each color component is blended in texture blending.
blend mode | Algorithm used to determine how a texture is blended with the colors of the surface to which the texture is applied.
blending stage | One step in a texture cascade. A blending stage includes one texture and a set of texture-blending operations that are used when blending multiple textures.
blit | Bit block transfer; sometimes called bitblt. A graphics function that moves blocks of bits from one bitmap to another in the most efficient manner supported by the hardware.
bob | A technique for displaying interlaced video. In bob mode, each field is displayed individually. The gaps between scan lines are filled using interpolation.
bounds checking | Process of checking that an on-screen image is displayed within the bounds of the screen.
bump mapping | Technique for simulating the appearance of rough surfaces in 3-D scenes. Variations in depth are stored in a texture and applied to a primitive, using standard texture-blending techniques.
C | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
camera | Direct3DRMFrame object used by the viewport to define the viewing position and direction. The viewport renders only what is visible along the positive z-axis of the camera frame, with the up direction in the direction of the positive y-axis.
camera space | Frame of reference in which the viewer is at the origin, looking in the direction of the positive z-axis. Objects are transformed from world space to camera space by using the view transformation.
chordmap | A scheme of chord progressions, arranged in a flowchart along a time line.
client/server session | Microsoft DirectPlay session in which only the server stores the session's complete state, and each client has only a subset of the session's state. Each client receives only the information that is relevant to that computer from the server. When one computer changes something, it propagates the change to the server. The server then determines which clients it must inform of the change. See also "peer-to-peer session."
clip list | Series of rectangles that describes the visible areas of the surface. The clip list cannot be set if a window handle is already associated with the DirectDrawClipper object.
clipper | DirectDrawClipper object.
codec | An abbreviation for compressor/decompressor. Software or hardware used to compress and decompress digital media.
collision detection | Process for determining if any pixels for two images share the same location on the screen. See also "hit detection."
color key | A color value used for pixel selection that enables transparent or translucent effects. When using a hardware blitter in graphics, for example, all the pixels of a rectangular area are blitted, except the value that was set as the color key. This creates nonrectangular sprites on a surface. In Microsoft DirectShow, an overlay surface is displayed in the region of the primary surface that contains the color key. In video production, color keys are used to combine two video signals. Also called a chroma key.
color space | Model for representing color as three or more coordinates. Color-space models map color components onto a Cartesian coordinate system in three or more dimensions. A color space may use any of several types of color encoding and visualizing. The two most common types of color space models are RGB and YUV.
color table | Array of n color values (normally RGB triples).
color-space conversion | Technique for converting a color in one color space to another color space. Typically, this conversion is from YUV colors from a video source to RGB for display.
complex surface | Collective term for several DirectDrawSurface objects, all of which are attached to a root surface. The complex-surface structure can be destroyed only by destroying the root.
composition | A collection of tracks and (optionally) other compositions. At rendering time, the sources in a composition are composited into a single image.
control segment | Musical segment that controls certain aspects of playback. Normally it is the primary segment, but a secondary segment can be designated as the control segment.
culling | Removing a face from the list of faces to render. Faces can be culled using a number of techniques including: back face, view frustum, and occlusion culling.
curve | In Microsoft DirectMusic, a continuous series of events with a start and end value, such as volume fade.
D | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
dark light | Light source that removes illumination from a scene Dark light is created by specifying negative values for the colors of the light.
DCI | Display Control Interface. Defined by the Intel and Microsoft corporations, DCI is an interface that offers improved graphics performance as a result of direct video memory access.
dead zone | Area within the physical range of an axis where the axis is considered to be at the center.
deadband | Zone around the offset of a force-feedback axis at which a condition is not active.
decal | Texture that is rendered directly, as a visual. Decals are rendered into a viewport-aligned rectangle.
deinterlace | To combine the interlaced fields in a video frame so that, during playback, the lines of the video frame are painted sequentially.
delta frame | A video frame that contains only the changes from the previous frame. In contrast, a key frame contains all the data necessary to construct that frame.
destination color key | Color that (in the case of blitting) is replaced or (in the case of overlays) is covered on the destination surface.
device window | Visible application window that Microsoft DirectDraw uses for display. Applications can have a device window for each display device attached to a given computer. See also "focus window."
DIB sequence | In DirectShow Editing Services, a series of device-independent bitmap (DIB) files rendered in a sequence as video frames.
directional | Description of a light source that is attached to a frame but appears to illuminate all objects with equal intensity, as if it were at an infinite distance from the objects. Directional light has orientation but no position, and it is commonly used to simulate distant light sources, such as the sun.
DirectPlay address | Data format that DirectPlay uses to pass addressing information between lobby servers, applications, DirectPlay, and service providers. A DirectPlay address is a sequence of variable-length data chunks tagged with a globally unique identifier (GUID) that supplies all the address information needed by DirectPlay. Examples of address information are: the network address of a server, the network address of a player, the e-mail name of a player, and the network address of a session.
DirectX Media Object (DMO) | A COM object that processes multimedia data streams from buffers allocated by the client.
dither | Method to display a range of colors with a limited palette. Each pixel on the source image is represented by multiple pixels (usually a 2x2 square) on the destination image. From a distance, the eye blends the multiple pixels into one color that has more shades than the original palette. The technique results in a better visual appearance than the removal of low precision bits. See a standard graphics reference for details. Dithering is a supported option by DXSurface and Microsoft DirectX Transform objects.
DLS | Downloadable sounds. A standard for synthesizing wave sounds from digital samples stored in software. The DLS level 1 and level 2 standards are published by the MIDI Manufacturers Association.
DMO | DirectX Media Object. A COM object that processes multimedia data streams from buffers allocated by the client.
downloadable sounds (DLS) | A standard for synthesizing wave sounds from digital samples stored in software. The DLS level 1 and level 2 standards are published by the MIDI Manufacturers Association.
downsample | To reduce the sampling rate of a signal.
downstream | In a filter graph, the direction in which digital media samples travel.
E | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
emissive property | Material property that determines whether a material emits light. The emissive property of a material is one of two properties that determines how the material reflects light. See also "specular property."
emissive setting | See "emissive property."
enable frame | Frame to which a light applies.
envelope | In force feedback, a set of values that defines the shape of an effect by modifying the magnitude at the beginning (attack) and end (fade). In audio, a set of values that defines the shape of the amplitude or pitch of a sound. Downloadable sounds (DLS) level 1 defines a four-segment envelope: attack, decay, sustain, and release (ADSR). DLS level 2 defines six segments: delay, attack, hold, decay, sustain, and release (DAHDSR).
even field | Second field, comprising a video frame in an odd/even field set. Also known as field 2.
execute buffer | Fully self-contained, independent packet of information that describes a 3-D scene. An execute buffer contains a vertex list followed by an instruction stream. The instruction stream consists of operation codes, and the data that is operated on by those codes.
F | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
face | Single polygon in a mesh.
fade | Period between the central, or sustain, portion of a force-feedback effect and its end.
falloff | Light attenuation between a spotlight's inner and outer cones.
field | A portion of an interlaced video frame. With interlaced video, the scan lines of even-numbered fields fall spatially halfway between the scan lines of odd-numbered fields.
field polarity | Quality determining whether a field is an even field or an odd field. In odd fields, the trailing edge of the vertical refresh (VREF) does not occur during a scan line. In even fields, the trailing edge of the VREF occurs during a scan line.
flimmering | Shimmering appearance on 3-D primitives that results from a poor separation of z-values when doing decaling. Some pixels from the back texture are rendered onto the front texture and vice versa.
flip | Process of swapping the addresses associated with the back and front buffer. This effectively swaps the image in the back buffer to the front buffer, thus displaying the image.
flipping chain | Series of surfaces attached to each other that can be flipped. See also "flip."
flipping surface | Any piece of memory that can be flipped. See also "flip."
focus window | Application window, visible or not visible, that DirectDraw uses to hook window messages. The focus window's message handler receives input messages forwarded by DirectDraw. Applications can have only one focus window. See also "device window."
frame | Invisible box that provides a frame of reference for objects in a scene. Objects can be placed in a scene by specifying their spatial relationship to a relevant reference frame. Visual objects take their positions and orientations from frames. In a movie or animation, a single image.
front buffer | Rectangle of memory that is translated by the graphics adapter and displayed on the monitor or other output device.
front clipping plane | Near boundary of a viewing frustum. Any object closer to the camera than the front clipping plane is not rendered. The height of the front clipping plane defines the field of view. See also "clipping plane."
G | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
gamma | The curve in the function that maps changes in voltage to changes in brightness on a phosphor screen. The change in voltage needed to produce a specified change in brightness is not constant across voltage levels.
genlocking | Process of synchronizing one video signal with another. Because they are synchronized, the genlocked signal can be mixed with the original signal, enabling dissolves, wipes, and other transition effects.
grid | Subdivision of a beat. The number of grids per beat is part of the DirectMusic time signature.
groove level | A value given to music during style playback. The groove level determines which patterns can be selected at any given time. The author assigns a range of groove levels to each pattern.
group | In DirectPlay, a logical collection of players. DirectPlay supports groups within a session. By creating a group of players, an application can send a single message to the group, and all players in the group receive the message. A group is the means by which a network's multicast capabilities are exposed to the application. Groups can be used to organize players in a session. A player can belong to more than one group. DirectPlay provides methods for administering groups and their membership. In DirectShow, a top-level collection of compositions and tracks, all representing the same multimedia type. Each group produces a separate stream in the rendered project.
H | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
HAL | The hardware abstraction layer (HAL) consists of hardware and device driver mechanisms that insulate applications from device-specific implementation details. If a capability requested by an application is not implemented by the current hardware, the capability is emulated by the software.
hardware blitter | Hardware component, built into the display adapter, that performs efficient blit operations.
HEL | Hardware emulation layer. The HEL provides software-based emulation of features that are not present in hardware.
HID | Human Interface Device. A universal serial bus (USB) class representing devices that enable a human to control a computer.
hit detection | See "collision detection."
host | In DirectPlay, a virtual player whose identifier (ID) is DPID_SYSMSG. The host manages system messages and messages sent to all players in a session.
host byte order | On an Intel x86 computer, the byte order for the system, or host, is little endian. Network byte order is always big endian.
HREF | In a video stream, the horizontal refresh (HREF) is active to signal that the display is to begin a new scan line. See also "VREF."
HRTF | Head-related transfer function. A mathematical representation of the effect of the listener's physiology on the pitch and timing of sounds arriving from different directions.
I | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
index palette | DirectDrawPalette object whose entries are indexes into another palette object.
intelligent connect | An algorithm used by the filter graph manager to build graphs and connect filters. If an output pin is specified, the filter graph manager renders the data from that pin by using default renderers. If two filters are specified, the filter graph manager attempts to connect them. It will insert intermediate filters if necessary.
interlace | To display a video frame in two fields. One field contains the even lines of the frame, the other field contains the odd lines. During playback, the lines in one field are displayed first, then the lines in the second field are displayed.
interleaving | The arrangement of video frames and audio samples in a file, such that video data alternates with audio data at regular intervals.
IPX service provider | Service provider that uses Windows Sockets to communicate over a local area network (LAN) using the Internetwork Packet Exchange (IPX) protocol. The service provider supports only non-guaranteed messaging. A single computer can host only one DirectPlay session using IPX.
IRE scale | International Radio Engineers scale. A scale of values ranging from 0 to 100 that defines the brightness level of a broadcast video signal. The spectrum of low-to-high IRE values describes increasing brightness levels of a video signal. At 7.5 IRE brightness, the black cut-off threshold for a National Television System Committee (NTSC) signal, the electron guns of an NTSC display device are cut off and do not display images.
K | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
kernel mode | The operational state of a processor that enables full, unprotected access to a system. A driver or thread running in kernel mode has access to system memory and hardware.
key frame | A video frame containing all the data needed to construct an image without reference to previous frames.
L | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
latency | A delay in response. For example, in Microsoft DirectSound, it is the interval between the time at which a sound buffer plays and the time that the speakers actually reproduce the sound. In DirectPlay, it is the time that it takes for a packet to reach a specified destination. In DirectShow, it is the amount of time it takes a filter to process a sample.
LED | Light-emitting diode.
letterbox | A video display format in which black bars appear above and below the video image while it is played. The letterbox format maintains the original aspect ratio of an image when it is displayed in a window with a different aspect ratio.
light map | Texture or group of textures that contain lighting information for a 3-D scene.
lobby client | Lobby management routines associated with the user's computer, including launching applications, updating the user interface, and communicating with the lobby server.
lobby provider | Client component (dynamic-link library) supplied by the developer of a lobby server. It implements communication functions with the lobby server, as requested by DirectPlay.
lobby server | Lobby management routines associated with a remote server. The lobby server coordinates all the information about the users who are connected to a specific application.
lobby session | Connection to a lobby server on which clients and the server have not been specifically written to interoperate.
lobby-aware application | Application that, at a minimum, supports being launched from a lobby.
locked audio | A video format in which the number of audio samples in a specified number of frames is fixed. In unlocked audio, the number of samples in a set of frames may vary, although the average equals the stated sample rate.
lookahead | To use data from later in the stream to process the current data. For example, the next key frame is used to calculate a delta frame.
M | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Mach bands | Bands of color that are not smoothly blended across a 3-D primitive.
material | Property that determines how a surface reflects light. A material has two components: an emissive property (whether it emits light) and a specular property, whose brightness is determined by a power setting.
medium | Structure that identifies a hardware data path between two devices on the host system. They can be devices on the same card, such as a crossbar and a tuner on a TV card; devices on separate cards; or external devices. Kernel-mode filters based on the Windows Driver Model can use mediums instead of media types to determine pin connections.
mesh | Set of faces, each of which is described by a simple polygon.
mipmap | Also known as MIP map (Latin: multum in parvo, translated as "much in little"). A sequence of textures, each of which is a progressively lower-resolution, prefiltered representation of the same image. A higher-resolution image is used when a visible object is close to the viewer. As the object moves farther away (and gets smaller), lower-resolution images are used.
mix-in buffer | In DirectSound, a buffer that receives data from other DirectSound buffers rather than directly from the synthesizer.
mixing | In DirectSound, the process of combining sound buffers that are playing, and writing the result to the primary sound buffer, which supplies audio data to the sound hardware. There is no limit to the number of buffers that can be mixed, except the available processing time.
Mode X | Hybrid display mode derived from the standard VGA Mode 13. This mode allows the use of up to 256 KB of display memory (rather than the 64 KB allowed by Mode 13) by using the VGA display adapter's EGA multiple video plane system.
model coordinates | Coordinates that are relative to a local origin. See also "model space" and "world coordinates."
model space | Frame of reference (used by model coordinates) that uses vertices relative to a single 3-D model's local origin.
motif | In DirectMusic, a type of pattern played explicitly by an application to mark an event.
multipass texture blending | Repeated rendering of a 3-D primitive while blending on a texture with each pass. This technique is widely used to achieve a variety of special effects.
multiplexer (MUX) | A filter that combines multiple input streams into one output stream.
music value | In DirectMusic, a note in a pattern within a style whose pitch is defined only when it is transposed to the current chord according to the current play mode and subchord level.
MUX | Multiplexer.
N | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
nagling | Algorithm that causes the Transmission Control Protocol/Internet Protocol (TCP/IP) service provider to buffer small data packets into larger ones before sending. Nagling prevents a TCP/IP protocol server from transmitting many very small packets by requiring the server to wait either until it has accumulated enough small data packets to combine them into a single large packet or until it has received an acknowledgment of the prior packet. Nagling can reduce message overhead (and decrease required bandwidth), but also causes a delay before small data packets are sent (increasing latency).
National Television Standards Committee (NTSC) | The dominant television standard in the United States and Japan. NTSC delivers 30 interlaced frames per second at 525 lines of resolution.
nonregistered parameter number (NRPN) | An identifier for a device-specific parameter that can be accessed through a MIDI controller. Nonregistered parameters can be used for different functions by different manufacturers.
normal vector | Imaginary ray extending perpendicularly from a surface that defines the face's orientation.
NRPN | Nonregistered parameter number.
NTSC | National Television Standards Committee.
O | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
odd field | First field comprising a video frame in an odd/even field set.
off-screen surface | Conceptually rectangular area in memory that is generally used to store bitmaps to be blitted to a back buffer before being displayed. Commonly used to store sprites.
opcode | Operation code that defines how to interpret the vertices in an execute buffer or how to change the state of the system.
overdraw | Average number of times that a screen pixel is written to.
overlay surface | Conceptually rectangular area in memory whose stored image information covers the image information of the primary surface to which it is applied. Overlays are assumed to be on top of all other screen components.
overlay z-order | Determines the order in which overlays clip each other, enabling a hardware sprite system to be implemented under DirectDraw.
P | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
page flipping | See "flip."
PAL | Phase Alternate Line.
palette | Set of colors used by an object or application. In DirectX, a DirectDrawPalette object.
palette index | Integer index into the palette table array that is used to select a particular color.
palettized surface | Collection of numbers where each number represents a pixel. Also called a color-indexed surface. Also, a DirectDrawSurface object that uses an attached palette to contain color information.
pan scan | A digital video disc (DVD) display format in which a 16x9 video is cropped for display in a 4x3 window, by using parameters defined by the video author.
pan value | Relative volume, measured in hundredths of decibels, between the left and right audio channels.
parallel point | Description of a light source that illuminates objects with parallel light, but the orientation of the light is taken from the position of the parallel point light source. For example, two meshes on either side of a parallel point light source are lit on the side that faces the position of the source.
pattern | In DirectMusic, a musical figure, one or more measures long, consisting of a basic sequence of music values for each instrument part.
PChannel | Performance channel.
PCM | Pulse code modulation.
peer-to-peer session | DirectPlay session in which the session's complete state is replicated on all the computers in the session. The session description data (the list of players and groups and the names and remote data associated with each session) are duplicated on every computer. When one computer changes something, it is immediately propagated to all the other computers. This is the default mode of communication for DirectPlay. See also "client/server session."
performance | In DirectMusic, an object that manages the flow of data from the source to the synthesizer, and controls global values, such as timing, tempo, and master volume.
performance channel (PChannel) | A MIDI channel in a particular channel group on a particular port. In DirectMusic, a set of parameters used to play one or more parts in a segment. Each performance channel has its own instrument, pan, volume, and transposition settings, and belongs to a single audiopath.
perspective correction | Technique of applying a texture map to a polygon that is angled away from the camera, interpolating so that the texture is stretched onto the polygon appropriately for the apparent depth of the polygon. Microsoft Direct3D supplies perspective correction automatically.
phase alternate line (PAL) | The dominant television standard in Europe and China. PAL delivers 25 interlaced frames per second at 625 lines of resolution.
pick | To search for visuals in a scene, given a 2-D coordinate in a viewport.
PID | Physical interface device. A universal serial bus (USB) class that enables humans to feel force feedback from a computer.
pitch | Distance, in bytes, between an address that represents the beginning of a bitmap line and the beginning of the next line. Do not confuse memory pitch and memory width because not all display memory is laid out as one linear block. For example, with rectangular memory, the pitch of the display memory could include the width of the bitmap plus part of a cache. See also "width" and "stride."
player | Single participant in a DirectPlay session. Each player is associated with a player ID that enables messages to be exchanged among players.
player ID | Unique number that is assigned to each participant in a DirectPlay session when the participant is created. The application can exchange messages among players by using player IDs. The host is always assigned the DPID_SYSMSG player ID.
PNG | Portable Network Graphics. A nonproprietary bitmap format using lossless compression.
point light | Light source that radiates equally in all directions from its origin.
point list | Simplest 3-D primitive. A collection of unconnected points in 3-D space.
power | In the specular property of a material, value that determines the sharpness of specular highlights. A value of 5 gives a metallic appearance, and higher values give a more plastic appearance.
preroll | To capture or play a number of video frames or a portion of audio data before encoding or rendering begins, in order to allow the source device to stabilize. Also used as a noun to describe the portion of the data to be prerolled.
primary buffer | A sound buffer in which all data is mixed for the final time and then passed to the rendering device.
primary surface | Memory containing the image being displayed on the screen.
projection space | Frame of reference containing vertices after they are modified from their world space locations by the projection transformation. Projection space is a homogeneous cuboid space in which all vertices in a scene have x-coordinates and y-coordinates that range from -1.0 to 1.0, and a z-coordinate that ranges from 0.0 to 1.0. Projection space is sometimes referred to as post-perspective homogeneous space.
projection transformation | Application of a matrix to vertices to change them from camera space to projection space.
pulse code modulation (PCM) | A technique for digitizing audio into an uncompressed format by assigning a value to the amplitude of the signal at fixed intervals.
Q | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
quality control | Mechanism for adjusting the rate of data flow in response to run-time conditions.
quaternion | Fourth element added to the [x, y, z] values that define a vector. Quaternions define a 3-D axis and a rotation around that axis.
R | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
reference clock | A clock that provides a common reference time with which filters can be synchronized.
reference count | Control for a COM object. When an object is created, its reference count is set to 1. Every time an interface is bound to the object, its reference count is incremented; when the interface connection is destroyed, the reference count is decremented. The object is destroyed when the reference count reaches 0. All interfaces to that object are then invalid.
reference time | An absolute time established by a reference clock in the filter graph.
region | In downloadable sounds (DLS), range of notes for which a particular digital sample is used in synthesizing an instrument's timbre.
registered parameter number (RPN) | An identification number for a registered parameter that has been assigned a function by the MIDI Manufacturers Association and can be accessed through controllers.
RGBA | Red, green, blue, and alpha (opacity) components of a pixel. Each color is represented in memory by data in ABGR order.
RHW | Transformed vertices in homogeneous space. The (x,y,z) data has already been divided by w (multiplied by the reciprocal of w).
rolloff | The attenuation of sound over distance.
root frame | Frame in Direct3D that has no parent frame; it is at the top of a hierarchy of frames. The root frame contains the entire set of objects that make up a scene. See also "scene."
RPN | Registered parameter number.
S | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
saturation | In input and force feedback, adjustment to an axis range so that minimum or maximum values are retrieved or set before the physical extremities are reached. If the maximum value in a range is 1,000 and the maximum saturation point is set to 900, the maximum value is reached after 90 percent of the travel in that direction.
scene | Entire set of objects that make up a virtual environment, including visible objects, sounds, lights, and frames. In Direct3D, the entire set of objects is contained in a root frame.
screen space | Frame of reference that relates 2-D coordinates to locations in the frame buffer. Screen space coordinates typically display on a monitor. The origin, or (0,0) is defined at the upper left corner. Y increases in the downward direction; X increases to the right. You use a viewport transformation matrix to convert points from projection space to screen space.
script | In DirectMusic, a file containing variables and routines that can be accessed from within an application.
secondary sound buffer | Object that manages a single sound or audio stream and plays it to the primary sound buffer.
segment state | An object created each time a segment is played. It is used to get information about the state of playback and the audiopath for that instance of the segment being played.
send | A sound effect for a buffer that is applied by sending the sound data to a second buffer.
service provider | Dynamic-link library used by DirectPlay to communicate over a network. The service provider contains all the network-specific code required to send and receive messages. Online services and network operators can supply service providers to use specialized hardware, protocols, communications media, and network resources.
session | In DirectPlay, instance of several applications on remote computers communicating with each other. Before an application can start communicating with other computers, it must be part of a session. An application can enumerate all the existing sessions on a network and join one of them, or it can create a new session and wait for other computers to join it. Once the application is part of a session, it can create a player and exchange messages with all the other players in the session.
sink | An object that manages the distribution of data from the synthesizer through buses to DirectSound buffers.
sink-in buffer | A DirectSound buffer that receives data directly from the synthesizer rather than from other DirectSound buffers.
smart recompression | In DirectShow Editing Services, the decompression and recompression of source data only when the data must be altered in some way before being written to the destination file.
sound buffer | Object that manages DirectSound audio data.
source color key | Color that (in the case of blitting) is not copied to or (in the case of overlays) not visible on the destination.
specular property | Material property that determines how a point of light on a shiny object corresponds to the reflected light source. The specular property of a material is one of two properties that determines how a material reflects light. See also "emissive property."
spotlight | Light source that emits a cone of light. Only objects within the cone are illuminated. The cone produces light of two degrees of intensity, with a central brightly lit section that acts as a point source, and a surrounding dimly lit section that merges with the surrounding deep shadow.
sRGB | Color space defined by Microsoft.
static buffer | A secondary sound buffer that contains an entire sound. Typically it is filled with data only once. See also "streaming buffer."
sticky focus | In DirectSound, ability to play sound buffers when the owning application does not have the input focus. For example, a DirectSound application could continue to play a sound buffer while the user is working in another application.
stream time | The current time minus the previous start time. Stream time is defined only in a running filter graph.
streaming buffer | A secondary sound buffer that contains only part of a sound. Its data must be refreshed as it is playing. See also "static buffer."
stretching | Blitting an image into a destination with different dimensions. This operation is supported directly by some hardware.
stride | Synonymous with pitch. See also "width."
style | In DirectMusic, a collection of musical patterns and other data that can be used to create a dynamic score. A style defines a basic melody and rhythm with variations, motifs, and embellishments, contains a time signature and a tempo, and can contain one or more bands.
subtype | A GUID value that describes the specific format of data digital media stream.
surface | Memory that represents visual images. This is often display memory but it can also be system memory. See also "complex surface," "off-screen surface," "overlay surface," and "primary surface."
sustain | Period during which the basic magnitude of a force-feedback effect is attained, after the attack and before the fade.
swap chain | A collection of one or more back buffers that can be serially presented to the front buffer.
synchronization point | A media sample that can be decoded without requiring the decompressor to examine any other samples. One example is a key frame.
system message | In DirectPlay, message from the player ID DPID_SYSMSG. All system messages begin with a DWORD value.
T | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
TCP/IP | Transmission Control Protocol/Internet Protocol. A protocol developed by the Department of Defense for communications between computers. It is built into the UNIX system and has become the standard for data transmission over networks, including the Internet.
TCP/IP service provider | Service provider that uses Microsoft Windows Sockets to communicate over the Internet or LAN, using the TCP/IP protocol. The User Datagram Protocol (UDP) TCP/IP service provider uses DirectPlay packets for nonguaranteed and guaranteed messaging. Using TCP/IP protocol, a single computer can host multiple DirectPlay sessions.
tearing | A visual artifact that occurs when one displayed video frame contains parts of two different source video frames. It is usually caused by improper synchronization between video rendering and the graphics display.
template | In DirectMusic, a segment that can be used in combination with a chordmap to compose a new segment at run time.
tessellating | Breaking an image into small square regions for processing or output.
texel | Single element in a texture. When a texture has been applied to an object, the texels rarely correspond to pixels on the screen. Applications can use texture filtering to control how the system interpolates between texels to create pixels in a scene.
texture | Rectangular array of pixels that is applied to a visual object in Direct3D.
texture blending | Technique of combining the colors of a texture with the colors of the surface to which the texture is applied.
texture coordinates | Coordinates that determine which texel in each texture is assigned to each vertex in an object.
texture filtering | Process of mapping texel colors from one or more textures onto the pixels that comprise the image of a 3-D primitive.
texture mapping | Application of a texture to an object. Because a texture is a flat image and the object is often not, the texture must be mapped to the surface of the object, using texture coordinates and wrapping flags. See also "texture coordinates" and "wrap."
texture stage | Contains a texture and operations that can be performed on the texture. As used in DirectX, a texture stage takes two arguments and performs a blending operation on them.
thrashing | Removing textures used in the current frame to reclaim texture memory for subsequent frames.
throttling | Restricting the number of messages to avoid sending them faster than the underlying transport can deliver them.
time code | A digital signal applied to a stream. The signal assigns a number to every frame of video, representing hours, minutes, seconds, and frames.
time stamp | The time on a media sample indicating when it was recorded or when it should be scheduled for playback.
timeline | In a DirectShow Editing Services video-editing project, the root node that contains all the other objects.
track | In DirectShow, a collection of nonoverlapping sources with a common media type (audio or video).
transform filter | A filter that receives data from an upstream filter, processes it, and then delivers it to the next filter in the graph.
trans-in-place filter | A filter that can modify data without copying it to a new buffer.
transport | A mechanism for moving data from one point to another. In a filter, the transport moves media samples across pins. In an external device such as a digital video (DV) camcorder, the transport channels data from the device to a computer, or from the computer to the device.
U | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
unit vector | Vector with a magnitude (length) of 1.0.
Universal Serial Bus (USB) | A serial bus with a bandwidth of 1.5 megabits per second (Mbps) for connecting peripherals to a PC.
upsample | To increase the number of audio samples or pixels, through a process such as interpolation.
USB | Universal Serial Bus.
V | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
VBI | Vertical blanking interval.
velocity | In music, the speed at which a MIDI key is pressed. This is roughly equivalent to the dynamic level at which the note is played in some instrumental timbres. In 3-D sound, for purposes of calculating Doppler shift, velocity is the speed at which a sound source or listener is considered to be moving.
vertex | Point in 3-D space.
vertical blanking interval (VBI) | In broadcast video, small period of time that elapses between video frames during which a display device refreshes its display for the next frame.
vertical refresh (VREF) | In a video stream, the VREF is active to signal that the display is to begin a new screen. See also "HREF."
video frame | Single image in a video stream, comprised of one odd field and one even field. See also "field."
view space | See "camera space."
view state | Accumulation of all a control's property values.
view transformation | Application of a matrix to a model's vertices to change its orientation from world space to view space.
viewing frustum | 3-D volume in a scene positioned relative to the viewport's camera. Objects within the frustum are visible. For perspective viewing, the viewing frustum is the volume of an imaginary pyramid that is between the front clipping plane and the back clipping plane. For orthographic viewing, the viewing frustum is cubic.
viewport | Rectangle that defines how a 3-D scene is rendered into a 2-D window. A viewport also defines an area on a device into which objects are rendered.
virtual device driver (VxD) | Software that manages a hardware or software system resource. These drivers are described using three letters, beginning with V and ending with D. The middle letter indicates the type of device, such as D for display, P for printer, T for timer, or x when the type of device is not under discussion.
virtual track | In DirectShow Editing Services, any object that can be contained in a composition.
VREF | Vertical refresh.
VxD | Virtual device driver.
W | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
WAV | A file format in which Windows stores sounds as waveforms. Such files have the extension .wav.
weave | A method to display interlaced video. In weave mode, alternating fields are combined into a single image.
width | Distance between two addresses in memory that represent the beginning of a line and the end of the line of a stored bitmap. This distance represents only the width of the bitmap in memory. It does not include any extra memory required to reach the beginning of the next line of the bitmap, such as a cache in rectangular memory.
world coordinates | Coordinates that are relative to the origin of a scene. See also "model coordinates" and "world space."
world space | Frame of reference used by world coordinates that declares vertices relative to a single origin within a 3-D scene.
world transformation | Application of a matrix to a model's vertices to change its orientation from model space to world space.
wrap | Procedure used to calculate texture coordinates for a face or mesh. The basic wrapping types are flat, cylindrical, spherical, and chrome.
Z | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
z-buffer | Buffer that stores a depth value for each pixel in a scene. Pixels with a small z-value overwrite pixels with a large z-value.
z-fighting | See "flimmering."


Mapping between a DirectX 9 Declaration and FVF Codes
Microsoft DirectX 9.0 SDK Update (October 2004)

Mapping between a DirectX 9 Declaration and FVF Codes

This table maps members of a D3DVERTEXELEMENT9 declaration to a flexible vertex format (FVF) code.

Data type | Usage | Usage index | FVF
D3DDECLTYPE_FLOAT3 | D3DDECLUSAGE_POSITION | 0 | D3DFVF_XYZ
D3DDECLTYPE_FLOAT4 | D3DDECLUSAGE_POSITIONT | 0 | D3DFVF_XYZRHW
D3DDECLTYPE_FLOATn | D3DDECLUSAGE_BLENDWEIGHT | 0 | D3DFVF_XYZBn
D3DDECLTYPE_UBYTE4 | D3DDECLUSAGE_BLENDINDICES | 0 | D3DFVF_XYZB (nWeights+1)
D3DDECLTYPE_FLOAT3 | D3DDECLUSAGE_NORMAL | 0 | D3DFVF_NORMAL
D3DDECLTYPE_FLOAT1 | D3DDECLUSAGE_PSIZE | 0 | D3DFVF_PSIZE
D3DDECLTYPE_D3DCOLOR | D3DDECLUSAGE_COLOR | 0 | D3DFVF_DIFFUSE
D3DDECLTYPE_D3DCOLOR | D3DDECLUSAGE_COLOR | 1 | D3DFVF_SPECULAR
D3DDECLTYPE_FLOATm | D3DDECLUSAGE_TEXCOORD | n | D3DFVF_TEXCOORDSIZEm(n)
D3DDECLTYPE_FLOAT3 | D3DDECLUSAGE_POSITION | 1 | N/A
D3DDECLTYPE_FLOAT3 | D3DDECLUSAGE_NORMAL | 1 | N/A


Beginning and Ending a Scene
Microsoft DirectX 9.0 SDK Update (October 2004)

Beginning and Ending a Scene

Applications written in C++ notify Microsoft Direct3D that scene rendering is about to begin by calling the IDirect3DDevice9::BeginScene method. IDirect3DDevice9::BeginScene causes the system to check its internal data structures and the availability and validity of rendering surfaces. It also sets an internal flag to signal that a scene is in progress. After you begin a scene, you can call the various rendering methods to render the primitives or individual vertices that make up the objects in the scene. Attempts to call rendering methods when a scene is not in progress fail. For more information, see Rendering Primitives.

After you complete the scene, call the IDirect3DDevice9::EndScene method. The IDirect3DDevice9::EndScene method flushes cached data, verifies the integrity of rendering surfaces, and clears an internal flag that signals when a scene is in progress.

All rendering methods must be bracketed by calls to the IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene methods. If surfaces are lost or internal errors occur, the scene methods return error values. If IDirect3DDevice9::BeginScene fails, the scene does not begin, and subsequent calls to IDirect3DDevice9::EndScene will fail.

To summarize these cases:

  • If IDirect3DDevice9::BeginScene returns any error, you must not call IDirect3DDevice9::EndScene because the scene has not successfully begun.
  • If IDirect3DDevice9::BeginScene succeeds, but you get an error while rendering the scene, you must call IDirect3DDevice9::EndScene.
  • If IDirect3DDevice9::EndScene fails, for any reason, you need not call it again.

For example, some simple scene code might look like the following example.

HRESULT hr;

if(SUCCEEDED(pDevice->BeginScene()))
{
    // Render primitives only if the scene
    // starts successfully.

    // Close the scene.
    hr = pDevice->EndScene();
    if(FAILED(hr))
        return hr;
}

You cannot embed scenes; that is, you must complete rendering a scene before you can begin another one. Calling IDirect3DDevice9::EndScene when IDirect3DDevice9::BeginScene has not been called returns an error value. Likewise, calling IDirect3DDevice9::BeginScene when a previous scene has not been completed with the IDirect3DDevice9::EndScene method results in an error.

Do not attempt to call Microsoft Windows Graphics Device Interface (GDI) functions on Direct3D surfaces, such as the render target or textures, while a scene is being rendered—is between IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene calls. Attempts to do so can prevent the results of the GDI operations from being visible. If your application uses GDI functions, be sure that all GDI calls are made outside the scene functions.


Clearing Surfaces
Microsoft DirectX 9.0 SDK Update (October 2004)

Clearing Surfaces

Before rendering objects in a scene, clear the viewport on the render-target surface or a subset of the viewport. Clearing the viewport causes the system to set the desired portion of the render-target surface and any attached depth or stencil buffers to a desired state. This resets the areas of the surface that will be rendered again, and it resets the corresponding areas of the depth and stencil buffers, if any are in use. Clearing a render-target surface can set the desired region to a default color or texture. For depth and stencil buffers, this can set a depth or stencil value.

Use the IDirect3DDevice9::Clear method to clear the viewport.

Performance Note Applications that render scenes covering the entire area of the render-target surface can improve performance by clearing the attached depth and stencil buffer surfaces, if any, instead of the render target. In this case, clearing the depth buffer causes Microsoft Direct3D to rewrite the render target on the next rendered frame, making an explicit clear operation on the render target redundant. However, if your application renders only to a portion of the render-target surface, explicit clear operations are required.


IDirect3DBaseTexture9::FreePrivateData Method

Frees the specified private data associated with this resource.

Syntax

HRESULT FreePrivateData(

    REFGUID refguid
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to free.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

Microsoft Direct3D calls this method automatically when a resource is released.

See Also

IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::GetPrivateData, IDirect3DIndexBuffer9::GetPrivateData, IDirect3DVertexBuffer9::GetPrivateData, IDirect3DResource9::SetPrivateData, IDirect3DBaseTexture9::SetPrivateData, IDirect3DCubeTexture9::SetPrivateData, IDirect3DTexture9::SetPrivateData, IDirect3DVolumeTexture9::SetPrivateData, IDirect3DIndexBuffer9::SetPrivateData, IDirect3DVertexBuffer9::SetPrivateData


IDirect3DBaseTexture9::GetDevice Method

Retrieves the device associated with a resource.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface to fill with the device pointer, if the query succeeds.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method allows navigation to the owning device object.

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Failure to call IUnknown::Release when finished using this IDirect3DDevice9 interface results in a memory leak.


IDirect3DBaseTexture9::GetPriority Method

Retrieves the priority for this resource.

Syntax

DWORD GetPriority(VOID);

Return Value

Returns a DWORD value, indicating the priority of the resource.

Remarks

IDirect3DBaseTexture9::GetPriority is used for priority control of managed resources. This method returns 0 on nonmanaged resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::SetPriority, IDirect3DBaseTexture9::SetPriority, IDirect3DCubeTexture9::SetPriority, IDirect3DTexture9::SetPriority, IDirect3DVolumeTexture9::SetPriority, IDirect3DIndexBuffer9::SetPriority, IDirect3DVertexBuffer9::SetPriority


IDirect3DBaseTexture9::GetPrivateData Method

Copies the private data associated with the resource to a provided buffer.

Syntax

HRESULT GetPrivateData(

    REFGUID refguid,
    void *pData,
    DWORD *pSizeOfData
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to retrieve.
pData
[in, out] Pointer to a previously allocated buffer to fill with the requested private data if the call succeeds. The application calling this method is responsible for allocating and releasing this buffer. If this parameter is NULL, this method will return the buffer size in pSizeOfData.
pSizeOfData
[in, out] Pointer to the size of the buffer at pData, in bytes. If this value is less than the actual size of the private data (such as 0), the method sets this parameter to the required buffer size and the method returns D3DERR_MOREDATA.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_MOREDATA | There is more data available than the specified buffer size can hold.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

This method is inherited by the following interfaces: IDirect3DResource9, IDirect3DBaseTexture9, IDirect3DCubeTexture9, IDirect3DTexture9, IDirect3DVolumeTexture9, IDirect3DIndexBuffer9, IDirect3DVertexBuffer9.


IDirect3DBaseTexture9::GetType Method

Returns the type of the resource.

Syntax

D3DRESOURCETYPE GetType(VOID);

Return Value

Returns a member of the D3DRESOURCETYPE enumerated type, identifying the type of the resource.


IDirect3DBaseTexture9::PreLoad Method

Preloads a managed resource.

Syntax

void PreLoad(VOID);

Return Value

No return value.

Remarks

Calling this method indicates that the application will need this managed resource shortly. This method has no effect on nonmanaged resources.

IDirect3DBaseTexture9::PreLoad detects "thrashing" conditions where more resources are being used in each frame than can fit in video memory simultaneously. Under such circumstances IDirect3DBaseTexture9::PreLoad silently does nothing.


IDirect3DBaseTexture9::SetPriority Method

Assigns the resource-management priority for this resource.

Syntax

DWORD SetPriority(

    DWORD PriorityNew
);

Parameters

PriorityNew
[in] DWORD value that specifies the new resource-management priority for the resource.

Return Value

Returns the previous priority value for the resource.

Remarks

IDirect3DBaseTexture9::SetPriority is used for priority control of managed resources. This method returns 0 on non-managed resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::GetPriority, IDirect3DBaseTexture9::GetPriority, IDirect3DCubeTexture9::GetPriority, IDirect3DTexture9::GetPriority, IDirect3DVolumeTexture9::GetPriority, IDirect3DIndexBuffer9::GetPriority, IDirect3DVertexBuffer9::GetPriority


IDirect3DBaseTexture9::SetPrivateData Method

Associates data with the resource that is intended for use by the application, not by Microsoft Direct3D. Data is passed by value, and multiple sets of data can be associated with a single resource.

Syntax

HRESULT SetPrivateData(

    REFGUID refguid,
    const void *pData,
    DWORD SizeOfData,
    DWORD Flags
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to set.
pData
[in] Pointer to a buffer that contains the data to be associated with the resource.
SizeOfData
[in] Size of the buffer at pData, in bytes.
Flags
[in] Value that describes the type of data being passed, or indicates to the application that the data should be invalidated when the resource changes.
(none)
If no flags are specified, Direct3D allocates memory to hold the data within the buffer and copies the data into the new buffer. The buffer allocated by Direct3D is automatically freed, as appropriate.
D3DSPD_IUNKNOWN
The data at pData is a pointer to an IUnknown interface. SizeOfData must be set to the size of a pointer to an IUnknown interface, sizeof(IUnknown*). Direct3D automatically calls IUnknown::AddRef through pData and IUnknown::Release when the private data is destroyed. Private data will be destroyed by a subsequent call to IDirect3DBaseTexture9::SetPrivateData with the same GUID, a subsequent call to IDirect3DResource9::FreePrivateData, or when the IDirect3D9 object is released. For more information, see Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Direct3D does not manage the memory at pData. If this buffer was dynamically allocated, it is the calling application's responsibility to free the memory.

See Also

IDirect3DResource9::FreePrivateData, IDirect3DBaseTexture9::FreePrivateData, IDirect3DCubeTexture9::FreePrivateData, IDirect3DTexture9::FreePrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData, IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData


IDirect3DCubeTexture9::FreePrivateData Method

Frees the specified private data associated with this resource.

Syntax

HRESULT FreePrivateData(

    REFGUID refguid
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to free.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

Microsoft Direct3D calls this method automatically when a resource is released.

See Also

IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::GetPrivateData, IDirect3DIndexBuffer9::GetPrivateData, IDirect3DVertexBuffer9::GetPrivateData, IDirect3DResource9::SetPrivateData, IDirect3DBaseTexture9::SetPrivateData, IDirect3DCubeTexture9::SetPrivateData, IDirect3DTexture9::SetPrivateData, IDirect3DVolumeTexture9::SetPrivateData, IDirect3DIndexBuffer9::SetPrivateData, IDirect3DVertexBuffer9::SetPrivateData


IDirect3DCubeTexture9::GenerateMipSubLevels Method

Generate mipmap sublevels.

Syntax

VOID GenerateMipSubLevels(VOID);

Return Value

No return value.

Remarks

An application can generate mipmap sublevels at any time by calling IDirect3DCubeTexture9::GenerateMipSubLevels. To have mipmap sublevels generated automatically at texture creation time (see Automatic Generation of Mipmaps), specify D3DUSAGE_AUTOGENMIPMAP during IDirect3DDevice9::CreateTexture, IDirect3DDevice9::CreateCubeTexture, and IDirect3DDevice9::CreateVolumeTexture. For more information about usage constants, see D3DUSAGE.

See Also

IDirect3DBaseTexture9::GetAutoGenFilterType, IDirect3DBaseTexture9::SetAutoGenFilterType


IDirect3DCubeTexture9::GetAutoGenFilterType Method

Get the filter type that is used for automatically generated mipmap sublevels.

Syntax

D3DTEXTUREFILTERTYPE GetAutoGenFilterType(VOID);

Return Value

Filter type. See D3DTEXTUREFILTERTYPE. A texture must be created with D3DUSAGE_AUTOGENMIPMAP to use this method. Any other usage value will cause this method to return D3DTEXF_NONE.

Remarks

Changing the filter type "dirties" the mipmap sublevels and causes them to be regenerated.

The (default) filter type set at texture creation time is D3DTEXF_LINEAR. If the driver doesn't support a linear filter, the filter type will be set to D3DTEXF_POINT. All filter types supported by the driver for regular texture filtering are supported for autogeneration except D3DTEXF_NONE. For each resource type, drivers should support all the filter types reported in the corresponding texture, cubetexture, and volumetexture filter caps. For more information about texture types, see D3DTEXTUREFILTERTYPE.

This method has no effect if the texture is not created with D3DUSAGE_AUTOGENMIPMAP.

See Also

IDirect3DBaseTexture9::GenerateMipSubLevels, IDirect3DBaseTexture9::SetAutoGenFilterType


IDirect3DCubeTexture9::GetDevice Method

Retrieves the device associated with a resource.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface to fill with the device pointer, if the query succeeds.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method allows navigation to the owning device object.

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Failure to call IUnknown::Release when finished using this IDirect3DDevice9 interface results in a memory leak.


IDirect3DCubeTexture9::GetLevelCount Method

Returns the number of texture levels in a multilevel texture.

Syntax

DWORD GetLevelCount(VOID);

Return Value

A DWORD value indicating the number of texture levels in a multilevel texture.

Remarks

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture9.

  • IDirect3DCubeTexture9
  • IDirect3DTexture9
  • IDirect3DVolumeTexture9


IDirect3DCubeTexture9::GetLOD Method

Returns a value clamped to the maximum level of detail (LOD) set for a managed texture (this method is not supported for an unmanaged texture).

Syntax

DWORD GetLOD(VOID);

Return Value

A DWORD value, clamped to the maximum LOD value (one less than the total number of levels).

Calling IDirect3DCubeTexture9::GetLOD on an unmanaged texture is not supported and will result in a D3DERR error code being returned.

See Also

IDirect3DBaseTexture9::SetLOD


IDirect3DCubeTexture9::GetPriority Method

Retrieves the priority for this resource.

Syntax

DWORD GetPriority(VOID);

Return Value

Returns a DWORD value, indicating the priority of the resource.

Remarks

IDirect3DCubeTexture9::GetPriority is used for priority control of managed resources. This method returns 0 on nonmanaged resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::SetPriority, IDirect3DBaseTexture9::SetPriority, IDirect3DCubeTexture9::SetPriority, IDirect3DTexture9::SetPriority, IDirect3DVolumeTexture9::SetPriority, IDirect3DIndexBuffer9::SetPriority, IDirect3DVertexBuffer9::SetPriority


IDirect3DCubeTexture9::GetPrivateData Method

Copies the private data associated with the resource to a provided buffer.

Syntax

HRESULT GetPrivateData(

    REFGUID refguid,
    void *pData,
    DWORD *pSizeOfData
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to retrieve.
pData
[in, out] Pointer to a previously allocated buffer to fill with the requested private data if the call succeeds. The application calling this method is responsible for allocating and releasing this buffer. If this parameter is NULL, this method will return the buffer size in pSizeOfData.
pSizeOfData
[in, out] Pointer to the size of the buffer at pData, in bytes. If this value is less than the actual size of the private data (such as 0), the method sets this parameter to the required buffer size and the method returns D3DERR_MOREDATA.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_MOREDATA | There is more data available than the specified buffer size can hold.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

This method is inherited by the following interfaces: IDirect3DResource9, IDirect3DBaseTexture9, IDirect3DCubeTexture9, IDirect3DTexture9, IDirect3DVolumeTexture9, IDirect3DIndexBuffer9, IDirect3DVertexBuffer9.


IDirect3DCubeTexture9::GetType Method

Returns the type of the resource.

Syntax

D3DRESOURCETYPE GetType(VOID);

Return Value

Returns a member of the D3DRESOURCETYPE enumerated type, identifying the type of the resource.


IDirect3DCubeTexture9::PreLoad Method

Preloads a managed resource.

Syntax

void PreLoad(VOID);

Return Value

No return value.

Remarks

Calling this method indicates that the application will need this managed resource shortly. This method has no effect on nonmanaged resources.

IDirect3DCubeTexture9::PreLoad detects "thrashing" conditions where more resources are being used in each frame than can fit in video memory simultaneously. Under such circumstances IDirect3DCubeTexture9::PreLoad silently does nothing.


IDirect3DCubeTexture9::SetAutoGenFilterType Method

Set the filter type that is used for automatically generated mipmap sublevels.

Syntax

HRESULT SetAutoGenFilterType(

    D3DTEXTUREFILTERTYPE FilterType
);

Parameters

FilterType
[in] Filter type. See D3DTEXTUREFILTERTYPE. This method will fail if the filter type is invalid or not supported.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Changing the filter type "dirties" the mipmap sublevels and causes them to be regenerated.

The (default) filter type set at texture creation time is D3DTEXF_LINEAR. If the driver does not support a linear filter, the filter type will be set to D3DTEXF_POINT. All filter types supported by the driver for regular texture filtering are supported for autogeneration except D3DTEXF_NONE. IDirect3DCubeTexture9::SetAutoGenFilterType will fail unless the driver sets the appropriate D3DPTFILTERCAPS_MINFxxx caps. These values are specified in the TextureFilterCaps and/or CubeTextureFilterCaps members of D3DCAPS9. For more information about texture filter types, see D3DTEXTUREFILTERTYPE.

This method has no effect if the texture is not created with D3DUSAGE_AUTOGENMIPMAP. In this case, no failure is returned. For more information about usage constants, see D3DUSAGE.

See Also

IDirect3DBaseTexture9::GenerateMipSubLevels, IDirect3DBaseTexture9::GetAutoGenFilterType


IDirect3DCubeTexture9::SetLOD Method

Sets the most detailed level of detail (LOD) for a managed texture.

Syntax

DWORD SetLOD(

    DWORD LODNew
);

Parameters

LODNew
[in] Most detailed LOD value to set for the mipmap chain.

Return Value

A DWORD value, clamped to the maximum LOD value (one less than the total number of levels). Subsequent calls to this method will return the clamped value, not the LOD value that was previously set.

Remarks

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture9.

  • IDirect3DCubeTexture9
  • IDirect3DTexture9
  • IDirect3DVolumeTexture9
  • IDirect3DResource9

IDirect3DCubeTexture9::SetLOD is used for LOD control of managed textures. This method returns 0 on nonmanaged textures.

IDirect3DCubeTexture9::SetLOD communicates to the Microsoft Direct3D texture manager the most detailed mipmap in the chain that should be loaded into local video memory. For example, in a five-level mipmap chain, setting LODNew to 2 indicates that the texture manager should load only mipmap levels 2 through 4 into local video memory at any given time.

More specifically, if the texture was created with the dimensions of 256x256, setting the most detailed level to 0 indicates that 256×256 is the largest mipmap available, setting the most detailed level to 1 indicates that 128×128 is the largest mipmap available, and so on, up to the most detailed mip level (the smallest texture size) for the chain.

See Also

IDirect3DBaseTexture9::GetLOD


IDirect3DCubeTexture9::SetPriority Method

Assigns the resource-management priority for this resource.

Syntax

DWORD SetPriority(

    DWORD PriorityNew
);

Parameters

PriorityNew
[in] DWORD value that specifies the new resource-management priority for the resource.

Return Value

Returns the previous priority value for the resource.

Remarks

IDirect3DCubeTexture9::SetPriority is used for priority control of managed resources. This method returns 0 on non-managed resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::GetPriority, IDirect3DBaseTexture9::GetPriority, IDirect3DCubeTexture9::GetPriority, IDirect3DTexture9::GetPriority, IDirect3DVolumeTexture9::GetPriority, IDirect3DIndexBuffer9::GetPriority, IDirect3DVertexBuffer9::GetPriority


IDirect3DCubeTexture9::SetPrivateData Method

Associates data with the resource that is intended for use by the application, not by Microsoft Direct3D. Data is passed by value, and multiple sets of data can be associated with a single resource.

Syntax

HRESULT SetPrivateData(

    REFGUID refguid,
    const void *pData,
    DWORD SizeOfData,
    DWORD Flags
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to set.
pData
[in] Pointer to a buffer that contains the data to be associated with the resource.
SizeOfData
[in] Size of the buffer at pData, in bytes.
Flags
[in] Value that describes the type of data being passed, or indicates to the application that the data should be invalidated when the resource changes.
(none)
If no flags are specified, Direct3D allocates memory to hold the data within the buffer and copies the data into the new buffer. The buffer allocated by Direct3D is automatically freed, as appropriate.
D3DSPD_IUNKNOWN
The data at pData is a pointer to an IUnknown interface. SizeOfData must be set to the size of a pointer to an IUnknown interface, sizeof(IUnknown*). Direct3D automatically calls IUnknown::AddRef through pData and IUnknown::Release when the private data is destroyed. Private data will be destroyed by a subsequent call to IDirect3DCubeTexture9::SetPrivateData with the same GUID, a subsequent call to IDirect3DResource9::FreePrivateData, or when the IDirect3D9 object is released. For more information, see Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Direct3D does not manage the memory at pData. If this buffer was dynamically allocated, it is the calling application's responsibility to free the memory.

See Also

IDirect3DResource9::FreePrivateData, IDirect3DBaseTexture9::FreePrivateData, IDirect3DCubeTexture9::FreePrivateData, IDirect3DTexture9::FreePrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData, IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData


IDirect3DIndexBuffer9::FreePrivateData Method

Frees the specified private data associated with this resource.

Syntax

HRESULT FreePrivateData(

    REFGUID refguid
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to free.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

Microsoft Direct3D calls this method automatically when a resource is released.

See Also

IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::GetPrivateData, IDirect3DIndexBuffer9::GetPrivateData, IDirect3DVertexBuffer9::GetPrivateData, IDirect3DResource9::SetPrivateData, IDirect3DBaseTexture9::SetPrivateData, IDirect3DCubeTexture9::SetPrivateData, IDirect3DTexture9::SetPrivateData, IDirect3DVolumeTexture9::SetPrivateData, IDirect3DIndexBuffer9::SetPrivateData, IDirect3DVertexBuffer9::SetPrivateData


IDirect3DIndexBuffer9::GetDevice Method

Retrieves the device associated with a resource.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface to fill with the device pointer, if the query succeeds.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method allows navigation to the owning device object.

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Failure to call IUnknown::Release when finished using this IDirect3DDevice9 interface results in a memory leak.


IDirect3DIndexBuffer9::GetPriority Method

Retrieves the priority for this resource.

Syntax

DWORD GetPriority(VOID);

Return Value

Returns a DWORD value, indicating the priority of the resource.

Remarks

IDirect3DIndexBuffer9::GetPriority is used for priority control of managed resources. This method returns 0 on nonmanaged resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::SetPriority, IDirect3DBaseTexture9::SetPriority, IDirect3DCubeTexture9::SetPriority, IDirect3DTexture9::SetPriority, IDirect3DVolumeTexture9::SetPriority, IDirect3DIndexBuffer9::SetPriority, IDirect3DVertexBuffer9::SetPriority


IDirect3DIndexBuffer9::GetPrivateData Method

Copies the private data associated with the resource to a provided buffer.

Syntax

HRESULT GetPrivateData(

    REFGUID refguid,
    void *pData,
    DWORD *pSizeOfData
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to retrieve.
pData
[in, out] Pointer to a previously allocated buffer to fill with the requested private data if the call succeeds. The application calling this method is responsible for allocating and releasing this buffer. If this parameter is NULL, this method will return the buffer size in pSizeOfData.
pSizeOfData
[in, out] Pointer to the size of the buffer at pData, in bytes. If this value is less than the actual size of the private data (such as 0), the method sets this parameter to the required buffer size and the method returns D3DERR_MOREDATA.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_MOREDATA | There is more data available than the specified buffer size can hold.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

This method is inherited by the following interfaces: IDirect3DResource9, IDirect3DBaseTexture9, IDirect3DCubeTexture9, IDirect3DTexture9, IDirect3DVolumeTexture9, IDirect3DIndexBuffer9, IDirect3DVertexBuffer9.


IDirect3DIndexBuffer9::GetType Method

Returns the type of the resource.

Syntax

D3DRESOURCETYPE GetType(VOID);

Return Value

Returns a member of the D3DRESOURCETYPE enumerated type, identifying the type of the resource.


IDirect3DIndexBuffer9::PreLoad Method

Preloads a managed resource.

Syntax

void PreLoad(VOID);

Return Value

No return value.

Remarks

Calling this method indicates that the application will need this managed resource shortly. This method has no effect on nonmanaged resources.

IDirect3DIndexBuffer9::PreLoad detects "thrashing" conditions where more resources are being used in each frame than can fit in video memory simultaneously. Under such circumstances IDirect3DIndexBuffer9::PreLoad silently does nothing.


IDirect3DIndexBuffer9::SetPriority Method

Assigns the resource-management priority for this resource.

Syntax

DWORD SetPriority(

    DWORD PriorityNew
);

Parameters

PriorityNew
[in] DWORD value that specifies the new resource-management priority for the resource.

Return Value

Returns the previous priority value for the resource.

Remarks

IDirect3DIndexBuffer9::SetPriority is used for priority control of managed resources. This method returns 0 on non-managed resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::GetPriority, IDirect3DBaseTexture9::GetPriority, IDirect3DCubeTexture9::GetPriority, IDirect3DTexture9::GetPriority, IDirect3DVolumeTexture9::GetPriority, IDirect3DIndexBuffer9::GetPriority, IDirect3DVertexBuffer9::GetPriority


IDirect3DIndexBuffer9::SetPrivateData Method

Associates data with the resource that is intended for use by the application, not by Microsoft Direct3D. Data is passed by value, and multiple sets of data can be associated with a single resource.

Syntax

HRESULT SetPrivateData(

    REFGUID refguid,
    const void *pData,
    DWORD SizeOfData,
    DWORD Flags
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to set.
pData
[in] Pointer to a buffer that contains the data to be associated with the resource.
SizeOfData
[in] Size of the buffer at pData, in bytes.
Flags
[in] Value that describes the type of data being passed, or indicates to the application that the data should be invalidated when the resource changes.
(none)
If no flags are specified, Direct3D allocates memory to hold the data within the buffer and copies the data into the new buffer. The buffer allocated by Direct3D is automatically freed, as appropriate.
D3DSPD_IUNKNOWN
The data at pData is a pointer to an IUnknown interface. SizeOfData must be set to the size of a pointer to an IUnknown interface, sizeof(IUnknown*). Direct3D automatically calls IUnknown::AddRef through pData and IUnknown::Release when the private data is destroyed. Private data will be destroyed by a subsequent call to IDirect3DIndexBuffer9::SetPrivateData with the same GUID, a subsequent call to IDirect3DResource9::FreePrivateData, or when the IDirect3D9 object is released. For more information, see Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Direct3D does not manage the memory at pData. If this buffer was dynamically allocated, it is the calling application's responsibility to free the memory.

See Also

IDirect3DResource9::FreePrivateData, IDirect3DBaseTexture9::FreePrivateData, IDirect3DCubeTexture9::FreePrivateData, IDirect3DTexture9::FreePrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData, IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData


IDirect3DSurface9::FreePrivateData Method

Frees the specified private data associated with this resource.

Syntax

HRESULT FreePrivateData(

    REFGUID refguid
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to free.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

Microsoft Direct3D calls this method automatically when a resource is released.

See Also

IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::GetPrivateData, IDirect3DIndexBuffer9::GetPrivateData, IDirect3DVertexBuffer9::GetPrivateData, IDirect3DResource9::SetPrivateData, IDirect3DBaseTexture9::SetPrivateData, IDirect3DCubeTexture9::SetPrivateData, IDirect3DTexture9::SetPrivateData, IDirect3DVolumeTexture9::SetPrivateData, IDirect3DIndexBuffer9::SetPrivateData, IDirect3DVertexBuffer9::SetPrivateData


IDirect3DSurface9::GetDevice Method

Retrieves the device associated with a resource.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface to fill with the device pointer, if the query succeeds.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method allows navigation to the owning device object.

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Failure to call IUnknown::Release when finished using this IDirect3DDevice9 interface results in a memory leak.


IDirect3DSurface9::GetPriority Method

Retrieves the priority for this resource.

Syntax

DWORD GetPriority(VOID);

Return Value

Returns a DWORD value, indicating the priority of the resource.

Remarks

IDirect3DSurface9::GetPriority is used for priority control of managed resources. This method returns 0 on nonmanaged resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::SetPriority, IDirect3DBaseTexture9::SetPriority, IDirect3DCubeTexture9::SetPriority, IDirect3DTexture9::SetPriority, IDirect3DVolumeTexture9::SetPriority, IDirect3DIndexBuffer9::SetPriority, IDirect3DVertexBuffer9::SetPriority


IDirect3DSurface9::GetPrivateData Method

Copies the private data associated with the resource to a provided buffer.

Syntax

HRESULT GetPrivateData(

    REFGUID refguid,
    void *pData,
    DWORD *pSizeOfData
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to retrieve.
pData
[in, out] Pointer to a previously allocated buffer to fill with the requested private data if the call succeeds. The application calling this method is responsible for allocating and releasing this buffer. If this parameter is NULL, this method will return the buffer size in pSizeOfData.
pSizeOfData
[in, out] Pointer to the size of the buffer at pData, in bytes. If this value is less than the actual size of the private data (such as 0), the method sets this parameter to the required buffer size and the method returns D3DERR_MOREDATA.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_MOREDATA | There is more data available than the specified buffer size can hold.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

This method is inherited by the following interfaces: IDirect3DResource9, IDirect3DBaseTexture9, IDirect3DCubeTexture9, IDirect3DTexture9, IDirect3DVolumeTexture9, IDirect3DIndexBuffer9, IDirect3DVertexBuffer9.


IDirect3DSurface9::GetType Method

Returns the type of the resource.

Syntax

D3DRESOURCETYPE GetType(VOID);

Return Value

Returns a member of the D3DRESOURCETYPE enumerated type, identifying the type of the resource.


IDirect3DSurface9::PreLoad Method

Preloads a managed resource.

Syntax

void PreLoad(VOID);

Return Value

No return value.

Remarks

Calling this method indicates that the application will need this managed resource shortly. This method has no effect on nonmanaged resources.

IDirect3DSurface9::PreLoad detects "thrashing" conditions where more resources are being used in each frame than can fit in video memory simultaneously. Under such circumstances IDirect3DSurface9::PreLoad silently does nothing.


IDirect3DSurface9::SetPriority Method

Assigns the resource-management priority for this resource.

Syntax

DWORD SetPriority(

    DWORD PriorityNew
);

Parameters

PriorityNew
[in] DWORD value that specifies the new resource-management priority for the resource.

Return Value

Returns the previous priority value for the resource.

Remarks

IDirect3DSurface9::SetPriority is used for priority control of managed resources. This method returns 0 on non-managed resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::GetPriority, IDirect3DBaseTexture9::GetPriority, IDirect3DCubeTexture9::GetPriority, IDirect3DTexture9::GetPriority, IDirect3DVolumeTexture9::GetPriority, IDirect3DIndexBuffer9::GetPriority, IDirect3DVertexBuffer9::GetPriority


IDirect3DSurface9::SetPrivateData Method

Associates data with the resource that is intended for use by the application, not by Microsoft Direct3D. Data is passed by value, and multiple sets of data can be associated with a single resource.

Syntax

HRESULT SetPrivateData(

    REFGUID refguid,
    const void *pData,
    DWORD SizeOfData,
    DWORD Flags
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to set.
pData
[in] Pointer to a buffer that contains the data to be associated with the resource.
SizeOfData
[in] Size of the buffer at pData, in bytes.
Flags
[in] Value that describes the type of data being passed, or indicates to the application that the data should be invalidated when the resource changes.
(none)
If no flags are specified, Direct3D allocates memory to hold the data within the buffer and copies the data into the new buffer. The buffer allocated by Direct3D is automatically freed, as appropriate.
D3DSPD_IUNKNOWN
The data at pData is a pointer to an IUnknown interface. SizeOfData must be set to the size of a pointer to an IUnknown interface, sizeof(IUnknown*). Direct3D automatically calls IUnknown::AddRef through pData and IUnknown::Release when the private data is destroyed. Private data will be destroyed by a subsequent call to IDirect3DSurface9::SetPrivateData with the same GUID, a subsequent call to IDirect3DResource9::FreePrivateData, or when the IDirect3D9 object is released. For more information, see Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Direct3D does not manage the memory at pData. If this buffer was dynamically allocated, it is the calling application's responsibility to free the memory.

See Also

IDirect3DResource9::FreePrivateData, IDirect3DBaseTexture9::FreePrivateData, IDirect3DCubeTexture9::FreePrivateData, IDirect3DTexture9::FreePrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData, IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData


IDirect3DTexture9::FreePrivateData Method

Frees the specified private data associated with this resource.

Syntax

HRESULT FreePrivateData(

    REFGUID refguid
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to free.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

Microsoft Direct3D calls this method automatically when a resource is released.

See Also

IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::GetPrivateData, IDirect3DIndexBuffer9::GetPrivateData, IDirect3DVertexBuffer9::GetPrivateData, IDirect3DResource9::SetPrivateData, IDirect3DBaseTexture9::SetPrivateData, IDirect3DCubeTexture9::SetPrivateData, IDirect3DTexture9::SetPrivateData, IDirect3DVolumeTexture9::SetPrivateData, IDirect3DIndexBuffer9::SetPrivateData, IDirect3DVertexBuffer9::SetPrivateData


IDirect3DTexture9::GenerateMipSubLevels Method

Generate mipmap sublevels.

Syntax

VOID GenerateMipSubLevels(VOID);

Return Value

No return value.

Remarks

An application can generate mipmap sublevels at any time by calling IDirect3DTexture9::GenerateMipSubLevels. To have mipmap sublevels generated automatically at texture creation time (see Automatic Generation of Mipmaps), specify D3DUSAGE_AUTOGENMIPMAP during IDirect3DDevice9::CreateTexture, IDirect3DDevice9::CreateCubeTexture, and IDirect3DDevice9::CreateVolumeTexture. For more information about usage constants, see D3DUSAGE.

See Also

IDirect3DBaseTexture9::GetAutoGenFilterType, IDirect3DBaseTexture9::SetAutoGenFilterType


IDirect3DTexture9::GetAutoGenFilterType Method

Get the filter type that is used for automatically generated mipmap sublevels.

Syntax

D3DTEXTUREFILTERTYPE GetAutoGenFilterType(VOID);

Return Value

Filter type. See D3DTEXTUREFILTERTYPE. A texture must be created with D3DUSAGE_AUTOGENMIPMAP to use this method. Any other usage value will cause this method to return D3DTEXF_NONE.

Remarks

Changing the filter type "dirties" the mipmap sublevels and causes them to be regenerated.

The (default) filter type set at texture creation time is D3DTEXF_LINEAR. If the driver doesn't support a linear filter, the filter type will be set to D3DTEXF_POINT. All filter types supported by the driver for regular texture filtering are supported for autogeneration except D3DTEXF_NONE. For each resource type, drivers should support all the filter types reported in the corresponding texture, cubetexture, and volumetexture filter caps. For more information about texture types, see D3DTEXTUREFILTERTYPE.

This method has no effect if the texture is not created with D3DUSAGE_AUTOGENMIPMAP.

See Also

IDirect3DBaseTexture9::GenerateMipSubLevels, IDirect3DBaseTexture9::SetAutoGenFilterType


IDirect3DTexture9::GetDevice Method

Retrieves the device associated with a resource.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface to fill with the device pointer, if the query succeeds.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method allows navigation to the owning device object.

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Failure to call IUnknown::Release when finished using this IDirect3DDevice9 interface results in a memory leak.


IDirect3DTexture9::GetLevelCount Method

Returns the number of texture levels in a multilevel texture.

Syntax

DWORD GetLevelCount(VOID);

Return Value

A DWORD value indicating the number of texture levels in a multilevel texture.

Remarks

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture9.

  • IDirect3DCubeTexture9
  • IDirect3DTexture9
  • IDirect3DVolumeTexture9


IDirect3DTexture9::GetLOD Method

Returns a value clamped to the maximum level of detail (LOD) set for a managed texture (this method is not supported for an unmanaged texture).

Syntax

DWORD GetLOD(VOID);

Return Value

A DWORD value, clamped to the maximum LOD value (one less than the total number of levels).

Calling IDirect3DTexture9::GetLOD on an unmanaged texture is not supported and will result in a D3DERR error code being returned.

See Also

IDirect3DBaseTexture9::SetLOD


IDirect3DTexture9::GetPriority Method

Retrieves the priority for this resource.

Syntax

DWORD GetPriority(VOID);

Return Value

Returns a DWORD value, indicating the priority of the resource.

Remarks

IDirect3DTexture9::GetPriority is used for priority control of managed resources. This method returns 0 on nonmanaged resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::SetPriority, IDirect3DBaseTexture9::SetPriority, IDirect3DCubeTexture9::SetPriority, IDirect3DTexture9::SetPriority, IDirect3DVolumeTexture9::SetPriority, IDirect3DIndexBuffer9::SetPriority, IDirect3DVertexBuffer9::SetPriority


IDirect3DTexture9::GetPrivateData Method

Copies the private data associated with the resource to a provided buffer.

Syntax

HRESULT GetPrivateData(

    REFGUID refguid,
    void *pData,
    DWORD *pSizeOfData
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to retrieve.
pData
[in, out] Pointer to a previously allocated buffer to fill with the requested private data if the call succeeds. The application calling this method is responsible for allocating and releasing this buffer. If this parameter is NULL, this method will return the buffer size in pSizeOfData.
pSizeOfData
[in, out] Pointer to the size of the buffer at pData, in bytes. If this value is less than the actual size of the private data (such as 0), the method sets this parameter to the required buffer size and the method returns D3DERR_MOREDATA.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_MOREDATA | There is more data available than the specified buffer size can hold.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

This method is inherited by the following interfaces: IDirect3DResource9, IDirect3DBaseTexture9, IDirect3DCubeTexture9, IDirect3DTexture9, IDirect3DVolumeTexture9, IDirect3DIndexBuffer9, IDirect3DVertexBuffer9.


IDirect3DTexture9::GetType Method

Returns the type of the resource.

Syntax

D3DRESOURCETYPE GetType(VOID);

Return Value

Returns a member of the D3DRESOURCETYPE enumerated type, identifying the type of the resource.


IDirect3DTexture9::PreLoad Method

Preloads a managed resource.

Syntax

void PreLoad(VOID);

Return Value

No return value.

Remarks

Calling this method indicates that the application will need this managed resource shortly. This method has no effect on nonmanaged resources.

IDirect3DTexture9::PreLoad detects "thrashing" conditions where more resources are being used in each frame than can fit in video memory simultaneously. Under such circumstances IDirect3DTexture9::PreLoad silently does nothing.


IDirect3DTexture9::SetAutoGenFilterType Method

Set the filter type that is used for automatically generated mipmap sublevels.

Syntax

HRESULT SetAutoGenFilterType(

    D3DTEXTUREFILTERTYPE FilterType
);

Parameters

FilterType
[in] Filter type. See D3DTEXTUREFILTERTYPE. This method will fail if the filter type is invalid or not supported.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Changing the filter type "dirties" the mipmap sublevels and causes them to be regenerated.

The (default) filter type set at texture creation time is D3DTEXF_LINEAR. If the driver does not support a linear filter, the filter type will be set to D3DTEXF_POINT. All filter types supported by the driver for regular texture filtering are supported for autogeneration except D3DTEXF_NONE. IDirect3DTexture9::SetAutoGenFilterType will fail unless the driver sets the appropriate D3DPTFILTERCAPS_MINFxxx caps. These values are specified in the TextureFilterCaps and/or CubeTextureFilterCaps members of D3DCAPS9. For more information about texture filter types, see D3DTEXTUREFILTERTYPE.

This method has no effect if the texture is not created with D3DUSAGE_AUTOGENMIPMAP. In this case, no failure is returned. For more information about usage constants, see D3DUSAGE.

See Also

IDirect3DBaseTexture9::GenerateMipSubLevels, IDirect3DBaseTexture9::GetAutoGenFilterType


IDirect3DTexture9::SetLOD Method

Sets the most detailed level of detail (LOD) for a managed texture.

Syntax

DWORD SetLOD(

    DWORD LODNew
);

Parameters

LODNew
[in] Most detailed LOD value to set for the mipmap chain.

Return Value

A DWORD value, clamped to the maximum LOD value (one less than the total number of levels). Subsequent calls to this method will return the clamped value, not the LOD value that was previously set.

Remarks

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture9.

  • IDirect3DCubeTexture9
  • IDirect3DTexture9
  • IDirect3DVolumeTexture9
  • IDirect3DResource9

IDirect3DTexture9::SetLOD is used for LOD control of managed textures. This method returns 0 on nonmanaged textures.

IDirect3DTexture9::SetLOD communicates to the Microsoft Direct3D texture manager the most detailed mipmap in the chain that should be loaded into local video memory. For example, in a five-level mipmap chain, setting LODNew to 2 indicates that the texture manager should load only mipmap levels 2 through 4 into local video memory at any given time.

More specifically, if the texture was created with the dimensions of 256x256, setting the most detailed level to 0 indicates that 256×256 is the largest mipmap available, setting the most detailed level to 1 indicates that 128×128 is the largest mipmap available, and so on, up to the most detailed mip level (the smallest texture size) for the chain.

See Also

IDirect3DBaseTexture9::GetLOD


IDirect3DTexture9::SetPriority Method

Assigns the resource-management priority for this resource.

Syntax

DWORD SetPriority(

    DWORD PriorityNew
);

Parameters

PriorityNew
[in] DWORD value that specifies the new resource-management priority for the resource.

Return Value

Returns the previous priority value for the resource.

Remarks

IDirect3DTexture9::SetPriority is used for priority control of managed resources. This method returns 0 on non-managed resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::GetPriority, IDirect3DBaseTexture9::GetPriority, IDirect3DCubeTexture9::GetPriority, IDirect3DTexture9::GetPriority, IDirect3DVolumeTexture9::GetPriority, IDirect3DIndexBuffer9::GetPriority, IDirect3DVertexBuffer9::GetPriority


IDirect3DTexture9::SetPrivateData Method

Associates data with the resource that is intended for use by the application, not by Microsoft Direct3D. Data is passed by value, and multiple sets of data can be associated with a single resource.

Syntax

HRESULT SetPrivateData(

    REFGUID refguid,
    const void *pData,
    DWORD SizeOfData,
    DWORD Flags
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to set.
pData
[in] Pointer to a buffer that contains the data to be associated with the resource.
SizeOfData
[in] Size of the buffer at pData, in bytes.
Flags
[in] Value that describes the type of data being passed, or indicates to the application that the data should be invalidated when the resource changes.
(none)
If no flags are specified, Direct3D allocates memory to hold the data within the buffer and copies the data into the new buffer. The buffer allocated by Direct3D is automatically freed, as appropriate.
D3DSPD_IUNKNOWN
The data at pData is a pointer to an IUnknown interface. SizeOfData must be set to the size of a pointer to an IUnknown interface, sizeof(IUnknown*). Direct3D automatically calls IUnknown::AddRef through pData and IUnknown::Release when the private data is destroyed. Private data will be destroyed by a subsequent call to IDirect3DTexture9::SetPrivateData with the same GUID, a subsequent call to IDirect3DResource9::FreePrivateData, or when the IDirect3D9 object is released. For more information, see Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Direct3D does not manage the memory at pData. If this buffer was dynamically allocated, it is the calling application's responsibility to free the memory.

See Also

IDirect3DResource9::FreePrivateData, IDirect3DBaseTexture9::FreePrivateData, IDirect3DCubeTexture9::FreePrivateData, IDirect3DTexture9::FreePrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData, IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData


IDirect3DVertexBuffer9::FreePrivateData Method

Frees the specified private data associated with this resource.

Syntax

HRESULT FreePrivateData(

    REFGUID refguid
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to free.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

Microsoft Direct3D calls this method automatically when a resource is released.

See Also

IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::GetPrivateData, IDirect3DIndexBuffer9::GetPrivateData, IDirect3DVertexBuffer9::GetPrivateData, IDirect3DResource9::SetPrivateData, IDirect3DBaseTexture9::SetPrivateData, IDirect3DCubeTexture9::SetPrivateData, IDirect3DTexture9::SetPrivateData, IDirect3DVolumeTexture9::SetPrivateData, IDirect3DIndexBuffer9::SetPrivateData, IDirect3DVertexBuffer9::SetPrivateData


IDirect3DVertexBuffer9::GetDevice Method

Retrieves the device associated with a resource.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface to fill with the device pointer, if the query succeeds.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method allows navigation to the owning device object.

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Failure to call IUnknown::Release when finished using this IDirect3DDevice9 interface results in a memory leak.


IDirect3DVertexBuffer9::GetPriority Method

Retrieves the priority for this resource.

Syntax

DWORD GetPriority(VOID);

Return Value

Returns a DWORD value, indicating the priority of the resource.

Remarks

IDirect3DVertexBuffer9::GetPriority is used for priority control of managed resources. This method returns 0 on nonmanaged resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::SetPriority, IDirect3DBaseTexture9::SetPriority, IDirect3DCubeTexture9::SetPriority, IDirect3DTexture9::SetPriority, IDirect3DVolumeTexture9::SetPriority, IDirect3DIndexBuffer9::SetPriority, IDirect3DVertexBuffer9::SetPriority


IDirect3DVertexBuffer9::GetPrivateData Method

Copies the private data associated with the resource to a provided buffer.

Syntax

HRESULT GetPrivateData(

    REFGUID refguid,
    void *pData,
    DWORD *pSizeOfData
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to retrieve.
pData
[in, out] Pointer to a previously allocated buffer to fill with the requested private data if the call succeeds. The application calling this method is responsible for allocating and releasing this buffer. If this parameter is NULL, this method will return the buffer size in pSizeOfData.
pSizeOfData
[in, out] Pointer to the size of the buffer at pData, in bytes. If this value is less than the actual size of the private data (such as 0), the method sets this parameter to the required buffer size and the method returns D3DERR_MOREDATA.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_MOREDATA | There is more data available than the specified buffer size can hold.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

This method is inherited by the following interfaces: IDirect3DResource9, IDirect3DBaseTexture9, IDirect3DCubeTexture9, IDirect3DTexture9, IDirect3DVolumeTexture9, IDirect3DIndexBuffer9, IDirect3DVertexBuffer9.


IDirect3DVertexBuffer9::GetType Method

Returns the type of the resource.

Syntax

D3DRESOURCETYPE GetType(VOID);

Return Value

Returns a member of the D3DRESOURCETYPE enumerated type, identifying the type of the resource.


IDirect3DVertexBuffer9::PreLoad Method

Preloads a managed resource.

Syntax

void PreLoad(VOID);

Return Value

No return value.

Remarks

Calling this method indicates that the application will need this managed resource shortly. This method has no effect on nonmanaged resources.

IDirect3DVertexBuffer9::PreLoad detects "thrashing" conditions where more resources are being used in each frame than can fit in video memory simultaneously. Under such circumstances IDirect3DVertexBuffer9::PreLoad silently does nothing.


IDirect3DVertexBuffer9::SetPriority Method

Assigns the resource-management priority for this resource.

Syntax

DWORD SetPriority(

    DWORD PriorityNew
);

Parameters

PriorityNew
[in] DWORD value that specifies the new resource-management priority for the resource.

Return Value

Returns the previous priority value for the resource.

Remarks

IDirect3DVertexBuffer9::SetPriority is used for priority control of managed resources. This method returns 0 on non-managed resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::GetPriority, IDirect3DBaseTexture9::GetPriority, IDirect3DCubeTexture9::GetPriority, IDirect3DTexture9::GetPriority, IDirect3DVolumeTexture9::GetPriority, IDirect3DIndexBuffer9::GetPriority, IDirect3DVertexBuffer9::GetPriority


IDirect3DVertexBuffer9::SetPrivateData Method

Associates data with the resource that is intended for use by the application, not by Microsoft Direct3D. Data is passed by value, and multiple sets of data can be associated with a single resource.

Syntax

HRESULT SetPrivateData(

    REFGUID refguid,
    const void *pData,
    DWORD SizeOfData,
    DWORD Flags
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to set.
pData
[in] Pointer to a buffer that contains the data to be associated with the resource.
SizeOfData
[in] Size of the buffer at pData, in bytes.
Flags
[in] Value that describes the type of data being passed, or indicates to the application that the data should be invalidated when the resource changes.
(none)
If no flags are specified, Direct3D allocates memory to hold the data within the buffer and copies the data into the new buffer. The buffer allocated by Direct3D is automatically freed, as appropriate.
D3DSPD_IUNKNOWN
The data at pData is a pointer to an IUnknown interface. SizeOfData must be set to the size of a pointer to an IUnknown interface, sizeof(IUnknown*). Direct3D automatically calls IUnknown::AddRef through pData and IUnknown::Release when the private data is destroyed. Private data will be destroyed by a subsequent call to IDirect3DVertexBuffer9::SetPrivateData with the same GUID, a subsequent call to IDirect3DResource9::FreePrivateData, or when the IDirect3D9 object is released. For more information, see Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Direct3D does not manage the memory at pData. If this buffer was dynamically allocated, it is the calling application's responsibility to free the memory.

See Also

IDirect3DResource9::FreePrivateData, IDirect3DBaseTexture9::FreePrivateData, IDirect3DCubeTexture9::FreePrivateData, IDirect3DTexture9::FreePrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData, IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData


IDirect3DVolumeTexture9::FreePrivateData Method

Frees the specified private data associated with this resource.

Syntax

HRESULT FreePrivateData(

    REFGUID refguid
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to free.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

Microsoft Direct3D calls this method automatically when a resource is released.

See Also

IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::GetPrivateData, IDirect3DIndexBuffer9::GetPrivateData, IDirect3DVertexBuffer9::GetPrivateData, IDirect3DResource9::SetPrivateData, IDirect3DBaseTexture9::SetPrivateData, IDirect3DCubeTexture9::SetPrivateData, IDirect3DTexture9::SetPrivateData, IDirect3DVolumeTexture9::SetPrivateData, IDirect3DIndexBuffer9::SetPrivateData, IDirect3DVertexBuffer9::SetPrivateData


IDirect3DVolumeTexture9::GenerateMipSubLevels Method

Generate mipmap sublevels.

Syntax

VOID GenerateMipSubLevels(VOID);

Return Value

No return value.

Remarks

An application can generate mipmap sublevels at any time by calling IDirect3DVolumeTexture9::GenerateMipSubLevels. To have mipmap sublevels generated automatically at texture creation time (see Automatic Generation of Mipmaps), specify D3DUSAGE_AUTOGENMIPMAP during IDirect3DDevice9::CreateTexture, IDirect3DDevice9::CreateCubeTexture, and IDirect3DDevice9::CreateVolumeTexture. For more information about usage constants, see D3DUSAGE.

See Also

IDirect3DBaseTexture9::GetAutoGenFilterType, IDirect3DBaseTexture9::SetAutoGenFilterType


IDirect3DVolumeTexture9::GetAutoGenFilterType Method

Get the filter type that is used for automatically generated mipmap sublevels.

Syntax

D3DTEXTUREFILTERTYPE GetAutoGenFilterType(VOID);

Return Value

Filter type. See D3DTEXTUREFILTERTYPE. A texture must be created with D3DUSAGE_AUTOGENMIPMAP to use this method. Any other usage value will cause this method to return D3DTEXF_NONE.

Remarks

Changing the filter type "dirties" the mipmap sublevels and causes them to be regenerated.

The (default) filter type set at texture creation time is D3DTEXF_LINEAR. If the driver doesn't support a linear filter, the filter type will be set to D3DTEXF_POINT. All filter types supported by the driver for regular texture filtering are supported for autogeneration except D3DTEXF_NONE. For each resource type, drivers should support all the filter types reported in the corresponding texture, cubetexture, and volumetexture filter caps. For more information about texture types, see D3DTEXTUREFILTERTYPE.

This method has no effect if the texture is not created with D3DUSAGE_AUTOGENMIPMAP.

See Also

IDirect3DBaseTexture9::GenerateMipSubLevels, IDirect3DBaseTexture9::SetAutoGenFilterType


IDirect3DVolumeTexture9::GetDevice Method

Retrieves the device associated with a resource.

Syntax

HRESULT GetDevice(

    IDirect3DDevice9 **ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface to fill with the device pointer, if the query succeeds.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method allows navigation to the owning device object.

Note Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Failure to call IUnknown::Release when finished using this IDirect3DDevice9 interface results in a memory leak.


IDirect3DVolumeTexture9::GetLevelCount Method

Returns the number of texture levels in a multilevel texture.

Syntax

DWORD GetLevelCount(VOID);

Return Value

A DWORD value indicating the number of texture levels in a multilevel texture.

Remarks

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture9.

  • IDirect3DCubeTexture9
  • IDirect3DTexture9
  • IDirect3DVolumeTexture9


IDirect3DVolumeTexture9::GetLOD Method

Returns a value clamped to the maximum level of detail (LOD) set for a managed texture (this method is not supported for an unmanaged texture).

Syntax

DWORD GetLOD(VOID);

Return Value

A DWORD value, clamped to the maximum LOD value (one less than the total number of levels).

Calling IDirect3DVolumeTexture9::GetLOD on an unmanaged texture is not supported and will result in a D3DERR error code being returned.

See Also

IDirect3DBaseTexture9::SetLOD


IDirect3DVolumeTexture9::GetPriority Method

Retrieves the priority for this resource.

Syntax

DWORD GetPriority(VOID);

Return Value

Returns a DWORD value, indicating the priority of the resource.

Remarks

IDirect3DVolumeTexture9::GetPriority is used for priority control of managed resources. This method returns 0 on nonmanaged resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::SetPriority, IDirect3DBaseTexture9::SetPriority, IDirect3DCubeTexture9::SetPriority, IDirect3DTexture9::SetPriority, IDirect3DVolumeTexture9::SetPriority, IDirect3DIndexBuffer9::SetPriority, IDirect3DVertexBuffer9::SetPriority


IDirect3DVolumeTexture9::GetPrivateData Method

Copies the private data associated with the resource to a provided buffer.

Syntax

HRESULT GetPrivateData(

    REFGUID refguid,
    void *pData,
    DWORD *pSizeOfData
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to retrieve.
pData
[in, out] Pointer to a previously allocated buffer to fill with the requested private data if the call succeeds. The application calling this method is responsible for allocating and releasing this buffer. If this parameter is NULL, this method will return the buffer size in pSizeOfData.
pSizeOfData
[in, out] Pointer to the size of the buffer at pData, in bytes. If this value is less than the actual size of the private data (such as 0), the method sets this parameter to the required buffer size and the method returns D3DERR_MOREDATA.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_MOREDATA | There is more data available than the specified buffer size can hold.
D3DERR_NOTFOUND | The requested item was not found.

Remarks

This method is inherited by the following interfaces: IDirect3DResource9, IDirect3DBaseTexture9, IDirect3DCubeTexture9, IDirect3DTexture9, IDirect3DVolumeTexture9, IDirect3DIndexBuffer9, IDirect3DVertexBuffer9.


IDirect3DVolumeTexture9::GetType Method

Returns the type of the resource.

Syntax

D3DRESOURCETYPE GetType(VOID);

Return Value

Returns a member of the D3DRESOURCETYPE enumerated type, identifying the type of the resource.


IDirect3DVolumeTexture9::PreLoad Method

Preloads a managed resource.

Syntax

void PreLoad(VOID);

Return Value

No return value.

Remarks

Calling this method indicates that the application will need this managed resource shortly. This method has no effect on nonmanaged resources.

IDirect3DVolumeTexture9::PreLoad detects "thrashing" conditions where more resources are being used in each frame than can fit in video memory simultaneously. Under such circumstances IDirect3DVolumeTexture9::PreLoad silently does nothing.


IDirect3DVolumeTexture9::SetAutoGenFilterType Method

Set the filter type that is used for automatically generated mipmap sublevels.

Syntax

HRESULT SetAutoGenFilterType(

    D3DTEXTUREFILTERTYPE FilterType
);

Parameters

FilterType
[in] Filter type. See D3DTEXTUREFILTERTYPE. This method will fail if the filter type is invalid or not supported.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Changing the filter type "dirties" the mipmap sublevels and causes them to be regenerated.

The (default) filter type set at texture creation time is D3DTEXF_LINEAR. If the driver does not support a linear filter, the filter type will be set to D3DTEXF_POINT. All filter types supported by the driver for regular texture filtering are supported for autogeneration except D3DTEXF_NONE. IDirect3DVolumeTexture9::SetAutoGenFilterType will fail unless the driver sets the appropriate D3DPTFILTERCAPS_MINFxxx caps. These values are specified in the TextureFilterCaps and/or CubeTextureFilterCaps members of D3DCAPS9. For more information about texture filter types, see D3DTEXTUREFILTERTYPE.

This method has no effect if the texture is not created with D3DUSAGE_AUTOGENMIPMAP. In this case, no failure is returned. For more information about usage constants, see D3DUSAGE.

See Also

IDirect3DBaseTexture9::GenerateMipSubLevels, IDirect3DBaseTexture9::GetAutoGenFilterType


IDirect3DVolumeTexture9::SetLOD Method

Sets the most detailed level of detail (LOD) for a managed texture.

Syntax

DWORD SetLOD(

    DWORD LODNew
);

Parameters

LODNew
[in] Most detailed LOD value to set for the mipmap chain.

Return Value

A DWORD value, clamped to the maximum LOD value (one less than the total number of levels). Subsequent calls to this method will return the clamped value, not the LOD value that was previously set.

Remarks

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture9.

  • IDirect3DCubeTexture9
  • IDirect3DTexture9
  • IDirect3DVolumeTexture9
  • IDirect3DResource9

IDirect3DVolumeTexture9::SetLOD is used for LOD control of managed textures. This method returns 0 on nonmanaged textures.

IDirect3DVolumeTexture9::SetLOD communicates to the Microsoft Direct3D texture manager the most detailed mipmap in the chain that should be loaded into local video memory. For example, in a five-level mipmap chain, setting LODNew to 2 indicates that the texture manager should load only mipmap levels 2 through 4 into local video memory at any given time.

More specifically, if the texture was created with the dimensions of 256x256, setting the most detailed level to 0 indicates that 256×256 is the largest mipmap available, setting the most detailed level to 1 indicates that 128×128 is the largest mipmap available, and so on, up to the most detailed mip level (the smallest texture size) for the chain.

See Also

IDirect3DBaseTexture9::GetLOD


IDirect3DVolumeTexture9::SetPriority Method

Assigns the resource-management priority for this resource.

Syntax

DWORD SetPriority(

    DWORD PriorityNew
);

Parameters

PriorityNew
[in] DWORD value that specifies the new resource-management priority for the resource.

Return Value

Returns the previous priority value for the resource.

Remarks

IDirect3DVolumeTexture9::SetPriority is used for priority control of managed resources. This method returns 0 on non-managed resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

See Also

IDirect3DResource9::GetPriority, IDirect3DBaseTexture9::GetPriority, IDirect3DCubeTexture9::GetPriority, IDirect3DTexture9::GetPriority, IDirect3DVolumeTexture9::GetPriority, IDirect3DIndexBuffer9::GetPriority, IDirect3DVertexBuffer9::GetPriority


IDirect3DVolumeTexture9::SetPrivateData Method

Associates data with the resource that is intended for use by the application, not by Microsoft Direct3D. Data is passed by value, and multiple sets of data can be associated with a single resource.

Syntax

HRESULT SetPrivateData(

    REFGUID refguid,
    const void *pData,
    DWORD SizeOfData,
    DWORD Flags
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to set.
pData
[in] Pointer to a buffer that contains the data to be associated with the resource.
SizeOfData
[in] Size of the buffer at pData, in bytes.
Flags
[in] Value that describes the type of data being passed, or indicates to the application that the data should be invalidated when the resource changes.
(none)
If no flags are specified, Direct3D allocates memory to hold the data within the buffer and copies the data into the new buffer. The buffer allocated by Direct3D is automatically freed, as appropriate.
D3DSPD_IUNKNOWN
The data at pData is a pointer to an IUnknown interface. SizeOfData must be set to the size of a pointer to an IUnknown interface, sizeof(IUnknown*). Direct3D automatically calls IUnknown::AddRef through pData and IUnknown::Release when the private data is destroyed. Private data will be destroyed by a subsequent call to IDirect3DVolumeTexture9::SetPrivateData with the same GUID, a subsequent call to IDirect3DResource9::FreePrivateData, or when the IDirect3D9 object is released. For more information, see Remarks.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Direct3D could not allocate sufficient memory to complete the call.

Remarks

Direct3D does not manage the memory at pData. If this buffer was dynamically allocated, it is the calling application's responsibility to free the memory.

See Also

IDirect3DResource9::FreePrivateData, IDirect3DBaseTexture9::FreePrivateData, IDirect3DCubeTexture9::FreePrivateData, IDirect3DTexture9::FreePrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData, IDirect3DResource9::GetPrivateData, IDirect3DBaseTexture9::GetPrivateData, IDirect3DCubeTexture9::GetPrivateData, IDirect3DTexture9::GetPrivateData, IDirect3DVolumeTexture9::FreePrivateData, IDirect3DIndexBuffer9::FreePrivateData, IDirect3DVertexBuffer9::FreePrivateData


D3DDECL_END Macro

Initialize the last vertex element in a vertex declaration array.

Syntax

#define D3DDECL_END() {0xFF,0,D3DDECLTYPE_UNUSED, 0,0,0}

Remarks

This is used to initialize the last vertex element in a vertex declaration array.

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98


D3DGETDATA_FLUSH Macro

This macro creates the value passed to IDirect3DQuery9::GetData to flush query data.

Syntax

#define D3DGETDATA_FLUSH (1 << 0)

Remarks

For more information about using queries, see Queries.

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98


D3DISSUE_BEGIN Macro

This macro creates a value used by IDirect3DQuery9::Issue to issue a query begin.

Syntax

#define D3DISSUE_BEGIN (1 << 1)

Remarks

D3DISSUE_BEGIN is valid for the following query type.

  • D3DQUERYTYPE_OCCLUSION

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DISSUE_END, D3DGETDATA_FLUSH, D3DQUERYTYPE


D3DISSUE_END Macro

This macro creates a value used by IDirect3DQuery9::Issue to issue a query end.

Syntax

#define D3DISSUE_END (1 << 0)

Remarks

This macro changes the query state to nonsignaled.

D3DISSUE_END is valid for the following query types.

  • D3DQUERYTYPE_VCACHE
  • D3DQUERYTYPE_RESOURCEMANAGER
  • D3DQUERYTYPE_VERTEXSTATS
  • D3DQUERYTYPE_EVENT
  • D3DQUERYTYPE_OCCLUSION

Macro Information

Header | d3d9types.h
Minimum operating systems | Windows 98

See Also

D3DISSUE_BEGIN, D3DQUERYTYPE


D3DCOLOR
Microsoft DirectX 9.0 SDK Update (October 2004)

D3DCOLOR

Defines the fundamental Microsoft Direct3D color type.

D3DCOLOR is defined as:

typedef DWORD D3DCOLOR

To use this type, include d3d9types.h in your project.


ID3DXCompressedAnimationSet::GetAnimationIndexByName Method

Gets the index of an animation, given its name.

Syntax

HRESULT GetAnimationIndexByName(

    LPCSTR pName,
    UINT *pIndex
);

Parameters

pName
[in] Name of the animation.
pIndex
[out] Pointer to the animation index.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR.


ID3DXCompressedAnimationSet::GetAnimationNameByIndex Method

Gets the name of an animation, given its index.

Syntax

HRESULT GetAnimationNameByIndex(

    UINT Index,
    LPCSTR *ppName
);

Parameters

Index
[in] Index of the animation.
ppName
[out] Address of a pointer to a string that receives the animation name.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR.


ID3DXCompressedAnimationSet::GetCallback Method

Gets information about a specific callback in the animation set.

Syntax

HRESULT GetCallback(

    DOUBLE Position,
    DWORD Flags,
    DOUBLE *pCallbackPosition,
    LPVOID *ppCallbackData
);

Parameters

Position
[in] Position from which to find callbacks.
Flags
[in] Callback search flags. This parameter can be set to a combination of one or more flags from D3DXCALLBACK_SEARCH_FLAGS.
pCallbackPosition
[out] Pointer to the position of the callback.
ppCallbackData
[out] Address of the callback data pointer.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR.


ID3DXCompressedAnimationSet::GetName Method

Gets the animation set name.

Syntax

LPCSTR GetName(VOID);

Return Value

Name of the animation set.


ID3DXCompressedAnimationSet::GetNumAnimations Method

Gets the number of animations in the animation set.

Syntax

UINT GetNumAnimations(VOID);

Return Value

Number of animations in the animation set.


ID3DXCompressedAnimationSet::GetPeriod Method

Gets the period of the animation set.

Syntax

DOUBLE GetPeriod(VOID);

Return Value

Period of the animation set.

Remarks

The period is the range of time that the animation key frames are valid. For looping animations, this is the period of the loop. The time units that the key frames are specified in (for example, seconds) is determined by the application.


ID3DXCompressedAnimationSet::GetPeriodicPosition Method

Returns time position in the local timeframe of an animation set.

Syntax

DOUBLE GetPeriodicPosition(

    DOUBLE Position
);

Parameters

Position
[in] Local time of the animation set.

Return Value

Time position as measured in the timeframe of the animation set. This value will be bounded by the period of the animation set.

Remarks

The time position returned by this method can be used as the PeriodicPosition parameter of ID3DXAnimationSet::GetSRT.


ID3DXCompressedAnimationSet::GetSRT Method

Gets the scale, rotation, and translation values of the animation set.

Syntax

HRESULT GetSRT(

    DOUBLE PeriodicPosition,
    UINT Animation,
    D3DXVECTOR3 *pScale,
    D3DXQUATERNION *pRotation,
    D3DXVECTOR3 *pTranslation
);

Parameters

PeriodicPosition
[in] Position of the animation set. The position can be obtained by calling ID3DXAnimationSet::GetPeriodicPosition.
Animation
[in] Animation index.
pScale
[out] Pointer to the D3DXVECTOR3 vector that describes the scale of the animation set.
pRotation
[out] Pointer to the D3DXQUATERNION quaternion that describes the rotation of the animation set.
pTranslation
[out] Pointer to the D3DXVECTOR3 vector that describes the translation of the animation set.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR.


ID3DXKeyframedAnimationSet::GetAnimationIndexByName Method

Gets the index of an animation, given its name.

Syntax

HRESULT GetAnimationIndexByName(

    LPCSTR pName,
    UINT *pIndex
);

Parameters

pName
[in] Name of the animation.
pIndex
[out] Pointer to the animation index.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR.


ID3DXKeyframedAnimationSet::GetAnimationNameByIndex Method

Gets the name of an animation, given its index.

Syntax

HRESULT GetAnimationNameByIndex(

    UINT Index,
    LPCSTR *ppName
);

Parameters

Index
[in] Index of the animation.
ppName
[out] Address of a pointer to a string that receives the animation name.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR.


ID3DXKeyframedAnimationSet::GetCallback Method

Gets information about a specific callback in the animation set.

Syntax

HRESULT GetCallback(

    DOUBLE Position,
    DWORD Flags,
    DOUBLE *pCallbackPosition,
    LPVOID *ppCallbackData
);

Parameters

Position
[in] Position from which to find callbacks.
Flags
[in] Callback search flags. This parameter can be set to a combination of one or more flags from D3DXCALLBACK_SEARCH_FLAGS.
pCallbackPosition
[out] Pointer to the position of the callback.
ppCallbackData
[out] Address of the callback data pointer.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR.


ID3DXKeyframedAnimationSet::GetName Method

Gets the animation set name.

Syntax

LPCSTR GetName(VOID);

Return Value

Name of the animation set.


ID3DXKeyframedAnimationSet::GetNumAnimations Method

Gets the number of animations in the animation set.

Syntax

UINT GetNumAnimations(VOID);

Return Value

Number of animations in the animation set.


ID3DXKeyframedAnimationSet::GetPeriod Method

Gets the period of the animation set.

Syntax

DOUBLE GetPeriod(VOID);

Return Value

Period of the animation set.

Remarks

The period is the range of time that the animation key frames are valid. For looping animations, this is the period of the loop. The time units that the key frames are specified in (for example, seconds) is determined by the application.


ID3DXKeyframedAnimationSet::GetPeriodicPosition Method

Returns time position in the local timeframe of an animation set.

Syntax

DOUBLE GetPeriodicPosition(

    DOUBLE Position
);

Parameters

Position
[in] Local time of the animation set.

Return Value

Time position as measured in the timeframe of the animation set. This value will be bounded by the period of the animation set.

Remarks

The time position returned by this method can be used as the PeriodicPosition parameter of ID3DXAnimationSet::GetSRT.


ID3DXKeyframedAnimationSet::GetSRT Method

Gets the scale, rotation, and translation values of the animation set.

Syntax

HRESULT GetSRT(

    DOUBLE PeriodicPosition,
    UINT Animation,
    D3DXVECTOR3 *pScale,
    D3DXQUATERNION *pRotation,
    D3DXVECTOR3 *pTranslation
);

Parameters

PeriodicPosition
[in] Position of the animation set. The position can be obtained by calling ID3DXAnimationSet::GetPeriodicPosition.
Animation
[in] Animation index.
pScale
[out] Pointer to the D3DXVECTOR3 vector that describes the scale of the animation set.
pRotation
[out] Pointer to the D3DXQUATERNION quaternion that describes the rotation of the animation set.
pTranslation
[out] Pointer to the D3DXVECTOR3 vector that describes the translation of the animation set.

Return Value

The return values of this method are implemented by an application programmer. In general, if no error occurs, program the method to return D3D_OK. Otherwise, program the method to return an appropriate error message from D3DERR or D3DXERR.


ID3DXMesh::CloneMesh Method

Clones a mesh using a declarator.

Syntax

HRESULT CloneMesh(

    DWORD Options,
    const D3DVERTEXELEMENT9 *pDeclaration,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXMESH *ppCloneMesh
);

Parameters

Options
[in] A combination of one or more D3DXMESH flags specifying creation options for the mesh.
pDeclaration
[in] An array of D3DVERTEXELEMENT9 elements, which specify the vertex format for the vertices in the output mesh.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device object associated with the mesh.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXMesh interface, representing the cloned mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

ID3DXBaseMesh::CloneMesh is used to reformat and change the vertex data layout. This is done by creating a new mesh object. For example, use it to add space for normals, texture coordinates, colors, weights, etc. that were not present before.

ID3DXBaseMesh::UpdateSemantics updates the vertex declaration with different semantic information without changing the layout of the vertex buffer. This method does not modify the contents of the vertex buffer. For example, use it to relabel a 3-D texture coordinate as a binormal or tangent or vice versa.

See Also

ID3DXBaseMesh::CloneMeshFVF, ID3DXBaseMesh::GetDeclaration, ID3DXMesh::GetDeclaration, ID3DXPMesh::GetDeclaration, D3DXDeclaratorFromFVF


ID3DXMesh::CloneMeshFVF Method

Clones a mesh using a flexible vertex format (FVF) code.

Syntax

HRESULT CloneMeshFVF(

    DWORD Options,
    DWORD FVF,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXMESH *ppCloneMesh
);

Parameters

Options
[in] A combination of one or more D3DXMESH flags specifying creation options for the mesh.
FVF
[in] Combination of FVF codes, which specifies the vertex format for the vertices in the output mesh. For the values of the codes, see D3DFVF.
pDevice
[in] Pointer to an IDirect3DDevice9 interface representing the device object associated with the mesh.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXMesh interface, representing the cloned mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

ID3DXBaseMesh::CloneMeshFVF is used to reformat and change the vertex data layout. This is done by creating a new mesh object. For example, use it to to add space for normals, texture coordinates, colors, weights, etc. that were not present before.

ID3DXBaseMesh::UpdateSemantics updates the vertex declaration with different semantic information without changing the layout of the vertex buffer. This method does not modify the contents of the vertex buffer. For example, use it to relabel a 3-D texture coordinate as a binormal or tangent or vice versa.

See Also

ID3DXBaseMesh::CloneMesh, ID3DXBaseMesh::GetFVF, ID3DXMesh::GetFVF, ID3DXPMesh::GetFVF, D3DXFVFFromDeclarator


ID3DXMesh::ConvertAdjacencyToPointReps Method

Converts mesh adjacency information to an array of point representatives.

Syntax

HRESULT ConvertAdjacencyToPointReps(

    CONST DWORD* pAdjacency,
    DWORD* pPRep
);

Parameters

pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh. The number of bytes in this array must be at least 3 * ID3DXBaseMesh::GetNumFaces * sizeof(DWORD).
pPRep
[in, out] Pointer to an array of one DWORD per vertex of the mesh that will be filled with point representative data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

See Also

ID3DXBaseMesh::ConvertPointRepsToAdjacency, ID3DXMesh::ConvertPointRepsToAdjacency, ID3DXPMesh::ConvertPointRepsToAdjacency


ID3DXMesh::ConvertPointRepsToAdjacency Method

Converts point representative data to mesh adjacency information.

Syntax

HRESULT ConvertPointRepsToAdjacency(

    CONST DWORD* pPRep,
    DWORD* pAdjacency
);

Parameters

pPRep
[in] Pointer to an array of one DWORD per vertex of the mesh that contains point representative data. This parameter is optional. Supplying a NULL value will cause this parameter to be interpreted as an "identity" array.
pAdjacency
[in, out] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh. The number of bytes in this array must be at least 3 * ID3DXBaseMesh::GetNumFaces * sizeof(DWORD).

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

See Also

ID3DXBaseMesh::ConvertAdjacencyToPointReps, ID3DXMesh::ConvertAdjacencyToPointReps, ID3DXPMesh::ConvertAdjacencyToPointReps


ID3DXMesh::DrawSubset Method

Draws a subset of a mesh.

Syntax

HRESULT DrawSubset(

    DWORD AttribId
);

Parameters

AttribId
[in] DWORD that specifies which subset of the mesh to draw. This value is used to differentiate faces in a mesh as belonging to one or more attribute groups.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

An attribute table is used to identify areas of the mesh that need to be drawn with different textures, render states, materials, and so on. In addition, the application can use the attribute table to hide portions of a mesh by not drawing a given attribute identifier (AttribId) when drawing the frame.

See Also

ID3DXBaseMesh::GetAttributeTable, ID3DXMesh::GetAttributeTable, ID3DXPMesh::GetAttributeTable


ID3DXMesh::GenerateAdjacency Method

Generate a list of mesh edges and the faces that share each edge.

Syntax

HRESULT GenerateAdjacency(

    FLOAT Epsilon,
    DWORD *pAdjacency
);

Parameters

Epsilon
[in] Specifies that vertices that differ in position by less than epsilon should be treated as coincident.
pAdjacency
[in] Pointer to an array of three DWORDs per face to be filled with adjacent face indices. The number of bytes in this array must be at least 3 * ID3DXBaseMesh::GetNumFaces * sizeof(DWORD).

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

After an application generates adjacency information for a mesh, the mesh data can be optimized for better drawing performance.

See Also

ID3DXMesh::Optimize, ID3DXMesh::OptimizeInplace


ID3DXMesh::GetAttributeTable Method

Retrieves either an attribute table for a mesh, or the number of entries stored in an attribute table for a mesh.

Syntax

HRESULT GetAttributeTable(

    D3DXATTRIBUTERANGE *pAttribTable,
    DWORD *pAttribTableSize
);

Parameters

pAttribTable
[in, out] Pointer to an array of D3DXATTRIBUTERANGE structures, representing the entries in the mesh's attribute table. Specify NULL to retrieve the value for pAttribTableSize.
pAttribTableSize
[in, out] Pointer to either the number of entries stored in pAttribTable or a value to be filled in with the number of entries stored in the attribute table for the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

An attribute table is created by ID3DXMesh::Optimize and passing D3DXMESHOPT_ATTRSORT for the Flags parameter.

An attribute table is used to identify areas of the mesh that need to be drawn with different textures, render states, materials, and so on. In addition, the application can use the attribute table to hide portions of a mesh by not drawing a given attribute identifier when drawing the frame.


ID3DXMesh::GetDeclaration Method

Retrieves a declaration describing the vertices in the mesh.

Syntax

HRESULT GetDeclaration(

    D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

Declaration
[in, out] Array of D3DVERTEXELEMENT9 elements describing the vertex format of the mesh vertices. The upper limit of this declarator array is MAX_FVF_DECL_SIZE. The vertex element array ends with the D3DDECL_END macro.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The array of elements includes the D3DDECL_END macro, which ends the declaration.

See Also

ID3DXBaseMesh::GetFVF, ID3DXMesh::GetFVF, ID3DXPMesh::GetFVF


ID3DXMesh::GetDevice Method

Retrieves the device associated with the mesh.

Syntax

HRESULT GetDevice(

    LPDIRECT3DDEVICE9 *ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface, representing the Microsoft Direct3D device object associated with the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Be sure to call IUnknown::Release when you are done using this IDirect3DDevice9 interface or you will have a memory leak.


ID3DXMesh::GetFVF Method

Gets the fixed function vertex value.

Syntax

DWORD GetFVF(VOID);

Return Value

Returns the flexible vertex format (FVF) codes.

Remarks

This method can return 0 if the vertex format cannot be mapped directly to an FVF code. This will occur for a mesh created from a vertex declaration that doesn't have the same order and elements supported by the FVF codes.


ID3DXMesh::GetIndexBuffer Method

Retrieves the data in an index buffer.

Syntax

HRESULT GetIndexBuffer(

    LPDIRECT3DINDEXBUFFER9 *ppIB
);

Parameters

ppIB
[out, retval] Address of a pointer to an IDirect3DIndexBuffer9 interface, representing the index buffer object associated with the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXMesh::GetNumBytesPerVertex Method

Gets the number of bytes per vertex.

Syntax

DWORD GetNumBytesPerVertex(VOID);

Return Value

Returns the number of bytes per vertex.


ID3DXMesh::GetNumFaces Method

Retrieves the number of faces in the mesh.

Syntax

DWORD GetNumFaces(VOID);

Return Value

Returns the number of faces in the mesh.


ID3DXMesh::GetNumVertices Method

Retrieves the number of vertices in the mesh.

Syntax

DWORD GetNumVertices(VOID);

Return Value

Returns the number of vertices in the mesh.


ID3DXMesh::GetOptions Method

Retrieves the mesh options enabled for this mesh at creation time.

Syntax

DWORD GetOptions(VOID);

Return Value

Returns a combination of one or more of the following flags, indicating the options enabled for this mesh at creation time.

D3DXMESH_32BIT | Use 32-bit indices.
D3DXMESH_DONOTCLIP | Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC | Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES | Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES | Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft Direct3D.
D3DXMESH_MANAGED | Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS | Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC | Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED | Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM | Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY | Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM | Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC | Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED | Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SYSTEMMEM | Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY | Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY | Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.


ID3DXMesh::GetVertexBuffer Method

Retrieves the data in a vertex buffer.

Syntax

HRESULT GetVertexBuffer(

    LPDIRECT3DVERTEXBUFFER9 *ppVB
);

Parameters

ppVB
[out, retval] Address of a pointer to an IDirect3DVertexBuffer9 interface, representing the vertex buffer object associated with the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXMesh::LockIndexBuffer Method

Locks an index buffer and obtains a pointer to the index buffer memory.

Syntax

HRESULT LockIndexBuffer(

    DWORD Flags,
    LPVOID *ppData
);

Parameters

Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY

For a description of the flags, see D3DLOCK.

ppData
[out, retval] VOID* pointer to a buffer containing the index data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When working with index buffers, you are allowed to make multiple lock calls. However, you must ensure that the number of lock calls match the number of unlock calls. DrawPrimitive calls will not succeed with any outstanding lock count on any currently set index buffer.

See Also

ID3DXBaseMesh::UnlockIndexBuffer, ID3DXMesh::UnlockIndexBuffer, ID3DXPMesh::UnlockIndexBuffer


ID3DXMesh::LockVertexBuffer Method

Locks a vertex buffer and obtains a pointer to the vertex buffer memory.

Syntax

HRESULT LockVertexBuffer(

    DWORD Flags,
    LPVOID *ppData
);

Parameters

Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY
  • D3DLOCK_NOOVERWRITE

For a description of the flags, see D3DLOCK.

ppData
[out, retval] VOID* pointer to a buffer containing the vertex data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When working with vertex buffers, you are allowed to make multiple lock calls; however, you must ensure that the number of lock calls match the number of unlock calls. DrawPrimitive calls will not succeed with any outstanding lock count on any currently set vertex buffer.

See Also

ID3DXBaseMesh::UnlockVertexBuffer, ID3DXMesh::UnlockVertexBuffer, ID3DXPMesh::UnlockVertexBuffer


ID3DXMesh::UnlockIndexBuffer Method

Unlocks an index buffer.

Syntax

HRESULT UnlockIndexBuffer(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseMesh::LockIndexBuffer, ID3DXMesh::LockIndexBuffer, ID3DXPMesh::LockIndexBuffer


ID3DXMesh::UnlockVertexBuffer Method

Unlocks a vertex buffer.

Syntax

HRESULT UnlockVertexBuffer(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseMesh::LockVertexBuffer, ID3DXMesh::LockVertexBuffer, ID3DXPMesh::LockVertexBuffer


ID3DXMesh::UpdateSemantics Method

This method allows the user to change the mesh declaration without changing the data layout of the vertex buffer. The call is valid only if the old and new declaration formats have the same vertex size.

Syntax

HRESULT UpdateSemantics(

    D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

Declaration
[in, out] An array of D3DVERTEXELEMENT9 elements, describing the vertex format of the mesh vertices. The upper limit of this declarator array is MAX_FVF_DECL_SIZE.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

ID3DXBaseMesh::CloneMesh is used to reformat and change the vertex data layout. For example, use it to to add space for normals, texture coordinates, colors, weights, etc. that were not present before.

ID3DXMesh::UpdateSemantics is a method for updating the vertex declaration with different semantic information, without changing the layout of the vertex buffer. For example, use it to relabel a 3-D texture coordinate as a binormal or tangent, or vice versa.

See Also

ID3DXBaseMesh::CloneMeshFVF, ID3DXBaseMesh::CloneMesh, ID3DXBaseMesh::GetDeclaration, ID3DXMesh::GetDeclaration, ID3DXPMesh::GetDeclaration, D3DXDeclaratorFromFVF


ID3DXPMesh::CloneMesh Method

Clones a mesh using a declarator.

Syntax

HRESULT CloneMesh(

    DWORD Options,
    const D3DVERTEXELEMENT9 *pDeclaration,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXMESH *ppCloneMesh
);

Parameters

Options
[in] A combination of one or more D3DXMESH flags specifying creation options for the mesh.
pDeclaration
[in] An array of D3DVERTEXELEMENT9 elements, which specify the vertex format for the vertices in the output mesh.
pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device object associated with the mesh.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXMesh interface, representing the cloned mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

ID3DXBaseMesh::CloneMesh is used to reformat and change the vertex data layout. This is done by creating a new mesh object. For example, use it to add space for normals, texture coordinates, colors, weights, etc. that were not present before.

ID3DXBaseMesh::UpdateSemantics updates the vertex declaration with different semantic information without changing the layout of the vertex buffer. This method does not modify the contents of the vertex buffer. For example, use it to relabel a 3-D texture coordinate as a binormal or tangent or vice versa.

See Also

ID3DXBaseMesh::CloneMeshFVF, ID3DXBaseMesh::GetDeclaration, ID3DXMesh::GetDeclaration, ID3DXPMesh::GetDeclaration, D3DXDeclaratorFromFVF


ID3DXPMesh::CloneMeshFVF Method

Clones a mesh using a flexible vertex format (FVF) code.

Syntax

HRESULT CloneMeshFVF(

    DWORD Options,
    DWORD FVF,
    LPDIRECT3DDEVICE9 pDevice,
    LPD3DXMESH *ppCloneMesh
);

Parameters

Options
[in] A combination of one or more D3DXMESH flags specifying creation options for the mesh.
FVF
[in] Combination of FVF codes, which specifies the vertex format for the vertices in the output mesh. For the values of the codes, see D3DFVF.
pDevice
[in] Pointer to an IDirect3DDevice9 interface representing the device object associated with the mesh.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXMesh interface, representing the cloned mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

ID3DXBaseMesh::CloneMeshFVF is used to reformat and change the vertex data layout. This is done by creating a new mesh object. For example, use it to to add space for normals, texture coordinates, colors, weights, etc. that were not present before.

ID3DXBaseMesh::UpdateSemantics updates the vertex declaration with different semantic information without changing the layout of the vertex buffer. This method does not modify the contents of the vertex buffer. For example, use it to relabel a 3-D texture coordinate as a binormal or tangent or vice versa.

See Also

ID3DXBaseMesh::CloneMesh, ID3DXBaseMesh::GetFVF, ID3DXMesh::GetFVF, ID3DXPMesh::GetFVF, D3DXFVFFromDeclarator


ID3DXPMesh::ConvertAdjacencyToPointReps Method

Converts mesh adjacency information to an array of point representatives.

Syntax

HRESULT ConvertAdjacencyToPointReps(

    CONST DWORD* pAdjacency,
    DWORD* pPRep
);

Parameters

pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh. The number of bytes in this array must be at least 3 * ID3DXBaseMesh::GetNumFaces * sizeof(DWORD).
pPRep
[in, out] Pointer to an array of one DWORD per vertex of the mesh that will be filled with point representative data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

See Also

ID3DXBaseMesh::ConvertPointRepsToAdjacency, ID3DXMesh::ConvertPointRepsToAdjacency, ID3DXPMesh::ConvertPointRepsToAdjacency


ID3DXPMesh::ConvertPointRepsToAdjacency Method

Converts point representative data to mesh adjacency information.

Syntax

HRESULT ConvertPointRepsToAdjacency(

    CONST DWORD* pPRep,
    DWORD* pAdjacency
);

Parameters

pPRep
[in] Pointer to an array of one DWORD per vertex of the mesh that contains point representative data. This parameter is optional. Supplying a NULL value will cause this parameter to be interpreted as an "identity" array.
pAdjacency
[in, out] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh. The number of bytes in this array must be at least 3 * ID3DXBaseMesh::GetNumFaces * sizeof(DWORD).

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

See Also

ID3DXBaseMesh::ConvertAdjacencyToPointReps, ID3DXMesh::ConvertAdjacencyToPointReps, ID3DXPMesh::ConvertAdjacencyToPointReps


ID3DXPMesh::DrawSubset Method

Draws a subset of a mesh.

Syntax

HRESULT DrawSubset(

    DWORD AttribId
);

Parameters

AttribId
[in] DWORD that specifies which subset of the mesh to draw. This value is used to differentiate faces in a mesh as belonging to one or more attribute groups.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

An attribute table is used to identify areas of the mesh that need to be drawn with different textures, render states, materials, and so on. In addition, the application can use the attribute table to hide portions of a mesh by not drawing a given attribute identifier (AttribId) when drawing the frame.

See Also

ID3DXBaseMesh::GetAttributeTable, ID3DXMesh::GetAttributeTable, ID3DXPMesh::GetAttributeTable


ID3DXPMesh::GenerateAdjacency Method

Generate a list of mesh edges and the faces that share each edge.

Syntax

HRESULT GenerateAdjacency(

    FLOAT Epsilon,
    DWORD *pAdjacency
);

Parameters

Epsilon
[in] Specifies that vertices that differ in position by less than epsilon should be treated as coincident.
pAdjacency
[in] Pointer to an array of three DWORDs per face to be filled with adjacent face indices. The number of bytes in this array must be at least 3 * ID3DXBaseMesh::GetNumFaces * sizeof(DWORD).

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

D3DERR_INVALIDCALL | The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY | Microsoft Direct3D could not allocate sufficient memory to complete the call.

Remarks

After an application generates adjacency information for a mesh, the mesh data can be optimized for better drawing performance.

See Also

ID3DXMesh::Optimize, ID3DXMesh::OptimizeInplace


ID3DXPMesh::GetAttributeTable Method

Retrieves either an attribute table for a mesh, or the number of entries stored in an attribute table for a mesh.

Syntax

HRESULT GetAttributeTable(

    D3DXATTRIBUTERANGE *pAttribTable,
    DWORD *pAttribTableSize
);

Parameters

pAttribTable
[in, out] Pointer to an array of D3DXATTRIBUTERANGE structures, representing the entries in the mesh's attribute table. Specify NULL to retrieve the value for pAttribTableSize.
pAttribTableSize
[in, out] Pointer to either the number of entries stored in pAttribTable or a value to be filled in with the number of entries stored in the attribute table for the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

An attribute table is created by ID3DXMesh::Optimize and passing D3DXMESHOPT_ATTRSORT for the Flags parameter.

An attribute table is used to identify areas of the mesh that need to be drawn with different textures, render states, materials, and so on. In addition, the application can use the attribute table to hide portions of a mesh by not drawing a given attribute identifier when drawing the frame.


ID3DXPMesh::GetDeclaration Method

Retrieves a declaration describing the vertices in the mesh.

Syntax

HRESULT GetDeclaration(

    D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

Declaration
[in, out] Array of D3DVERTEXELEMENT9 elements describing the vertex format of the mesh vertices. The upper limit of this declarator array is MAX_FVF_DECL_SIZE. The vertex element array ends with the D3DDECL_END macro.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The array of elements includes the D3DDECL_END macro, which ends the declaration.

See Also

ID3DXBaseMesh::GetFVF, ID3DXMesh::GetFVF, ID3DXPMesh::GetFVF


ID3DXPMesh::GetDevice Method

Retrieves the device associated with the mesh.

Syntax

HRESULT GetDevice(

    LPDIRECT3DDEVICE9 *ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice9 interface, representing the Microsoft Direct3D device object associated with the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Calling this method will increase the internal reference count on the IDirect3DDevice9 interface. Be sure to call IUnknown::Release when you are done using this IDirect3DDevice9 interface or you will have a memory leak.


ID3DXPMesh::GetFVF Method

Gets the fixed function vertex value.

Syntax

DWORD GetFVF(VOID);

Return Value

Returns the flexible vertex format (FVF) codes.

Remarks

This method can return 0 if the vertex format cannot be mapped directly to an FVF code. This will occur for a mesh created from a vertex declaration that doesn't have the same order and elements supported by the FVF codes.


ID3DXPMesh::GetIndexBuffer Method

Retrieves the data in an index buffer.

Syntax

HRESULT GetIndexBuffer(

    LPDIRECT3DINDEXBUFFER9 *ppIB
);

Parameters

ppIB
[out, retval] Address of a pointer to an IDirect3DIndexBuffer9 interface, representing the index buffer object associated with the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXPMesh::GetNumBytesPerVertex Method

Gets the number of bytes per vertex.

Syntax

DWORD GetNumBytesPerVertex(VOID);

Return Value

Returns the number of bytes per vertex.


ID3DXPMesh::GetNumFaces Method

Retrieves the number of faces in the mesh.

Syntax

DWORD GetNumFaces(VOID);

Return Value

Returns the number of faces in the mesh.


ID3DXPMesh::GetNumVertices Method

Retrieves the number of vertices in the mesh.

Syntax

DWORD GetNumVertices(VOID);

Return Value

Returns the number of vertices in the mesh.


ID3DXPMesh::GetOptions Method

Retrieves the mesh options enabled for this mesh at creation time.

Syntax

DWORD GetOptions(VOID);

Return Value

Returns a combination of one or more of the following flags, indicating the options enabled for this mesh at creation time.

D3DXMESH_32BIT | Use 32-bit indices.
D3DXMESH_DONOTCLIP | Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC | Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES | Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES | Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft Direct3D.
D3DXMESH_MANAGED | Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS | Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC | Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED | Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM | Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY | Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM | Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC | Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED | Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SYSTEMMEM | Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY | Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY | Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.


ID3DXPMesh::GetVertexBuffer Method

Retrieves the data in a vertex buffer.

Syntax

HRESULT GetVertexBuffer(

    LPDIRECT3DVERTEXBUFFER9 *ppVB
);

Parameters

ppVB
[out, retval] Address of a pointer to an IDirect3DVertexBuffer9 interface, representing the vertex buffer object associated with the mesh.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXPMesh::LockIndexBuffer Method

Locks an index buffer and obtains a pointer to the index buffer memory.

Syntax

HRESULT LockIndexBuffer(

    DWORD Flags,
    LPVOID *ppData
);

Parameters

Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY

For a description of the flags, see D3DLOCK.

ppData
[out, retval] VOID* pointer to a buffer containing the index data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When working with index buffers, you are allowed to make multiple lock calls. However, you must ensure that the number of lock calls match the number of unlock calls. DrawPrimitive calls will not succeed with any outstanding lock count on any currently set index buffer.

See Also

ID3DXBaseMesh::UnlockIndexBuffer, ID3DXMesh::UnlockIndexBuffer, ID3DXPMesh::UnlockIndexBuffer


ID3DXPMesh::LockVertexBuffer Method

Locks a vertex buffer and obtains a pointer to the vertex buffer memory.

Syntax

HRESULT LockVertexBuffer(

    DWORD Flags,
    LPVOID *ppData
);

Parameters

Flags
[in] Combination of zero or more locking flags that describe the type of lock to perform. For this method, the valid flags are:
  • D3DLOCK_DISCARD
  • D3DLOCK_NO_DIRTY_UPDATE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_READONLY
  • D3DLOCK_NOOVERWRITE

For a description of the flags, see D3DLOCK.

ppData
[out, retval] VOID* pointer to a buffer containing the vertex data.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When working with vertex buffers, you are allowed to make multiple lock calls; however, you must ensure that the number of lock calls match the number of unlock calls. DrawPrimitive calls will not succeed with any outstanding lock count on any currently set vertex buffer.

See Also

ID3DXBaseMesh::UnlockVertexBuffer, ID3DXMesh::UnlockVertexBuffer, ID3DXPMesh::UnlockVertexBuffer


ID3DXPMesh::UnlockIndexBuffer Method

Unlocks an index buffer.

Syntax

HRESULT UnlockIndexBuffer(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseMesh::LockIndexBuffer, ID3DXMesh::LockIndexBuffer, ID3DXPMesh::LockIndexBuffer


ID3DXPMesh::UnlockVertexBuffer Method

Unlocks a vertex buffer.

Syntax

HRESULT UnlockVertexBuffer(VOID);

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseMesh::LockVertexBuffer, ID3DXMesh::LockVertexBuffer, ID3DXPMesh::LockVertexBuffer


ID3DXPMesh::UpdateSemantics Method

This method allows the user to change the mesh declaration without changing the data layout of the vertex buffer. The call is valid only if the old and new declaration formats have the same vertex size.

Syntax

HRESULT UpdateSemantics(

    D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

Declaration
[in, out] An array of D3DVERTEXELEMENT9 elements, describing the vertex format of the mesh vertices. The upper limit of this declarator array is MAX_FVF_DECL_SIZE.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

ID3DXBaseMesh::CloneMesh is used to reformat and change the vertex data layout. For example, use it to to add space for normals, texture coordinates, colors, weights, etc. that were not present before.

ID3DXPMesh::UpdateSemantics is a method for updating the vertex declaration with different semantic information, without changing the layout of the vertex buffer. For example, use it to relabel a 3-D texture coordinate as a binormal or tangent, or vice versa.

See Also

ID3DXBaseMesh::CloneMeshFVF, ID3DXBaseMesh::CloneMesh, ID3DXBaseMesh::GetDeclaration, ID3DXMesh::GetDeclaration, ID3DXPMesh::GetDeclaration, D3DXDeclaratorFromFVF


ID3DXEffect::GetAnnotation Method

Gets the handle of an annotation.

Syntax

D3DXHANDLE GetAnnotation(

    D3DXHANDLE hObject,
    UINT Index
);

Parameters

hObject
[in] Handle of a technique, pass, or top-level parameter. See Handles.
Index
[in] Annotation index.

Return Value

Returns the handle of the specified annotation, or NULL if the index was invalid. See Handles.

Remarks

Annotations are user-specific data that can be attached to any technique, pass, or parameter. See Handles.


ID3DXEffect::GetAnnotationByName Method

Gets the handle of an annotation by looking up its name.

Syntax

D3DXHANDLE GetAnnotationByName(

    D3DXHANDLE hObject,
    LPCSTR pName
);

Parameters

hObject
[in] Handle of a technique, pass, or top-level parameter. See Handles.
pName
[in] String containing the annotation name.

Return Value

Returns the handle of the specified annotation, or NULL if the name was not found. See Handles.


ID3DXEffect::GetBool Method

Gets a BOOL value.

Syntax

HRESULT GetBool(

    D3DXHANDLE hParameter,
    BOOL* pb
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pb
[out] Returns a Boolean value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetBool


ID3DXEffect::GetBoolArray Method

Gets an array of BOOL values.

Syntax

HRESULT GetBoolArray(

    D3DXHANDLE hParameter,
    BOOL* pB,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pB
[out] Returns an array of Boolean values.
Count
[in] Number of Boolean values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetBoolArray


ID3DXEffect::GetDesc Method

Gets the effect description.

Syntax

HRESULT GetDesc(

    D3DXEFFECT_DESC* pDesc
);

Parameters

pDesc
[out] Returns a description of the effect. See D3DXEFFECT_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXEffect::GetFloat Method

Gets a floating point value.

Syntax

HRESULT GetFloat(

    D3DXHANDLE hParameter,
    FLOAT* pf
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pf
[out] Returns a floating point value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetFloat


ID3DXEffect::GetFloatArray Method

Gets an array of floating point values.

Syntax

HRESULT GetFloatArray(

    D3DXHANDLE hParameter,
    FLOAT* pf,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pf
[out] Returns an array of floating point values.
Count
[in] Number of floating point values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetFloatArray


ID3DXEffect::GetFunction Method

Gets the handle of a function.

Syntax

D3DXHANDLE GetFunction(

    UINT Index
);

Parameters

Index
[in] Function index.

Return Value

Returns the handle of the specified function, or NULL if the index was invalid. See Handles.


ID3DXEffect::GetFunctionByName Method

Gets the handle of a function by looking up its name.

Syntax

D3DXHANDLE GetFunctionByName(

    LPCSTR pName
);

Parameters

pName
[in] String containing the function name.

Return Value

Returns the handle of the specified function, or NULL if the name was not found. See Handles.


ID3DXEffect::GetFunctionDesc Method

Gets a function description.

Syntax

HRESULT GetFunctionDesc(

    D3DXHANDLE hFunction,
    D3DXFUNCTION_DESC* pDesc
);

Parameters

hFunction
[in] Function handle. See Handles.
pDesc
[out] Returns a description of the function. See D3DXFUNCTION_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXEffect::GetInt Method

Gets an integer.

Syntax

HRESULT GetInt(

    D3DXHANDLE hParameter,
    INT* pn
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pn
[out] Returns an integer.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetInt


ID3DXEffect::GetIntArray Method

Gets an array of integers.

Syntax

HRESULT GetIntArray(

    D3DXHANDLE hParameter,
    INT* pn,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pn
[out] Returns an array of integers.
Count
[in] Number of integers in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetIntArray


ID3DXEffect::GetMatrix Method

Gets a nontransposed matrix.

Syntax

HRESULT GetMatrix(

    D3DXHANDLE hParameter,
    D3DXMATRIX* pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns a nontransposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

If the destination matrix is larger than the source matrix, only the upper-left components of the destination matrix will be filled, and the remaining components will be set to zero.

See Also

ID3DXBaseEffect::SetMatrix


ID3DXEffect::GetMatrixArray Method

Gets an array of nontransposed matrices.

Syntax

HRESULT GetMatrixArray(

    D3DXHANDLE hParameter,
    D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns an array of nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

If the destination matrices are larger than the source matrices, only the upper-left components of each destination matrix will be filled, and the remaining destination matrix components will be set to zero.

See Also

ID3DXBaseEffect::SetMatrixArray


ID3DXEffect::GetMatrixPointerArray Method

Gets an array of pointers to nontransposed matrices.

Syntax

HRESULT GetMatrixPointerArray(

    D3DXHANDLE hParameter,
    D3DXMATRIX **ppMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppMatrix
[out] Array of pointers to nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

If the destination matrices are larger than the source matrices, only the upper-left components of each destination matrix will be filled, and the remaining destination matrix components will be set to zero.

See Also

ID3DXBaseEffect::GetMatrixArray


ID3DXEffect::GetMatrixTranspose Method

Gets a transposed matrix.

Syntax

HRESULT GetMatrixTranspose(

    D3DXHANDLE hParameter,
    D3DXMATRIX* pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns a transposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

If the destination matrix is larger than the source matrix, only the upper-left elements of the destination matrix will be filled, and the remaining destination matrix components will be set to zero.

See Also

ID3DXBaseEffect::SetMatrixTranspose


ID3DXEffect::GetMatrixTransposeArray Method

Gets an array of transposed matrices.

Syntax

HRESULT GetMatrixTransposeArray(

    D3DXHANDLE hParameter,
    D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns an array of transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

If the destination matrices are larger than the source matrices, only the upper-left components of each destination matrix will be filled, and the remaining destination matrix components will be set to zero.

See Also

ID3DXBaseEffect::SetMatrixTransposeArray


ID3DXEffect::GetMatrixTransposePointerArray Method

Sets an array of pointers to transposed matrices.

Syntax

HRESULT GetMatrixTransposePointerArray(

    D3DXHANDLE hParameter,
    D3DXMATRIX** ppMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppMatrix
[in] Array of pointers to transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

If the destination matrices are larger than the source matrices, only the upper-left components of each destination matrix will be filled, and the remaining destination matrix components will be set to zero.

See Also

ID3DXBaseEffect::GetMatrixTransposeArray


ID3DXEffect::GetParameter Method

Gets the handle of a top-level parameter or a structure member parameter.

Syntax

D3DXHANDLE GetParameter(

    D3DXHANDLE hParameter,
    UINT Index
);

Parameters

hParameter
[in] Handle of the parameter, or NULL for top-level parameters. See Handles.
Index
[in] Parameter index.

Return Value

Returns the handle of the specified parameter, or NULL if the index was invalid. See Handles.


ID3DXEffect::GetParameterByName Method

Gets the handle of a top-level parameter or a structure member parameter by looking up its name.

Syntax

D3DXHANDLE GetParameterByName(

    D3DXHANDLE hParameter,
    LPCSTR pName
);

Parameters

hParameter
[in] Handle of the parameter, or NULL for top-level parameters. See Handles.
pName
[in] String containing the parameter name.

Return Value

Returns the handle of the specified parameter, or NULL if the index was invalid. See Handles.


ID3DXEffect::GetParameterBySemantic Method

Gets the handle of a top-level parameter or a structure member parameter by looking up its semantic with a case-insensitive search.

Syntax

D3DXHANDLE GetParameterBySemantic(

    D3DXHANDLE hParameter,
    LPCSTR pSemantic
);

Parameters

hParameter
[in] Handle of the parameter, or NULL for top-level parameters. See Handles.
pSemantic
[in] String containing the semantic name.

Return Value

Returns the handle of the first parameter that matches the specified semantic, or NULL if the semantic was not found. See Handles.


ID3DXEffect::GetParameterDesc Method

Gets a parameter or annotation description.

Syntax

HRESULT GetParameterDesc(

    D3DXHANDLE hParameter,
    D3DXPARAMETER_DESC* pDesc
);

Parameters

hParameter
[in] Parameter or annotation handle. See Handles.
pDesc
[out] Returns a description of the specified parameter or annotation. See D3DXPARAMETER_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXEffect::GetParameterElement Method

Get the handle of an array element parameter.

Syntax

D3DXHANDLE GetParameterElement(

    D3DXHANDLE hParameter,
    UINT ElementIndex
);

Parameters

hParameter
[in] Handle of the array. See Handles.
ElementIndex
[in] Array element index.

Return Value

Returns the handle of the specified parameter, or NULL if either hParameter or ElementIndex is invalid. See Handles.

Remarks

This method is used to get an element of a parameter that is an array.


ID3DXEffect::GetPass Method

Gets the handle of a pass.

Syntax

D3DXHANDLE GetPass(

    D3DXHANDLE hTechnique,
    UINT Index
);

Parameters

hTechnique
[in] Handle of the parent technique. See Handles.
Index
[in] Index for the pass.

Return Value

Returns the handle of the specified pass inside the specified technique, or NULL if the index was invalid. See Handles.


ID3DXEffect::GetPassByName Method

Gets the handle of a pass by looking up its name.

Syntax

D3DXHANDLE GetPassByName(

    D3DXHANDLE hTechnique,
    LPCSTR pName
);

Parameters

hTechnique
[in] Handle of the parent technique. See Handles.
pName
[in] String containing the pass name.

Return Value

Returns the handle of the first pass inside the specified technique that has the specified name, or NULL if the name was not found. See Handles.


ID3DXEffect::GetPassDesc Method

Gets a pass description.

Syntax

HRESULT GetPassDesc(

    D3DXHANDLE hPass,
    D3DXPASS_DESC* pDesc
);

Parameters

hPass
[in] Pass handle. See Handles.
pDesc
[out] Returns a description of the specified pass. See D3DXPASS_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXEffect::GetPixelShader Method

Gets a pixel shader.

Syntax

HRESULT GetPixelShader(

    D3DXHANDLE hParameter,
    LPDIRECT3DPIXELSHADER9* ppPShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppPShader
[out] Returns a pixel shader object. See IDirect3DPixelShader9 object.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetPixelShader


ID3DXEffect::GetString Method

Gets a string.

Syntax

HRESULT GetString(

    D3DXHANDLE hParameter,
    LPCSTR* ppString
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppString
[out] Returns a string identified by hParameter.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetString


ID3DXEffect::GetTechnique Method

Gets the handle of a technique.

Syntax

D3DXHANDLE GetTechnique(

    UINT Index
);

Parameters

Index
[in] Technique index.

Return Value

Returns the handle of the specified technique, or NULL if the index was invalid. See Handles.


ID3DXEffect::GetTechniqueByName Method

Gets the handle of a technique by looking up its name.

Syntax

D3DXHANDLE GetTechniqueByName(

    LPCSTR pName
);

Parameters

pName
[in] String containing the technique name.

Return Value

Returns the handle of the first technique that has the specified name, or NULL if the name was not found. See Handles.


ID3DXEffect::GetTechniqueDesc Method

Gets a technique description.

Syntax

HRESULT GetTechniqueDesc(

    D3DXHANDLE hTechnique,
    D3DXTECHNIQUE_DESC* pDesc
);

Parameters

hTechnique
[in] Technique handle. See Handles.
pDesc
[out] Returns a description of the technique. See D3DXTECHNIQUE_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXEffect::GetTexture Method

Gets a texture.

Syntax

HRESULT GetTexture(

    D3DXHANDLE hParameter,
    LPDIRECT3DBASETEXTURE9* ppTexture
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppTexture
[out] Returns a texture object. See IDirect3DBaseTexture9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetTexture


ID3DXEffect::GetValue Method

Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Getxxx calls in ID3DXBaseEffect.

Syntax

HRESULT GetValue(

    D3DXHANDLE hParameter,
    LPVOID pData,
    UINT Bytes
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pData
[out] Returns a buffer containing the value.
Bytes
[in] [in] Number of bytes in the buffer. Pass in D3DX_DEFAULT if you know your buffer is large enough to contain the entire parameter, and you want to skip size validation.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetValue


ID3DXEffect::GetVector Method

Gets a vector.

Syntax

HRESULT GetVector(

    D3DXHANDLE hParameter,
    D3DXVECTOR4* pVector
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[out] Returns a 4-D vector.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the destination vector is larger than the source vector, only the initial components of the destination vector will be filled, and the remaining components will be set to zero.

See Also

ID3DXBaseEffect::SetVector


ID3DXEffect::GetVectorArray Method

Gets an array of vectors.

Syntax

HRESULT GetVectorArray(

    D3DXHANDLE hParameter,
    D3DXVECTOR4* pVector,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[out] Returns an array of 4-D floating point vectors.
Count
[in] Number of vectors in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the destination vectors are larger than the source vectors, only the initial components of each destination vector will be filled, and the remaining destination vector components will be set to zero.

See Also

ID3DXBaseEffect::SetVectorArray


ID3DXEffect::GetVertexShader Method

Gets a vertex shader.

Syntax

HRESULT GetVertexShader(

    D3DXHANDLE hParameter,
    LPDIRECT3DVERTEXSHADER9* ppVShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppVShader
[out] Returns a vertex shader object. See IDirect3DVertexShader9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXEffect::SetArrayRange Method

Set the range of an array to pass to the device.

Syntax

HRESULT SetArrayRange(

    D3DXHANDLE hParameter,
    UINT Start,
    UINT Stop
);

Parameters

hParameter
[in] Unique identifier. See Handles.
Start
[in] Start index.
Stop
[in] Stop index.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXEffect::SetBool Method

Sets a BOOL value.

Syntax

HRESULT SetBool(

    D3DXHANDLE hParameter,
    BOOL b
);

Parameters

hParameter
[in] Unique identifier. See Handles.
b
[in] Boolean value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetBool


ID3DXEffect::SetBoolArray Method

Sets an array of Boolean values.

Syntax

HRESULT SetBoolArray(

    D3DXHANDLE hParameter,
    CONST BOOL* pB,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pB
[in] Array of Boolean values.
Count
[in] Number of Boolean values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetBoolArray


ID3DXEffect::SetFloat Method

Sets a floating point value.

Syntax

HRESULT SetFloat(

    D3DXHANDLE hParameter,
    FLOAT f
);

Parameters

hParameter
[in] Unique identifier. See Handles.
f
[in] Floating point value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetFloat


ID3DXEffect::SetFloatArray Method

Sets an array of floating point values.

Syntax

HRESULT SetFloatArray(

    D3DXHANDLE hParameter,
    CONST FLOAT* pf,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pf
[in] Array of floating point values.
Count
[in] Number of floating point values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetFloatArray


ID3DXEffect::SetInt Method

Sets an integer.

Syntax

HRESULT SetInt(

    D3DXHANDLE hParameter,
    INT n
);

Parameters

hParameter
[in] Unique identifier. See Handles.
n
[in] Integer value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetInt


ID3DXEffect::SetIntArray Method

Sets an array of integers.

Syntax

HRESULT SetIntArray(

    D3DXHANDLE hParameter,
    CONST INT* pn,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pn
[in] Array of integers.
Count
[in] Number of integers in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetIntArray


ID3DXEffect::SetMatrix Method

Sets a non-transposed matrix.

Syntax

HRESULT SetMatrix(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Pointer to a nontransposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A non-transposed matrix contains row-major data. In other words, each vector is contained in a row.

If the destination matrix is smaller than the source matrix, the additional components of the source matrix will be ignored.

See Also

ID3DXBaseEffect::GetMatrix


ID3DXEffect::SetMatrixArray Method

Sets an array of nontransposed matrices.

Syntax

HRESULT SetMatrixArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Array of nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

If the destination matrices are smaller than the source matrices, the additional components of the source matrices will be ignored.

See Also

ID3DXBaseEffect::GetMatrixArray


ID3DXEffect::SetMatrixPointerArray Method

Sets an array of pointers to nontransposed matrices.

Syntax

HRESULT SetMatrixPointerArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX** ppMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppMatrix
[in] Array of pointers to nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

If the destination matrices are smaller than the source matrices, the additional components of the source matrices will be ignored.

See Also

ID3DXBaseEffect::GetMatrixArray


ID3DXEffect::SetMatrixTranspose Method

Sets a transposed matrix.

Syntax

HRESULT SetMatrixTranspose(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Pointer to a transposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

If the destination matrix is smaller than the source matrix, the additional components of the source matrix will be ignored.

See Also

ID3DXBaseEffect::GetMatrixTranspose


ID3DXEffect::SetMatrixTransposeArray Method

Sets an array of transposed matrices.

Syntax

HRESULT SetMatrixTransposeArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Array of transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

If the destination matrices are smaller than the source matrices, the additional components of the source matrices will be ignored.

See Also

ID3DXBaseEffect::GetMatrixTransposeArray


ID3DXEffect::SetMatrixTransposePointerArray Method

Sets an array of pointers to transposed matrices.

Syntax

HRESULT SetMatrixTransposePointerArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX** ppMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppMatrix
[in] Array of pointers to transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

If the destination matrices are smaller than the source matrices, the additional components of the source matrices will be ignored.

See Also

ID3DXBaseEffect::GetMatrixTransposeArray


ID3DXEffect::SetPixelShader Method

Sets a pixel shader.

Syntax

HRESULT SetPixelShader(

    D3DXHANDLE hParameter,
    LPDIRECT3DPIXELSHADER9 pPShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pPShader
[in] Pixel shader object. See IDirect3DPixelShader9 object.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetPixelShader


ID3DXEffect::SetString Method

Sets a string.

Syntax

HRESULT SetString(

    D3DXHANDLE hParameter,
    LPCSTR pString
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pString
[in] String to set.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetString


ID3DXEffect::SetTexture Method

Sets a texture.

Syntax

HRESULT SetTexture(

    D3DXHANDLE hParameter,
    LPDIRECT3DBASETEXTURE9 pTexture
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pTexture
[in] Texture object. See IDirect3DBaseTexture9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetTexture


ID3DXEffect::SetValue Method

Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Setxxx calls in ID3DXBaseEffect.

Syntax

HRESULT SetValue(

    D3DXHANDLE hParameter,
    LPCVOID pData,
    UINT Bytes
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pData
[in] Pointer to a buffer containing data.
Bytes
[in] [in] Number of bytes in the buffer. Pass in D3DX_DEFAULT if you know your buffer is large enough to contain the entire parameter, and you want to skip size validation.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetValue


ID3DXEffect::SetVector Method

Sets a vector.

Syntax

HRESULT SetVector(

    D3DXHANDLE hParameter,
    CONST D3DXVECTOR4* pVector
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[in] Pointer to a 4-D vector.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the destination vector is smaller than the source vector, the additional components of the source vector will be ignored.

See Also

ID3DXBaseEffect::GetVector


ID3DXEffect::SetVectorArray Method

Sets an array of vectors.

Syntax

HRESULT SetVectorArray(

    D3DXHANDLE hParameter,
    CONST D3DXVECTOR4* pVector,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[in] Array of 4-D floating point vectors.
Count
[in] Number of vectors in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the destination vectors are smaller than the source vectors, the additional components of the source vectors will be ignored.

See Also

ID3DXBaseEffect::GetVectorArray


ID3DXEffect::SetVertexShader Method

Sets a vertex shader.

Syntax

HRESULT SetVertexShader(

    D3DXHANDLE hParameter,
    LPDIRECT3DVERTEXSHADER9 pVertexShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVertexShader
[in] Vertex shader object. See IDirect3DVertexShader9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetVertexShader


ID3DXEffectCompiler::GetAnnotation Method

Gets the handle of an annotation.

Syntax

D3DXHANDLE GetAnnotation(

    D3DXHANDLE hObject,
    UINT Index
);

Parameters

hObject
[in] Handle of a technique, pass, or top-level parameter. See Handles.
Index
[in] Annotation index.

Return Value

Returns the handle of the specified annotation, or NULL if the index was invalid. See Handles.

Remarks

Annotations are user-specific data that can be attached to any technique, pass, or parameter. See Handles.


ID3DXEffectCompiler::GetAnnotationByName Method

Gets the handle of an annotation by looking up its name.

Syntax

D3DXHANDLE GetAnnotationByName(

    D3DXHANDLE hObject,
    LPCSTR pName
);

Parameters

hObject
[in] Handle of a technique, pass, or top-level parameter. See Handles.
pName
[in] String containing the annotation name.

Return Value

Returns the handle of the specified annotation, or NULL if the name was not found. See Handles.


ID3DXEffectCompiler::GetBool Method

Gets a BOOL value.

Syntax

HRESULT GetBool(

    D3DXHANDLE hParameter,
    BOOL* pb
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pb
[out] Returns a Boolean value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetBool


ID3DXEffectCompiler::GetBoolArray Method

Gets an array of BOOL values.

Syntax

HRESULT GetBoolArray(

    D3DXHANDLE hParameter,
    BOOL* pB,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pB
[out] Returns an array of Boolean values.
Count
[in] Number of Boolean values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetBoolArray


ID3DXEffectCompiler::GetDesc Method

Gets the effect description.

Syntax

HRESULT GetDesc(

    D3DXEFFECT_DESC* pDesc
);

Parameters

pDesc
[out] Returns a description of the effect. See D3DXEFFECT_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXEffectCompiler::GetFloat Method

Gets a floating point value.

Syntax

HRESULT GetFloat(

    D3DXHANDLE hParameter,
    FLOAT* pf
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pf
[out] Returns a floating point value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetFloat


ID3DXEffectCompiler::GetFloatArray Method

Gets an array of floating point values.

Syntax

HRESULT GetFloatArray(

    D3DXHANDLE hParameter,
    FLOAT* pf,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pf
[out] Returns an array of floating point values.
Count
[in] Number of floating point values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetFloatArray


ID3DXEffectCompiler::GetFunction Method

Gets the handle of a function.

Syntax

D3DXHANDLE GetFunction(

    UINT Index
);

Parameters

Index
[in] Function index.

Return Value

Returns the handle of the specified function, or NULL if the index was invalid. See Handles.


ID3DXEffectCompiler::GetFunctionByName Method

Gets the handle of a function by looking up its name.

Syntax

D3DXHANDLE GetFunctionByName(

    LPCSTR pName
);

Parameters

pName
[in] String containing the function name.

Return Value

Returns the handle of the specified function, or NULL if the name was not found. See Handles.


ID3DXEffectCompiler::GetFunctionDesc Method

Gets a function description.

Syntax

HRESULT GetFunctionDesc(

    D3DXHANDLE hFunction,
    D3DXFUNCTION_DESC* pDesc
);

Parameters

hFunction
[in] Function handle. See Handles.
pDesc
[out] Returns a description of the function. See D3DXFUNCTION_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXEffectCompiler::GetInt Method

Gets an integer.

Syntax

HRESULT GetInt(

    D3DXHANDLE hParameter,
    INT* pn
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pn
[out] Returns an integer.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetInt


ID3DXEffectCompiler::GetIntArray Method

Gets an array of integers.

Syntax

HRESULT GetIntArray(

    D3DXHANDLE hParameter,
    INT* pn,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pn
[out] Returns an array of integers.
Count
[in] Number of integers in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetIntArray


ID3DXEffectCompiler::GetMatrix Method

Gets a nontransposed matrix.

Syntax

HRESULT GetMatrix(

    D3DXHANDLE hParameter,
    D3DXMATRIX* pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns a nontransposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

If the destination matrix is larger than the source matrix, only the upper-left components of the destination matrix will be filled, and the remaining components will be set to zero.

See Also

ID3DXBaseEffect::SetMatrix


ID3DXEffectCompiler::GetMatrixArray Method

Gets an array of nontransposed matrices.

Syntax

HRESULT GetMatrixArray(

    D3DXHANDLE hParameter,
    D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns an array of nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

If the destination matrices are larger than the source matrices, only the upper-left components of each destination matrix will be filled, and the remaining destination matrix components will be set to zero.

See Also

ID3DXBaseEffect::SetMatrixArray


ID3DXEffectCompiler::GetMatrixPointerArray Method

Gets an array of pointers to nontransposed matrices.

Syntax

HRESULT GetMatrixPointerArray(

    D3DXHANDLE hParameter,
    D3DXMATRIX **ppMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppMatrix
[out] Array of pointers to nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

If the destination matrices are larger than the source matrices, only the upper-left components of each destination matrix will be filled, and the remaining destination matrix components will be set to zero.

See Also

ID3DXBaseEffect::GetMatrixArray


ID3DXEffectCompiler::GetMatrixTranspose Method

Gets a transposed matrix.

Syntax

HRESULT GetMatrixTranspose(

    D3DXHANDLE hParameter,
    D3DXMATRIX* pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns a transposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

If the destination matrix is larger than the source matrix, only the upper-left elements of the destination matrix will be filled, and the remaining destination matrix components will be set to zero.

See Also

ID3DXBaseEffect::SetMatrixTranspose


ID3DXEffectCompiler::GetMatrixTransposeArray Method

Gets an array of transposed matrices.

Syntax

HRESULT GetMatrixTransposeArray(

    D3DXHANDLE hParameter,
    D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[out] Returns an array of transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

If the destination matrices are larger than the source matrices, only the upper-left components of each destination matrix will be filled, and the remaining destination matrix components will be set to zero.

See Also

ID3DXBaseEffect::SetMatrixTransposeArray


ID3DXEffectCompiler::GetMatrixTransposePointerArray Method

Sets an array of pointers to transposed matrices.

Syntax

HRESULT GetMatrixTransposePointerArray(

    D3DXHANDLE hParameter,
    D3DXMATRIX** ppMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppMatrix
[in] Array of pointers to transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

If the destination matrices are larger than the source matrices, only the upper-left components of each destination matrix will be filled, and the remaining destination matrix components will be set to zero.

See Also

ID3DXBaseEffect::GetMatrixTransposeArray


ID3DXEffectCompiler::GetParameter Method

Gets the handle of a top-level parameter or a structure member parameter.

Syntax

D3DXHANDLE GetParameter(

    D3DXHANDLE hParameter,
    UINT Index
);

Parameters

hParameter
[in] Handle of the parameter, or NULL for top-level parameters. See Handles.
Index
[in] Parameter index.

Return Value

Returns the handle of the specified parameter, or NULL if the index was invalid. See Handles.


ID3DXEffectCompiler::GetParameterByName Method

Gets the handle of a top-level parameter or a structure member parameter by looking up its name.

Syntax

D3DXHANDLE GetParameterByName(

    D3DXHANDLE hParameter,
    LPCSTR pName
);

Parameters

hParameter
[in] Handle of the parameter, or NULL for top-level parameters. See Handles.
pName
[in] String containing the parameter name.

Return Value

Returns the handle of the specified parameter, or NULL if the index was invalid. See Handles.


ID3DXEffectCompiler::GetParameterBySemantic Method

Gets the handle of a top-level parameter or a structure member parameter by looking up its semantic with a case-insensitive search.

Syntax

D3DXHANDLE GetParameterBySemantic(

    D3DXHANDLE hParameter,
    LPCSTR pSemantic
);

Parameters

hParameter
[in] Handle of the parameter, or NULL for top-level parameters. See Handles.
pSemantic
[in] String containing the semantic name.

Return Value

Returns the handle of the first parameter that matches the specified semantic, or NULL if the semantic was not found. See Handles.


ID3DXEffectCompiler::GetParameterDesc Method

Gets a parameter or annotation description.

Syntax

HRESULT GetParameterDesc(

    D3DXHANDLE hParameter,
    D3DXPARAMETER_DESC* pDesc
);

Parameters

hParameter
[in] Parameter or annotation handle. See Handles.
pDesc
[out] Returns a description of the specified parameter or annotation. See D3DXPARAMETER_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXEffectCompiler::GetParameterElement Method

Get the handle of an array element parameter.

Syntax

D3DXHANDLE GetParameterElement(

    D3DXHANDLE hParameter,
    UINT ElementIndex
);

Parameters

hParameter
[in] Handle of the array. See Handles.
ElementIndex
[in] Array element index.

Return Value

Returns the handle of the specified parameter, or NULL if either hParameter or ElementIndex is invalid. See Handles.

Remarks

This method is used to get an element of a parameter that is an array.


ID3DXEffectCompiler::GetPass Method

Gets the handle of a pass.

Syntax

D3DXHANDLE GetPass(

    D3DXHANDLE hTechnique,
    UINT Index
);

Parameters

hTechnique
[in] Handle of the parent technique. See Handles.
Index
[in] Index for the pass.

Return Value

Returns the handle of the specified pass inside the specified technique, or NULL if the index was invalid. See Handles.


ID3DXEffectCompiler::GetPassByName Method

Gets the handle of a pass by looking up its name.

Syntax

D3DXHANDLE GetPassByName(

    D3DXHANDLE hTechnique,
    LPCSTR pName
);

Parameters

hTechnique
[in] Handle of the parent technique. See Handles.
pName
[in] String containing the pass name.

Return Value

Returns the handle of the first pass inside the specified technique that has the specified name, or NULL if the name was not found. See Handles.


ID3DXEffectCompiler::GetPassDesc Method

Gets a pass description.

Syntax

HRESULT GetPassDesc(

    D3DXHANDLE hPass,
    D3DXPASS_DESC* pDesc
);

Parameters

hPass
[in] Pass handle. See Handles.
pDesc
[out] Returns a description of the specified pass. See D3DXPASS_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXEffectCompiler::GetPixelShader Method

Gets a pixel shader.

Syntax

HRESULT GetPixelShader(

    D3DXHANDLE hParameter,
    LPDIRECT3DPIXELSHADER9* ppPShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppPShader
[out] Returns a pixel shader object. See IDirect3DPixelShader9 object.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetPixelShader


ID3DXEffectCompiler::GetString Method

Gets a string.

Syntax

HRESULT GetString(

    D3DXHANDLE hParameter,
    LPCSTR* ppString
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppString
[out] Returns a string identified by hParameter.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetString


ID3DXEffectCompiler::GetTechnique Method

Gets the handle of a technique.

Syntax

D3DXHANDLE GetTechnique(

    UINT Index
);

Parameters

Index
[in] Technique index.

Return Value

Returns the handle of the specified technique, or NULL if the index was invalid. See Handles.


ID3DXEffectCompiler::GetTechniqueByName Method

Gets the handle of a technique by looking up its name.

Syntax

D3DXHANDLE GetTechniqueByName(

    LPCSTR pName
);

Parameters

pName
[in] String containing the technique name.

Return Value

Returns the handle of the first technique that has the specified name, or NULL if the name was not found. See Handles.


ID3DXEffectCompiler::GetTechniqueDesc Method

Gets a technique description.

Syntax

HRESULT GetTechniqueDesc(

    D3DXHANDLE hTechnique,
    D3DXTECHNIQUE_DESC* pDesc
);

Parameters

hTechnique
[in] Technique handle. See Handles.
pDesc
[out] Returns a description of the technique. See D3DXTECHNIQUE_DESC.

Return Value

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXEffectCompiler::GetTexture Method

Gets a texture.

Syntax

HRESULT GetTexture(

    D3DXHANDLE hParameter,
    LPDIRECT3DBASETEXTURE9* ppTexture
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppTexture
[out] Returns a texture object. See IDirect3DBaseTexture9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetTexture


ID3DXEffectCompiler::GetValue Method

Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Getxxx calls in ID3DXBaseEffect.

Syntax

HRESULT GetValue(

    D3DXHANDLE hParameter,
    LPVOID pData,
    UINT Bytes
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pData
[out] Returns a buffer containing the value.
Bytes
[in] [in] Number of bytes in the buffer. Pass in D3DX_DEFAULT if you know your buffer is large enough to contain the entire parameter, and you want to skip size validation.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::SetValue


ID3DXEffectCompiler::GetVector Method

Gets a vector.

Syntax

HRESULT GetVector(

    D3DXHANDLE hParameter,
    D3DXVECTOR4* pVector
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[out] Returns a 4-D vector.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the destination vector is larger than the source vector, only the initial components of the destination vector will be filled, and the remaining components will be set to zero.

See Also

ID3DXBaseEffect::SetVector


ID3DXEffectCompiler::GetVectorArray Method

Gets an array of vectors.

Syntax

HRESULT GetVectorArray(

    D3DXHANDLE hParameter,
    D3DXVECTOR4* pVector,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[out] Returns an array of 4-D floating point vectors.
Count
[in] Number of vectors in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the destination vectors are larger than the source vectors, only the initial components of each destination vector will be filled, and the remaining destination vector components will be set to zero.

See Also

ID3DXBaseEffect::SetVectorArray


ID3DXEffectCompiler::GetVertexShader Method

Gets a vertex shader.

Syntax

HRESULT GetVertexShader(

    D3DXHANDLE hParameter,
    LPDIRECT3DVERTEXSHADER9* ppVShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppVShader
[out] Returns a vertex shader object. See IDirect3DVertexShader9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXEffectCompiler::SetArrayRange Method

Set the range of an array to pass to the device.

Syntax

HRESULT SetArrayRange(

    D3DXHANDLE hParameter,
    UINT Start,
    UINT Stop
);

Parameters

hParameter
[in] Unique identifier. See Handles.
Start
[in] Start index.
Stop
[in] Stop index.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.


ID3DXEffectCompiler::SetBool Method

Sets a BOOL value.

Syntax

HRESULT SetBool(

    D3DXHANDLE hParameter,
    BOOL b
);

Parameters

hParameter
[in] Unique identifier. See Handles.
b
[in] Boolean value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetBool


ID3DXEffectCompiler::SetBoolArray Method

Sets an array of Boolean values.

Syntax

HRESULT SetBoolArray(

    D3DXHANDLE hParameter,
    CONST BOOL* pB,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pB
[in] Array of Boolean values.
Count
[in] Number of Boolean values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetBoolArray


ID3DXEffectCompiler::SetFloat Method

Sets a floating point value.

Syntax

HRESULT SetFloat(

    D3DXHANDLE hParameter,
    FLOAT f
);

Parameters

hParameter
[in] Unique identifier. See Handles.
f
[in] Floating point value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetFloat


ID3DXEffectCompiler::SetFloatArray Method

Sets an array of floating point values.

Syntax

HRESULT SetFloatArray(

    D3DXHANDLE hParameter,
    CONST FLOAT* pf,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pf
[in] Array of floating point values.
Count
[in] Number of floating point values in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetFloatArray


ID3DXEffectCompiler::SetInt Method

Sets an integer.

Syntax

HRESULT SetInt(

    D3DXHANDLE hParameter,
    INT n
);

Parameters

hParameter
[in] Unique identifier. See Handles.
n
[in] Integer value.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetInt


ID3DXEffectCompiler::SetIntArray Method

Sets an array of integers.

Syntax

HRESULT SetIntArray(

    D3DXHANDLE hParameter,
    CONST INT* pn,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pn
[in] Array of integers.
Count
[in] Number of integers in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetIntArray


ID3DXEffectCompiler::SetMatrix Method

Sets a non-transposed matrix.

Syntax

HRESULT SetMatrix(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Pointer to a nontransposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A non-transposed matrix contains row-major data. In other words, each vector is contained in a row.

If the destination matrix is smaller than the source matrix, the additional components of the source matrix will be ignored.

See Also

ID3DXBaseEffect::GetMatrix


ID3DXEffectCompiler::SetMatrixArray Method

Sets an array of nontransposed matrices.

Syntax

HRESULT SetMatrixArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Array of nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

If the destination matrices are smaller than the source matrices, the additional components of the source matrices will be ignored.

See Also

ID3DXBaseEffect::GetMatrixArray


ID3DXEffectCompiler::SetMatrixPointerArray Method

Sets an array of pointers to nontransposed matrices.

Syntax

HRESULT SetMatrixPointerArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX** ppMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppMatrix
[in] Array of pointers to nontransposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A nontransposed matrix contains row-major data; that is, each vector is contained in a row.

If the destination matrices are smaller than the source matrices, the additional components of the source matrices will be ignored.

See Also

ID3DXBaseEffect::GetMatrixArray


ID3DXEffectCompiler::SetMatrixTranspose Method

Sets a transposed matrix.

Syntax

HRESULT SetMatrixTranspose(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Pointer to a transposed matrix. See D3DXMATRIX.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

If the destination matrix is smaller than the source matrix, the additional components of the source matrix will be ignored.

See Also

ID3DXBaseEffect::GetMatrixTranspose


ID3DXEffectCompiler::SetMatrixTransposeArray Method

Sets an array of transposed matrices.

Syntax

HRESULT SetMatrixTransposeArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX* pMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pMatrix
[in] Array of transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

If the destination matrices are smaller than the source matrices, the additional components of the source matrices will be ignored.

See Also

ID3DXBaseEffect::GetMatrixTransposeArray


ID3DXEffectCompiler::SetMatrixTransposePointerArray Method

Sets an array of pointers to transposed matrices.

Syntax

HRESULT SetMatrixTransposePointerArray(

    D3DXHANDLE hParameter,
    CONST D3DXMATRIX** ppMatrix,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
ppMatrix
[in] Array of pointers to transposed matrices. See D3DXMATRIX.
Count
[in] Number of matrices in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A transposed matrix contains column-major data; that is, each vector is contained in a column.

If the destination matrices are smaller than the source matrices, the additional components of the source matrices will be ignored.

See Also

ID3DXBaseEffect::GetMatrixTransposeArray


ID3DXEffectCompiler::SetPixelShader Method

Sets a pixel shader.

Syntax

HRESULT SetPixelShader(

    D3DXHANDLE hParameter,
    LPDIRECT3DPIXELSHADER9 pPShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pPShader
[in] Pixel shader object. See IDirect3DPixelShader9 object.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetPixelShader


ID3DXEffectCompiler::SetString Method

Sets a string.

Syntax

HRESULT SetString(

    D3DXHANDLE hParameter,
    LPCSTR pString
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pString
[in] String to set.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetString


ID3DXEffectCompiler::SetTexture Method

Sets a texture.

Syntax

HRESULT SetTexture(

    D3DXHANDLE hParameter,
    LPDIRECT3DBASETEXTURE9 pTexture
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pTexture
[in] Texture object. See IDirect3DBaseTexture9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetTexture


ID3DXEffectCompiler::SetValue Method

Get the value of an arbitrary parameter or annotation, including simple types, structs, arrays, strings, shaders and textures. This method can be used in place of nearly all the Setxxx calls in ID3DXBaseEffect.

Syntax

HRESULT SetValue(

    D3DXHANDLE hParameter,
    LPCVOID pData,
    UINT Bytes
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pData
[in] Pointer to a buffer containing data.
Bytes
[in] [in] Number of bytes in the buffer. Pass in D3DX_DEFAULT if you know your buffer is large enough to contain the entire parameter, and you want to skip size validation.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetValue


ID3DXEffectCompiler::SetVector Method

Sets a vector.

Syntax

HRESULT SetVector(

    D3DXHANDLE hParameter,
    CONST D3DXVECTOR4* pVector
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[in] Pointer to a 4-D vector.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the destination vector is smaller than the source vector, the additional components of the source vector will be ignored.

See Also

ID3DXBaseEffect::GetVector


ID3DXEffectCompiler::SetVectorArray Method

Sets an array of vectors.

Syntax

HRESULT SetVectorArray(

    D3DXHANDLE hParameter,
    CONST D3DXVECTOR4* pVector,
    UINT Count
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVector
[in] Array of 4-D floating point vectors.
Count
[in] Number of vectors in the array.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the destination vectors are smaller than the source vectors, the additional components of the source vectors will be ignored.

See Also

ID3DXBaseEffect::GetVectorArray


ID3DXEffectCompiler::SetVertexShader Method

Sets a vertex shader.

Syntax

HRESULT SetVertexShader(

    D3DXHANDLE hParameter,
    LPDIRECT3DVERTEXSHADER9 pVertexShader
);

Parameters

hParameter
[in] Unique identifier. See Handles.
pVertexShader
[in] Vertex shader object. See IDirect3DVertexShader9.

Return Value

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

See Also

ID3DXBaseEffect::GetVertexShader


Flow Control Statement Syntax
Microsoft DirectX 9.0 SDK Update (October 2004)

Flow Control Statement Syntax

Flow-control statements determine which statement block to execute next. There are several flow-control statements including:

  • if statement
  • do statement
  • for statement
  • while statement

Most current vertex and pixel shader hardware is designed to run a shader line by line, executing each instruction once. High-level shader language (HLSL) supports flow control, which includes static branching, predicated instructions, static looping, dynamic branching, and dynamic looping.

The most common branching support in current hardware shading models is static branching. Static branching allows a statement block to be switched on or off based on a Boolean shader constant. This is a convenient method for enabling or disabling code paths. Between draw calls you can decide which features you want to support with the current shader, and then set the Boolean flags required to get that behavior. Now that HLSL supports branching, any statements that are disabled by a Boolean constant are skipped during execution.

The most familiar branching support is dynamic branching. With dynamic branching, the comparison condition resides in a variable, which means that the comparison is done for each vertex or pixel at runtime (as opposed to the comparison occuring at compile time, or between 2 draw calls). The performance hit is the cost of the branch plus the cost of the instructions on the side of the branch taken. Dynamic branching is currently available for vertex shaders. Optimizing shaders that work with these models is similar to optimizing code that runs on a CPU.

if statement

The if statement chooses which statement block to execute next based on the result of a comparison:

if ( (Normal dot LightDirection) > 0 )

The comparison is followed by the statement block:

{
    // face is lit, so add a diffuse color component for example
    ...
}

Remember that a statement block is one or more statements, enclosed in curly braces. The statement block can be expanded up to n statements, as long as you don't exceed the shader instruction slot count.

An if statement can also use an optional else block. If the if expression is true, the code in the statement block associated with the if statement is processed. Otherwise, the statement block associated with the optional else block is processed.

do statement

The do statement executes a statement block, and then evaluates a conditional expression to determine whether to execute the statement block again. This is repeated until the conditional expression fails.

do
{
  // one or more statements
  color /= 2;
}
    while ( color.a > 0.33f )

This code divides the color components by 2, and then checks the resulting alpha component to see if the first statement will be repeated. Each subsequent time that the alpha component is greater than 0.33f, the color components are divided in half. When the alpha component is less than or equal to 0.33f, the while comparison will fail and the program will continue at the next instruction.

This example uses a statement block that has a single statement in it. The statement block can be expanded to n statements.

do  {
    color.r /= 2;
    color.g /= 4;
    color.b /= 8;
    ....  // Other statements
    color.a /= 8;
}
    while ( color.a > 0.33f )

Don't forget to modify the alpha value, either in the statement block or in the comparison statement. Otherwise, you will cause a infinite loop, which will definitely reduce the shader throughput.

for statement

A for statement implements a loop that provides static control over the number of times a statement block will be executed. It contains an initialization expression, a comparison expression, and an increment (or decrement) expression, followed by a statement block.

for ( int i = 0; i < 2; i++ )
{
   // one or more statements
   ...
   statement n;
};

Here is an example that uses a loop to sample a texture over four different sets of texture coordinates.

sampler RenderTarget;
float4 textureCoordinates[4];
float4 outColor[4];

for ( int i = 0; i < 3; i++ )
{
    outColor[i] = tex2D(RenderTarget, textureCoordinates[i]);
}

The statement block is executed each time that the comparison expression succeeds.

while statement

The while statement implements a loop, which evaluates an expression to determine whether to execute a statement block.

while ( color.a > 0.33f )
{
    color /= 2;
}

This code checks to see if the alpha component is greater than 0.33f. For each time that it is, the color components are each divided in half. As soon as alpha is less than or equal to 0.33f, the comparison expression will fail and the program will continue at the next instruction after the statement block.

This example uses a statement block that has a single statement in it.

    color /= 2;

When a single statement is used, the enclosing curly braces are optional. The statement block can be expanded to n statements.

while ( color.a > 0.33f )
{
    color.r /= 2;
    color.g /= 4;
    color.b /= 8;
    ....  // Other statements
    color.a /= 8;
}

Don't forget to modify the alpha value, either in the comparison expression or in the statement block.

Remarks

Curly braces ({}) start and end a statement block. When a statement block uses a single statement, the curly braces are optional. Everyone has their own preference for handling an if statement that encompasses one statement.

if ( some expression )
   color.rgb = tex3D(Sampler, texturecoordinates);

This is equivalent to using the curly braces:

if ( some expression )
{
   color.rgb = tex3D(Sampler, texturecoordinates);
}

Some people find this easier to read.

Previously, using an if statement resulted in assembly-language shader code that implements both the if side and the else side of the code flow. The code is executed linearly and the output results from the side of the if statement that would have been taken. Here is the corresponding HLSL code:

if (Value > 0)
    oPos = Value1;
else
    oPos = Value2;

And here is the assembly code, compiled for vs_1_1:

// Calculate linear interpolate (lerp) value in r0.w
mov r1.w, c2.x
slt r0.w, c3.x, r1.w
// Lerp between value1 and value2
mov r7, -c1
add r2, r7, c0
mad oPos, r0.w, r2, c1

Some hardware allows for either static or dynamic looping, but most require linear execution. On the models that do not support looping, all loops must be unrolled. An example is the DepthOfField Sample sample that uses unrolled loops even for ps_1_1 shaders.


IDirectXFileBinary::GetId Method

Retrieves a pointer to the globally unique identifier (GUID) that identifies a Microsoft DirectX file object. Deprecated.

Syntax

HRESULT GetId(

    LPGUID pGuid
);

Parameters

pGuid
[out, retval] Pointer to a GUID to receive the object's ID. The function will set the GUID to a NULL GUID if the object does not have an ID.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be DXFILEERR_BADVALUE.


IDirectXFileBinary::GetName Method

Retrieves a pointer to a Microsoft DirectX file object's name. Deprecated.

Syntax

HRESULT GetName(

    LPSTR pstrNameBuf,
    LPDWORD pdwBufLen
);

Parameters

pstrNameBuf
[out] Pointer to the buffer in which the DirectX file object's name will be copied. Set to NULL if only the buffer length is needed.
pdwBufLen
[in, out] Pointer to a DWORD specifying the length of the buffer pointed to by pstrNameBuf. The pdwBufLen parameter value will be modified to the buffer length needed to hold the object's name even if pstrNameBuf is NULL. In either case, the function will return DXFILEERR_BADVALUE if the original value of pdwBufLen is not as large as or larger than the length needed to hold the object's name.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC | Memory allocation failed.
DXFILEERR_BADVALUE | Parameter is invalid.


IDirectXFileData::GetId Method

Retrieves a pointer to the globally unique identifier (GUID) that identifies a Microsoft DirectX file object. Deprecated.

Syntax

HRESULT GetId(

    LPGUID pGuid
);

Parameters

pGuid
[out, retval] Pointer to a GUID to receive the object's ID. The function will set the GUID to a NULL GUID if the object does not have an ID.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be DXFILEERR_BADVALUE.


IDirectXFileData::GetName Method

Retrieves a pointer to a Microsoft DirectX file object's name. Deprecated.

Syntax

HRESULT GetName(

    LPSTR pstrNameBuf,
    LPDWORD pdwBufLen
);

Parameters

pstrNameBuf
[out] Pointer to the buffer in which the DirectX file object's name will be copied. Set to NULL if only the buffer length is needed.
pdwBufLen
[in, out] Pointer to a DWORD specifying the length of the buffer pointed to by pstrNameBuf. The pdwBufLen parameter value will be modified to the buffer length needed to hold the object's name even if pstrNameBuf is NULL. In either case, the function will return DXFILEERR_BADVALUE if the original value of pdwBufLen is not as large as or larger than the length needed to hold the object's name.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC | Memory allocation failed.
DXFILEERR_BADVALUE | Parameter is invalid.


IDirectXFileDataReference::GetId Method

Retrieves a pointer to the globally unique identifier (GUID) that identifies a Microsoft DirectX file object. Deprecated.

Syntax

HRESULT GetId(

    LPGUID pGuid
);

Parameters

pGuid
[out, retval] Pointer to a GUID to receive the object's ID. The function will set the GUID to a NULL GUID if the object does not have an ID.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be DXFILEERR_BADVALUE.


IDirectXFileDataReference::GetName Method

Retrieves a pointer to a Microsoft DirectX file object's name. Deprecated.

Syntax

HRESULT GetName(

    LPSTR pstrNameBuf,
    LPDWORD pdwBufLen
);

Parameters

pstrNameBuf
[out] Pointer to the buffer in which the DirectX file object's name will be copied. Set to NULL if only the buffer length is needed.
pdwBufLen
[in, out] Pointer to a DWORD specifying the length of the buffer pointed to by pstrNameBuf. The pdwBufLen parameter value will be modified to the buffer length needed to hold the object's name even if pstrNameBuf is NULL. In either case, the function will return DXFILEERR_BADVALUE if the original value of pdwBufLen is not as large as or larger than the length needed to hold the object's name.

Return Value

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC | Memory allocation failed.
DXFILEERR_BADVALUE | Parameter is invalid.


Tutorial 1: Initialize a Direct3D Application
Microsoft DirectX 9.0 SDK Update (October 2004)

Tutorial 1: Initialize a Direct3D Application

The goal of this tutorial is to initialize a Direct3D application and render an image to the screen. This is the minimum code necessary to start up a Direct3D application. The tutorial is divided into these tasks:

  • Task 1: Create a Direct3D Object
  • Task 2: Choose the Presentation Settings
  • Task 3: Create a Direct3D Device
  • Task 4: Clear the Back Buffer
  • Task 5: Render to the Back Buffer
  • Task 6: Display the Output
  • Task 7: Releasing COM objects

Setup

Preparation

Open CreateDirect3DWindow.cpp inside of your favorite editor.

Description

CreateDirect3DWindow.cpp contains a few functions with the source code demonstrated in this tutorial. You can follow along and compare the tutorial steps with the functions in the source code.

Duration

This tutorial can take as few as 5-10 minutes if you simply follow the steps, but could take longer if you build the tutorial and use the debugger to step through each of the function calls watching the arguments and the return types.

Task 1: Create a Direct3D Object

Preparation

Locate the function InitD3D() in CreateDirect3DWindow.cpp.

Description

Use Direct3DCreate9 to create a pointer to an IDirect3D9 interface. The Microsoft Direct3D object is a Component Object Model (COM) interface. All COM interfaces start with a capital "I", as in "IDirect3D9".

Solution

IDirect3D9* g_pD3D = NULL;
if(NULL == (g_pD3D = Direct3DCreate9(D3D_SDK_VERSION)))
{
  MessageBox(0, L"Direct3DCreate9() failed", L"InitD3D()", MB_OK);
  return E_FAIL;
}

Direct3DCreate9 takes only one parameter, D3D_SDK_VERSION. This version identifier is passed to this function to ensure that an application is built against the correct DirectX header files. If the value passed into Direct3DCreate9 does not match D3D_SDK_VERSION the call will fail, and the function will return NULL. If the function is successful, the return value will be a valid pointer to an IDirect3D9 object.

The MessageBox World Wide Web link function displays a message box if the object creation fails.

Task 2: Choose the Presentation Settings

Preparation

This code is located the function InitD3D() in CreateDirect3DWindow.cpp.

Description

Initialize the presentation settings which control how the rendered output may be sent to the display. We want to set four default conditions:

  • A windowed-mode application. (See Windowed vs Full-Screen Mode).
  • One back buffer. More advanced applications may use multiple back buffers organized in a swap chain to improve performance. (See What Is A Swap Chain? )
  • A data format for the surface the application will render to. (See Surface Formats)
  • A swap effect to control how data is swapped between the front and back buffer.

Solution

D3DPRESENT_PARAMETERS d3dpp = {0};
d3dpp.Windowed = TRUE;
d3dpp.BackBufferCount = 1;
d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;

Task 3: Create a Direct3D Device

Preparation

This code is located the function InitD3D() in CreateDirect3DWindow.cpp.

Description

Use IDirect3D9::CreateDevice to create a Direct3D device.

The most commonly used interface in Direct3D is IDirect3DDevice9. It is the main rendering interface and is commonly called the Direct3D device or render device. The Direct3D device represents a single graphics adapter configured to the application's needs. The device represents the video adapter so we need to tell Direct3D how much work the adapter should do and how much work Direct3D should do.

We have two choices to make that determine where our data will be processed. The vertex data is processed either in software or hardware by setting the vertex processing type. This tutorial uses software vertex processing (specified with D3DCREATE_SOFTWARE_VERTEXPROCESSING), which is best to choose when trying to debug something. The rendering can be done in software of hardware by setting the device type. This tutorial uses hardware accelearation by specifying a HAL device using D3DDEVTYPE_HAL. For more information, see Device Types.

Solution

IDirect3DDevice9*   g_pd3dDevice = NULL;
if(FAILED(g_pD3D->CreateDevice(
  D3DADAPTER_DEFAULT,                  // Primary display adapter ID.
  D3DDEVTYPE_HAL,                      // Use a HAL device.
  hWnd,                                // Window handle.
  D3DCREATE_SOFTWARE_VERTEXPROCESSING, // Vertex processing mode.
  &d3dpp,                              // Presentation parameters.
  &g_pd3dDevice                        // Device to create.
  )))
{
  MessageBox(0, L"Direct3DCreate9() failed", L"InitD3D()", MB_OK);
      return E_FAIL;
}

Task 4: Clear the Back Buffer

Preparation

This code is located the function Render() in CreateDirect3DWindow.cpp.

Description

Call IDirect3DDevice9::Clear to clear the back buffer

By default the back buffer is the current render target. When setting up the presentation parameters for the device, we specified the swap effect to discard the front buffer data. This means after a swap, the back buffer will contain random data, so it needs to be cleared to a known state. The know state could be a single color value, set with the D3DCOLOR_XRGB macro. Color channel data varies from 0 to 255.

Solution

g_pd3dDevice->Clear(
  0,
  NULL,                     // Clear the entire viewport.
  D3DCLEAR_TARGET,          // What surface in the view port to clear.
  D3DCOLOR_XRGB(0, 0, 255), // Color to clear with
  0,                        // Z-Buffer (Not Used)
  0                         // Stencil data (Not Used)
  );

Task 5: Render to the Back Buffer

Preparation

This code is located the function Render() in CreateDirect3DWindow.cpp.

Description

Add IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene calls.

All custom render code should be added to an application between IDirect3DDevice9::BeginScene and IDirect3DDevice9::EndScene.

Solution

if(SUCCEEDED(g_pd3dDevice->BeginScene()))
{
     // Custom rendering code belongs here...

     g_pd3dDevice->EndScene();
}
Tip

Use the SUCCEEDED macro to check the return code. If IDirect3DDevice9::BeginScene fails, an application should not call any rendering methods and should not call IDirect3DDevice9::EndScene.

Task 6: Display the Output

Preparation

This code is located the function Render() in CreateDirect3DWindow.cpp.

Description

Call IDirect3DDevice9::Present to send the render calls to Direct3D.

After the scene is rendered to the back buffer, swap the back buffer to the front buffer to display the image. The entire back buffer (or any rectangular portion of it) can be swapped with the front buffer (or any rectangular portion of it).

Solution

g_pd3dDevice->Present(
  NULL, // Pointer to the source RECT.
  NULL, // Pointer to the destination RECT.
  NULL, // Destination window for present.
  NULL  // Minimal set of pixels to be updated.
  )

Task 7: Releasing COM objects

Preparation

This code is located the function Shutdown() in CreateDirect3DWindow.cpp.

Description

When exiting the application, use the SAFE_RELEASE macro to clean up any COM objects that we have created.

An applications shuts down after a Windows quit message (WM_QUIT) is received by the message processing loop. In response to this message, the application needs to release all COM objects that it created. COM objects should be released in the opposite order from which they were created.

Solution

if(g_pd3dDevice != NULL)
{
    g_pd3dDevice>Release();
    g_pd3dDevice = NULL;
}

if(g_pD3D != NULL)
{
    g_pD3D->Release();
    g_pD3D = NULL;
}

Running the SAFE_RELEASE macro checks the pointer to make sure it is valid before releasing it and setting it to NULL. This code could be replaced with:

    SAFE_RELEASE(g_pd3dDevice);
    SAFE_RELEASE(g_pD3D);


Shader Tutorial 1: Create a Vertex Shader
Microsoft DirectX 9.0 SDK Update (October 2004)

Shader Tutorial 1: Create a Vertex Shader

This tutorial creates a single vertex shader that implements standard lighting and transforms. The shader is compiled and rendered with the Effect system. To understand this tutorial, you should be familiar with writing C functions, declaring HLSL variables (see Variable Declaration Syntax), declaring HLSL functions (see Function Declaration Syntax), and HLSL vector and matrix math (see HLSL Implements Per Component Math Operations).

Duration

This tutorial can take as few as 10-15 minutes if you are familiar with the prerequisites. Otherwise, you may want to start by reading about HLSL data types and matrix math before implementing this vertex shader.

  • Step 1: Identify Shader Inputs
  • Step 2: Identify Shader Outputs
  • Step 3: Implement The Position Transform
  • Step 4: Implement Ambient, Diffuse and Specular Lighting
  • Step 5: Setup Default Values for the Uniform Shader Variables
  • Step 6: Implement the Effect Technique
  • Step 7: Compile The Effect
  • Step 8: Render The Shader

Step 1: Identify Shader Inputs

Description

Declare a vertex shader function that:

  • Returns nothing.
  • Takes a three component input position.
  • Takes a three component input normal.

Solution

void VertexShader1(
    float3 InPos  : POSITION,
    float3 InNormal : NORMAL
    )
{
  ...
}

The shader is named VertexShader1, which is an arbitrary function name. At this point, the function has no body so it returns nothing. The function will take two inputs, each of which is a three component vector containing x,y,z data. Both inputs have semantics attached to them (the string after the semicolon - see Varying Shader Inputs and Semantics). Semantics attach pipeline data to shader inputs. In this function the two input semantics specify that the shader inputs are position and normal data.

Step 2: Identify Shader Outputs

Description

Implement a return type that contains three outputs:

  • A four component position.
  • A four component diffuse color.
  • A four component specular color.

Solution

struct VS_OUTPUT
{
    float4 Position  : POSITION;
    float4 Diffuse   : COLOR0;
    float4 Specular  : COLOR1;
};

In C, a function returns a single type. HLSL functions can return more than one type by declaring a structure and using it for the return type of the function. This structure contains three members: one for position, one for diffuse color and one for specular color. Each member is a four component type. You can think of the position data as x,y,z,w data, and the color data as r,g,b,a data. Each member also has a semantic attached so that the vertex shader outputs can be attached to the next pipeline stage (primitive processing), or a pixel shader. Vertex shader output semantics are defined in Shader Semantic Syntax.

Step 3: Implement The Position Transform

Description

Implement the following in the shader body:

  • Calculate the transformed position. This means the position data needs to be transformed from model space to projection space.
  • Calculate standard N dot L lighting that takes into account ambient, diffuse and specular terms, as well as material colors.

Solution

VS_OUTPUT VS(
    float3 InPos  : POSITION,
    float3 InNormal : NORMAL
    )
{
    VS_OUTPUT Out = (VS_OUTPUT)0;

    // Transform the position
    float3 Pos = mul(float4(InPos, 1), World);

    Out.Pos  = mul(float4(Pos, 1), ViewProjection);

    return Out;
}

The position data is in model space (object space) when the shader runs. It needs to be transformed into projection space. This shader implements the transform in two steps: a transform from model space to world space followed by a transform from world space to projection space.

Each transform is done with a matrix multiply that combines a 1x4 vector and a 4x3 matrix. In the code, notice the:

    float4(InPos, 1);

This is a float4 type constuctor. The constructor which initializes the first three values to the x,y,z values from InPos, and sets the fourth component to a 1. This constructor converts a 1x3 vector to a 1x4 vector to prepare for the matrix multiply. The matrix multiply returns a 1x3 result.

Every vertex shader must at a minimum, implement a position transform. Anything else you implement in a vertex shader is optional.

Step 4: Implement Ambient, Diffuse and Specular Lighting

Description

Implement calculations for ambient, diffuse, specular lighting equations that take into account:

  • The light color.
  • The material color.
  • The normal vector.
  • The view vector.

Solution

VS_OUTPUT VS(
    float3 InPos  : POSITION,
    float3 InNormal : NORMAL
    )
{
    VS_OUTPUT Out = (VS_OUTPUT)0;

    float3 Normal = normalize(mul(InNormal, (float3x3)World));
    float3 EyeToVertex = normalize(Pos - CameraPos);

    float4 Amb  = CalcAmbient();
    float4 Diff = CalcDiffuse(Normal, -DirFromLight);
    float4 Spec = CalcSpecular(Normal, DirFromLight, EyeToVertex);

    Out.Diff = Amb + Diff ;
    Out.Spec = Spec;

    return Out;
}

The lighting calculations for ambient, diffuse and specular lighting are done with three helper functions: CalcAmbient, CalcDiffuse, and CalcSpecular. Since some of these functions require a normal, and others require the view vector (EyeToVertex), these vectors are transformed into world space before the helper functions are called.

When the normal is calculated, it is tranformed with the mul function just like the position was transformed. Additionally, the normalize function is used to convert the result into a normalized vector.

The helper functions for each of the lighting components are shown next:

float4 CalcAmbient()
{
    return LightAmbientIntensity * MaterialAmbientIntensity;
}

float4 CalcDiffuse(float3 Normal, float3 DirToLight)
{
    return MaterialDiffuseColor * LightDiffuseColor * max(0, dot(Normal, DirToLight));
}

float4 CalcSpecular(float3 Normal, float3 DirFromLight, float3 EyeToVertex)
{
    float3 R = normalize(reflect(DirFromLight, Normal));
    return MaterialSpecularColor * LightSpecularColor * pow(max(0, dot(R, -EyeToVertex)), MaterialSpecularPower/4);
}

The ambient helper simply combines the ambient light intensity with the material ambient intensity. Each function returns a four component value which can be thought of as r,g,b,a data. The diffuse helper uses the dot function to calculate the N dot L dot, which is combined with the light and the material color. The diffuse helper also uses the max function to clamp the result. This is because a negative result is light that occurs on the backside of an object. By clamping the results to only be positive, we do not waste time calculating light we cannot see.

The specular helper uses the pow function to calculate the specular highlights. This requires a reflection vector which is calculated first. Then the helper function combines the specular calculation with the light and the material color. The specular power factor is divided by 4, which is a number that you can modify to adjust the size of your specular highlights.

Step 5: Setup Default Values for the Uniform Shader Variables

Description

Implement default values for the following shader constants:

  • The light direction.
  • The light color.
  • The material color.
  • The world and view-projection matrices.
  • The camera position.

Solution

float3 DirFromLight < string UIDirectional = "Light Direction"; > =
  {0.577, -0.577, 0.577};

float4 LightAmbientIntensity  = { 0.8f, 0.8f, 0.8f, 1.0f };
float4 LightDiffuseColor      = { 1.0f, 0.9f, 0.8f, 1.0f };
float4 LightSpecularColor     = { 1.0f, 1.0f, 1.0f, 1.0f };

float4 MaterialAmbientIntensity = { 0.5f, 0.5f, 0.5f, 1.0f };
float4 MaterialDiffuseColor     = { 0.4f, 0.4f, 0.4f, 1.0f };
float4 MaterialSpecularColor    = { 0.1f, 0.1f, 0.1f, 1.0f };
int    MaterialSpecularPower    = 32;

float4x3 World          : WORLD;
float4x3 View           : VIEW;
float4x4 ViewProjection : VIEWPROJECTION;
float3 CameraPos        : CAMERAPOSITION;

Uniform shader variables are variables that are set once for each invocation of the shader. Every vertex processed by the shader sees the same value for each usiform shader constant.

In this tutorial, each constant is declared like a global variable in an effect file. Some variables have default values explicitly declared in the effect file. Those that don't will need to be initialized by the application before the shader is rendered.

This is an example of a variable, that is a uniform constant, which contains an explicit declaration:

float3 DirFromLight < string UIDirectional = "Light Direction"; > =
  {0.577, -0.577, 0.577};

The DirFromLight will be initialized to the values shown here when the application calls Effect->SetDefaults. This variable uses an annotation which is the declaration inside of the angle brackets. The annotation can be used by the application to find out more about the parameter DirFromLight.

This variable contains explicit default values only. It is also initialized when calling Effect->SetDefaults.

float4 LightAmbientIntensity  = { 0.8f, 0.8f, 0.8f, 1.0f };

This variable contains explicit default values only. It is also initialized when calling Effect->SetDefaults.

This uniform shader constant has no explicit values declared, but does have a semantic attached to it:

float4x3 World          : WORLD;

Since there are no values, the matrix will need to be initialized by calling Effect->SetMatrix in the application. The semantic attached means that this variable is automatically tied to the world transform in the pipeline. Semantics are used to attach shader inputs and outputs to each other or to the pipeline.

Step 6: Implement the Effect Technique

Description

Implement a technique that:

  • Contains one technique with one pass.
  • Compiles the vertex shader for a vs_2_0 target.

Solution

technique TransformAndLitVertices
{
    pass P0
    {
        VertexShader = compile vs_2_0 VertexShader1();
    }
}

An effect contains one of more techniques. Each technique contains one or more passes. Each pass contains the state that uniquely identifies how to render a particular effect.

In this case, the technique implements one pass which contains a single shader. The shader contains the minimum state necessay to implement an effect that performs transformation and lighting. The pass contains a single compile statement that identifies the compile target and the name of the shader function to compile. When the shader is successfully compiled, a VertexShader object is generated.

Step 7: Compile The Effect

Description

Implement calculations for ambient, diffuse, specular lighting equations that take into account:

  • The light color.
  • The material color.
  • The normal vector.
  • The view vector.

Solution

ID3DXEffect*            g_pEffect = NULL;       // D3DX effect interface

    // Read the D3DX effect file
    WCHAR str[MAX_PATH];
    V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"BasicHLSL.fx" ) );

    DWORD dwShaderFlags = 0;
    #ifdef DEBUG_VS
        dwShaderFlags |= D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT;
    #endif
    #ifdef DEBUG_PS
        dwShaderFlags |= D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT;
    #endif

    // Preshaders are parts of the shader that the effect system pulls out of the
    // shader and runs on the host CPU. They should be used if you are GPU limited.
    // The D3DXSHADER_NO_PRESHADER flag disables preshaders.
    if( !g_bEnablePreshader )
        dwShaderFlags |= D3DXSHADER_NO_PRESHADER;

    // Read the D3DX effect file
    WCHAR str[MAX_PATH];
    V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"BasicHLSL.fx" ) );

    // If this fails, there should be debug output as to
    // why the .fx file failed to compile
    V_RETURN( D3DXCreateEffectFromFile( pd3dDevice, str, NULL, NULL, dwShaderFlags, NULL, &g_pEffect, NULL ) );

Step 8: Render The Shader

Description

Implement calculations for ambient, diffuse, specular lighting equations that take into account:

  • The light color.
  • The material color.
  • The normal vector.
  • The view vector.

Solution

IDirect3DTexture9*      g_pMeshTexture = NULL;  // Mesh texture

    V_RETURN( D3DXCreateTextureFromFileEx( pd3dDevice, str, D3DX_DEFAULT, D3DX_DEFAULT,
                                       D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED,
                                       D3DX_DEFAULT, D3DX_DEFAULT, 0,
                                       NULL, NULL, &g_pMeshTexture ) );

    // Set effect variables as needed
    D3DXCOLOR colorMtrlDiffuse(1.0f, 1.0f, 1.0f, 1.0f);
    D3DXCOLOR colorMtrlAmbient(0.35f, 0.35f, 0.35f, 0);

    V_RETURN( g_pEffect->SetValue("g_MaterialAmbientColor", &colorMtrlAmbient, sizeof(D3DXCOLOR) ) );
    V_RETURN( g_pEffect->SetValue("g_MaterialDiffuseColor", &colorMtrlDiffuse, sizeof(D3DXCOLOR) ) );
    V_RETURN( g_pEffect->SetTexture( "g_MeshTexture", g_pMeshTexture) );

void CALLBACK OnFrameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime )
{
    HRESULT hr;
    D3DXMATRIXA16 mWorldViewProjection;
    D3DXVECTOR3 vLightDir[MAX_LIGHTS];
    D3DXCOLOR   vLightDiffuse[MAX_LIGHTS];
    UINT iPass, cPasses;
    D3DXMATRIXA16 mWorld;
    D3DXMATRIXA16 mView;
    D3DXMATRIXA16 mProj;

    // Clear the render target and the zbuffer
    V( pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DXCOLOR(0.0f,0.25f,0.25f,0.55f), 1.0f, 0) );

    // Render the scene
    if( SUCCEEDED( pd3dDevice->BeginScene() ) )
    {
        // Get the projection & view matrix from the camera class
        mWorld = *g_Camera.GetWorldMatrix();
        mProj = *g_Camera.GetProjMatrix();
        mView = *g_Camera.GetViewMatrix();

        mWorldViewProjection = mWorld * mView * mProj;

        // Render the light spheres so the user can
        // visually see the light dir
        for( int i=0; iSetValue( "g_LightDir", &vLightDir, sizeof(D3DXVECTOR3)*MAX_LIGHTS ) );
        V( g_pEffect->SetValue( "g_LightDiffuse", &vLightDiffuse, sizeof(D3DXVECTOR4)*MAX_LIGHTS ) );

        // Update the effect's variables.  Instead of using strings, it would
        // be more efficient to cache a handle to the parameter by calling
        // ID3DXEffect::GetParameterByName
        V( g_pEffect->SetMatrix( "g_mWorldViewProjection", &mWorldViewProjection ) );
        V( g_pEffect->SetMatrix( "g_mWorld", &mWorld ) );
        V( g_pEffect->SetFloat( "g_fTime", (float)fTime ) );

        D3DXCOLOR vWhite = D3DXCOLOR(1,1,1,1);
        V( g_pEffect->SetValue("g_MaterialDiffuseColor", &vWhite, sizeof(D3DXCOLOR) ) );
        V( g_pEffect->SetFloat( "g_fTime", (float)fTime ) );
        V( g_pEffect->SetInt( "g_nNumLights", g_nNumActiveLights ) );

        // Render the scene with this technique
        // as defined in the .fx file
        switch( g_nNumActiveLights )
        {
            case 1: V( g_pEffect->SetTechnique( "RenderSceneWithTexture1Light" ) ); break;
            case 2: V( g_pEffect->SetTechnique( "RenderSceneWithTexture2Light" ) ); break;
            case 3: V( g_pEffect->SetTechnique( "RenderSceneWithTexture3Light" ) ); break;
        }

        // Apply the technique contained in the effect
        V( g_pEffect->Begin(&cPasses, 0) );

        for (iPass = 0; iPass < cPasses; iPass++)
        {
            V( g_pEffect->BeginPass(iPass) );

            // The effect interface queues up the changes and performs them
            // with the CommitChanges call. You do not need to call CommitChanges if
            // you are not setting any parameters between the BeginPass and EndPass.
            // V( g_pEffect->CommitChanges() );

            // Render the mesh with the applied technique
            V( g_pMesh->DrawSubset(0) );

            V( g_pEffect->EndPass() );
        }
        V( g_pEffect->End() );

        g_HUD.OnRender( fElapsedTime );
        g_SampleUI.OnRender( fElapsedTime );

        RenderText( fTime );

        V( pd3dDevice->EndScene() );
    }
}